adk_graph/time_travel.rs
1//! Time-travel debugging for graph execution history.
2//!
3//! This module provides [`TimeTravelHandle`] for navigating, inspecting, and forking
4//! graph execution history. It works with any [`Checkpointer`] implementation to
5//! inspect past execution steps, resume from arbitrary points, and create divergent
6//! execution branches.
7//!
8//! # Overview
9//!
10//! Time-travel debugging allows you to:
11//! - List all checkpointed steps for a thread
12//! - Resume execution from any historical step
13//! - Fork a thread at a specific step into a new independent thread
14//! - Fork from a checkpoint with edited state, recording the fork's lineage
15//! ([`fork_thread`], [`TimeTravelHandle::fork`]; spec 3.3 §12)
16//! - Replay execution between two steps, collecting intermediate states
17//!
18//! # Example
19//!
20//! ```rust,ignore
21//! use adk_graph::prelude::*;
22//! use adk_graph::time_travel::{TimeTravelHandle, StepInfo};
23//!
24//! // Build and execute a graph
25//! let graph = StateGraph::new(StateSchema::simple(&["data"]))
26//! .add_node("process", process_fn)
27//! .add_edge(START, "process")
28//! .add_edge("process", END)
29//! .compile(Some(checkpointer.clone()));
30//!
31//! // Get a time-travel handle for a thread
32//! let handle = graph.time_travel("thread_1").unwrap();
33//!
34//! // List all steps
35//! let steps = handle.steps().await?;
36//! for step in &steps {
37//! println!("Step {}: checkpoint={}", step.step, step.checkpoint_id);
38//! }
39//!
40//! // Fork at step 2 into a new thread
41//! handle.fork_at(2, "thread_1_fork").await?;
42//!
43//! // Replay steps 0 through 3
44//! let states = handle.state_history(0, Some(3)).await?;
45//! ```
46
47use std::collections::BTreeMap;
48use std::sync::Arc;
49
50use serde::Serialize;
51use serde_json::Value;
52use thiserror::Error;
53
54use crate::checkpoint::Checkpointer;
55use crate::error::{GraphError, Result};
56use crate::graph::CompiledGraph;
57use crate::node::ExecutionConfig;
58use crate::record::{LINEAGE_METADATA_KEY, Lineage};
59use crate::state::{Checkpoint, State, StateSchema};
60
61/// Information about a single execution step in the graph history.
62///
63/// Each `StepInfo` corresponds to a checkpoint saved after a super-step
64/// in the Pregel execution model. It provides metadata useful for
65/// navigating and understanding the execution timeline.
66///
67/// # Example
68///
69/// ```rust,ignore
70/// use adk_graph::time_travel::StepInfo;
71///
72/// let step = StepInfo {
73/// step: 3,
74/// checkpoint_id: "abc-123".to_string(),
75/// timestamp: Some("2025-01-15T10:30:00Z".to_string()),
76/// pending_nodes: vec!["transform".to_string()],
77/// state_keys: vec!["data".to_string(), "result".to_string()],
78/// };
79///
80/// println!("Step {} has {} pending nodes", step.step, step.pending_nodes.len());
81/// ```
82#[derive(Debug, Clone, Serialize)]
83pub struct StepInfo {
84 /// The step number in the execution sequence (0-indexed).
85 pub step: usize,
86 /// The unique checkpoint identifier for this step.
87 pub checkpoint_id: String,
88 /// ISO 8601 timestamp when this step was checkpointed, if available.
89 pub timestamp: Option<String>,
90 /// Node names that were pending execution at this step.
91 pub pending_nodes: Vec<String>,
92 /// State keys that were present at this step.
93 pub state_keys: Vec<String>,
94}
95
96/// Handle for time-travel operations on a graph thread.
97///
98/// `TimeTravelHandle` provides methods to navigate, replay, and fork
99/// graph execution history. It holds a reference to the compiled graph
100/// and uses the associated checkpointer to access historical state.
101///
102/// Create a handle via [`CompiledGraph::time_travel`].
103///
104/// # Example
105///
106/// ```rust,ignore
107/// use adk_graph::prelude::*;
108/// use adk_graph::time_travel::TimeTravelHandle;
109///
110/// let graph = StateGraph::new(StateSchema::simple(&["count"]))
111/// .add_node("increment", increment_fn)
112/// .add_edge(START, "increment")
113/// .add_edge("increment", END)
114/// .compile(Some(checkpointer.clone()));
115///
116/// // Create a time-travel handle
117/// let handle = graph.time_travel("my_thread");
118///
119/// // Inspect execution history
120/// let steps = handle.steps().await?;
121/// println!("Thread has {} steps", steps.len());
122///
123/// // Fork at step 1 to explore an alternative path
124/// handle.fork_at(1, "alternative_thread").await?;
125/// ```
126pub struct TimeTravelHandle<'g> {
127 /// Reference to the compiled graph for re-execution in `resume_from`.
128 pub(crate) graph: &'g CompiledGraph,
129 /// The thread identifier whose history is being navigated.
130 pub(crate) thread_id: String,
131 /// The checkpointer used to load and save checkpoints.
132 pub(crate) checkpointer: Arc<dyn Checkpointer>,
133}
134
135impl<'g> TimeTravelHandle<'g> {
136 /// Create a new `TimeTravelHandle` for the given thread.
137 ///
138 /// # Arguments
139 ///
140 /// * `graph` - Reference to the compiled graph
141 /// * `thread_id` - The thread whose history to navigate
142 /// * `checkpointer` - The checkpointer for accessing historical state
143 ///
144 /// # Example
145 ///
146 /// ```rust,ignore
147 /// use adk_graph::time_travel::TimeTravelHandle;
148 ///
149 /// let handle = TimeTravelHandle::new(&graph, "thread_1", checkpointer.clone());
150 /// ```
151 pub fn new(
152 graph: &'g CompiledGraph,
153 thread_id: &str,
154 checkpointer: Arc<dyn Checkpointer>,
155 ) -> Self {
156 Self { graph, thread_id: thread_id.to_string(), checkpointer }
157 }
158
159 /// List all checkpointed steps for this thread, ordered by step number.
160 ///
161 /// Returns a [`StepInfo`] for each checkpoint, providing metadata about
162 /// the execution state at that point in time.
163 ///
164 /// # Errors
165 ///
166 /// Returns [`GraphError`] if the checkpointer fails to list checkpoints.
167 ///
168 /// # Example
169 ///
170 /// ```rust,ignore
171 /// let handle = graph.time_travel("thread_1").unwrap();
172 /// let steps = handle.steps().await?;
173 ///
174 /// for step in &steps {
175 /// println!(
176 /// "Step {}: {} (pending: {:?})",
177 /// step.step, step.checkpoint_id, step.pending_nodes
178 /// );
179 /// }
180 /// ```
181 pub async fn steps(&self) -> Result<Vec<StepInfo>> {
182 let checkpoints = self.checkpointer.list(&self.thread_id).await?;
183 let mut steps: Vec<StepInfo> = checkpoints
184 .into_iter()
185 .map(|cp| StepInfo {
186 step: cp.step,
187 checkpoint_id: cp.checkpoint_id,
188 timestamp: Some(cp.created_at.to_rfc3339()),
189 pending_nodes: cp.pending_nodes,
190 state_keys: cp.state.keys().cloned().collect(),
191 })
192 .collect();
193 steps.sort_by_key(|s| s.step);
194 Ok(steps)
195 }
196
197 /// Resume graph execution from the checkpoint at the specified step.
198 ///
199 /// Loads the state from the checkpoint at `step` and re-executes the graph
200 /// from that point forward using the provided execution configuration.
201 ///
202 /// # Arguments
203 ///
204 /// * `step` - The step number to resume from
205 /// * `config` - Execution configuration for the resumed run
206 ///
207 /// # Errors
208 ///
209 /// Returns [`GraphError`] if:
210 /// - No checkpoint exists at the specified step
211 /// - The graph execution fails after resuming
212 ///
213 /// # Example
214 ///
215 /// ```rust,ignore
216 /// let handle = graph.time_travel("thread_1").unwrap();
217 ///
218 /// // Resume from step 3
219 /// let config = ExecutionConfig::new("thread_1");
220 /// let final_state = handle.resume_from(3, config).await?;
221 /// println!("Resumed execution produced: {:?}", final_state);
222 /// ```
223 pub async fn resume_from(&self, step: usize, config: ExecutionConfig) -> Result<State> {
224 // List all checkpoints for this thread
225 let checkpoints = self.checkpointer.list(&self.thread_id).await?;
226
227 // Find the checkpoint at the specified step
228 let checkpoint = checkpoints.into_iter().find(|cp| cp.step == step).ok_or_else(|| {
229 GraphError::CheckpointError(format!(
230 "no checkpoint found at step {step} for thread '{}'",
231 self.thread_id
232 ))
233 })?;
234
235 // Create an ExecutionConfig that resumes from this checkpoint
236 let mut resume_config =
237 ExecutionConfig::new(&config.thread_id).with_resume_from(&checkpoint.checkpoint_id);
238 resume_config.recursion_limit = config.recursion_limit;
239
240 // Invoke the graph with the checkpoint's state — the executor will
241 // restore state from the checkpoint and continue execution from there
242 self.graph.invoke(State::new(), resume_config).await
243 }
244
245 /// Fork the thread at a specific step into a new independent thread.
246 ///
247 /// Loads the checkpoint at `step` and saves it under `new_thread_id`,
248 /// creating a new execution branch. The original thread remains unchanged.
249 /// The fork keeps the arrivals of joins still waiting and records its
250 /// [`Lineage`]; see [`fork_thread`] for what else it carries.
251 ///
252 /// # Arguments
253 ///
254 /// * `step` - The step number to fork from
255 /// * `new_thread_id` - The identifier for the new forked thread
256 ///
257 /// # Errors
258 ///
259 /// Returns [`GraphError`] if:
260 /// - No checkpoint exists at the specified step
261 /// - The checkpointer fails to save the forked checkpoint
262 ///
263 /// # Example
264 ///
265 /// ```rust,ignore
266 /// let handle = graph.time_travel("thread_1").unwrap();
267 ///
268 /// // Fork at step 2 to explore an alternative execution path
269 /// handle.fork_at(2, "thread_1_experiment").await?;
270 ///
271 /// // The original thread_1 is unaffected
272 /// let original_steps = handle.steps().await?;
273 /// ```
274 pub async fn fork_at(&self, step: usize, new_thread_id: &str) -> Result<()> {
275 // List all checkpoints for this thread
276 let checkpoints = self.checkpointer.list(&self.thread_id).await?;
277
278 // Find the checkpoint at the specified step
279 let checkpoint = checkpoints.into_iter().find(|cp| cp.step == step).ok_or_else(|| {
280 GraphError::CheckpointError(format!(
281 "no checkpoint found at step {step} for thread '{}'",
282 self.thread_id
283 ))
284 })?;
285
286 // Clone the checkpoint under the new thread_id, after its newest.
287 let version =
288 self.checkpointer.load(new_thread_id).await?.map_or(1, |newest| newest.version + 1);
289 let forked =
290 forked_checkpoint(&checkpoint, new_thread_id, version, &BTreeMap::new(), true)?;
291
292 // Save the forked checkpoint
293 self.checkpointer.save(&forked).await?;
294 Ok(())
295 }
296
297 /// Returns the stored state at each checkpointed step in a range.
298 ///
299 /// This **reads** checkpoints; it does not execute anything. No node runs, no
300 /// event is regenerated, and no side effect is repeated — the states returned are
301 /// the snapshots that were saved when the graph originally ran. Use it to inspect
302 /// how state evolved, not to reproduce a decision.
303 ///
304 /// To re-run from a point in history, fork that checkpoint with `fork_at`
305 /// and invoke the graph on the forked thread.
306 ///
307 /// # Arguments
308 ///
309 /// * `from_step` - First step to include
310 /// * `to_step` - Last step to include, or `None` for the last checkpointed step
311 ///
312 /// # Errors
313 ///
314 /// Returns [`GraphError`] when no checkpoint exists at `from_step`.
315 ///
316 /// # Example
317 ///
318 /// ```rust,ignore
319 /// let handle = graph.time_travel("thread_1").unwrap();
320 ///
321 /// // The stored state at steps 1 through 4
322 /// let transitions = handle.state_history(1, Some(4)).await?;
323 /// for (step, state) in &transitions {
324 /// println!("Step {}: {:?}", step, state.keys().collect::<Vec<_>>());
325 /// }
326 ///
327 /// // From step 2 to the last checkpoint
328 /// let all_remaining = handle.state_history(2, None).await?;
329 /// ```
330 pub async fn state_history(
331 &self,
332 from_step: usize,
333 to_step: Option<usize>,
334 ) -> Result<Vec<(usize, State)>> {
335 // List all checkpoints for this thread
336 let mut checkpoints = self.checkpointer.list(&self.thread_id).await?;
337
338 // Sort by step to ensure correct ordering
339 checkpoints.sort_by_key(|cp| cp.step);
340
341 // Filter to checkpoints in the requested range
342 let results: Vec<(usize, State)> = checkpoints
343 .into_iter()
344 .filter(|cp| cp.step >= from_step && to_step.is_none_or(|end| cp.step <= end))
345 .map(|cp| (cp.step, cp.state))
346 .collect();
347
348 // Verify that from_step exists in the results
349 if results.is_empty() || results[0].0 != from_step {
350 return Err(GraphError::CheckpointError(format!(
351 "no checkpoint found at step {from_step} for thread '{}'",
352 self.thread_id
353 )));
354 }
355
356 Ok(results)
357 }
358}
359
360impl TimeTravelHandle<'_> {
361 /// Forks this thread at the checkpoint `spec.from`, with edits checked against the
362 /// graph's declared channels (spec 3.3 §12).
363 ///
364 /// See [`fork_thread`].
365 ///
366 /// # Errors
367 ///
368 /// Returns [`ForkError::OtherThread`] when the checkpoint belongs to another thread,
369 /// and every error [`fork_thread`] returns.
370 ///
371 /// # Example
372 ///
373 /// ```
374 /// use adk_graph::checkpoint::{Checkpointer, MemoryCheckpointer};
375 /// use adk_graph::edge::{END, START};
376 /// use adk_graph::graph::StateGraph;
377 /// use adk_graph::node::{ExecutionConfig, NodeOutput};
378 /// use adk_graph::state::State;
379 /// use adk_graph::time_travel::ForkSpec;
380 /// use serde_json::json;
381 /// use std::sync::Arc;
382 ///
383 /// # #[tokio::main(flavor = "current_thread")]
384 /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
385 /// let checkpointer = Arc::new(MemoryCheckpointer::new());
386 /// let graph = StateGraph::with_channels(&["note", "done"])
387 /// .add_node_fn("draft", |_ctx| async { Ok(NodeOutput::new().with_update("note", json!("v1"))) })
388 /// .add_node_fn("send", |_ctx| async { Ok(NodeOutput::new().with_update("done", json!(true))) })
389 /// .add_edge(START, "draft")
390 /// .add_edge("draft", "send")
391 /// .add_edge("send", END)
392 /// .compile()?
393 /// .with_checkpointer_arc(checkpointer.clone());
394 /// graph.invoke(State::new(), ExecutionConfig::new("t1")).await?;
395 ///
396 /// let after_draft = checkpointer.list("t1").await?[0].checkpoint_id.clone();
397 /// let fork = graph
398 /// .time_travel("t1")?
399 /// .fork(ForkSpec::new(&after_draft, "t1-fork").set("note", json!("v2")))
400 /// .await?;
401 /// assert_eq!(fork.state["note"], json!("v2"));
402 /// assert_eq!(fork.lineage()?.map(|l| l.edited), Some(vec!["note".to_string()]));
403 /// # Ok(())
404 /// # }
405 /// ```
406 pub async fn fork(&self, spec: ForkSpec) -> std::result::Result<Checkpoint, ForkError> {
407 let source = self
408 .checkpointer
409 .load_by_id(&spec.from)
410 .await?
411 .ok_or_else(|| ForkError::UnknownCheckpoint { id: spec.from.clone() })?;
412 if source.thread_id != self.thread_id {
413 return Err(ForkError::OtherThread {
414 id: spec.from,
415 thread: source.thread_id,
416 expected: self.thread_id.clone(),
417 });
418 }
419 fork_thread(self.checkpointer.as_ref(), spec, Some(self.graph.schema())).await
420 }
421}
422
423/// What to fork, where to, and which state to overwrite (spec 3.3 §12).
424///
425/// # Example
426///
427/// ```
428/// use adk_graph::time_travel::ForkSpec;
429/// use serde_json::json;
430///
431/// let spec = ForkSpec::new("c1", "t1-fork").set("note", json!("re-run for audit"));
432/// assert_eq!(spec.set["note"], json!("re-run for audit"));
433/// ```
434#[derive(Debug, Clone, PartialEq, Default)]
435pub struct ForkSpec {
436 /// The id of the checkpoint to fork from: the completed checkpoint of a step.
437 pub from: String,
438 /// The thread the fork is written to; it must have no checkpoints yet.
439 pub new_thread_id: String,
440 /// Channels to overwrite in the fork, whole: no reducer is applied.
441 pub set: BTreeMap<String, Value>,
442}
443
444impl ForkSpec {
445 /// A fork of checkpoint `from` into `new_thread_id`, with no edits.
446 pub fn new(from: impl Into<String>, new_thread_id: impl Into<String>) -> Self {
447 Self { from: from.into(), new_thread_id: new_thread_id.into(), set: BTreeMap::new() }
448 }
449
450 /// Overwrites channel `key` with `value` in the fork.
451 #[must_use]
452 pub fn set(mut self, key: impl Into<String>, value: Value) -> Self {
453 self.set.insert(key.into(), value);
454 self
455 }
456}
457
458/// Why a fork was refused (spec 3.3 §12).
459///
460/// Every message starts with the stable [`code`](Self::code).
461///
462/// # Example
463///
464/// ```
465/// use adk_graph::time_travel::ForkError;
466///
467/// let error = ForkError::NothingToRun { id: "c3".to_string() };
468/// assert_eq!(error.code(), "fork.nothing_to_run");
469/// assert!(error.to_string().starts_with("fork.nothing_to_run:"));
470/// ```
471#[derive(Debug, Error)]
472#[non_exhaustive]
473pub enum ForkError {
474 /// No checkpoint has the id.
475 #[error("fork.unknown_checkpoint: no checkpoint '{id}'")]
476 UnknownCheckpoint {
477 /// The id asked for.
478 id: String,
479 },
480 /// The checkpoint belongs to another thread than the handle's.
481 #[error("fork.other_thread: checkpoint '{id}' belongs to thread '{thread}', not '{expected}'")]
482 OtherThread {
483 /// The id asked for.
484 id: String,
485 /// The thread the checkpoint belongs to.
486 thread: String,
487 /// The handle's thread.
488 expected: String,
489 },
490 /// The checkpoint is a pause: a node of its step waits.
491 #[error(
492 "fork.paused: checkpoint '{id}' is a pause, where a node waits mid-step; fork from the \
493 completed checkpoint of its step"
494 )]
495 Paused {
496 /// The id asked for.
497 id: String,
498 },
499 /// The checkpoint ends its run, so nothing would run in the fork.
500 #[error(
501 "fork.nothing_to_run: nothing runs after the last step: checkpoint '{id}' has no pending nodes"
502 )]
503 NothingToRun {
504 /// The id asked for.
505 id: String,
506 },
507 /// An edit names a channel the graph does not declare.
508 #[error("fork.undeclared_channel: '{key}' is not a channel of this graph")]
509 UndeclaredChannel {
510 /// The edited key.
511 key: String,
512 },
513 /// An unchecked edit names a key the checkpoint's state does not hold.
514 #[error(
515 "fork.unknown_key: '{key}' is not a key of this checkpoint; without the graph's channels \
516 only existing keys can be edited"
517 )]
518 UnknownKey {
519 /// The edited key.
520 key: String,
521 },
522 /// The target thread already has checkpoints.
523 #[error(
524 "fork.thread_exists: thread '{thread}' already has checkpoints; fork into a new thread"
525 )]
526 ThreadExists {
527 /// The target thread.
528 thread: String,
529 },
530 /// The checkpointer failed.
531 #[error(transparent)]
532 Checkpointer(#[from] GraphError),
533}
534
535impl ForkError {
536 /// The stable code this refusal's message starts with; `fork.checkpointer` for a
537 /// checkpointer failure.
538 pub fn code(&self) -> &'static str {
539 match self {
540 Self::UnknownCheckpoint { .. } => "fork.unknown_checkpoint",
541 Self::OtherThread { .. } => "fork.other_thread",
542 Self::Paused { .. } => "fork.paused",
543 Self::NothingToRun { .. } => "fork.nothing_to_run",
544 Self::UndeclaredChannel { .. } => "fork.undeclared_channel",
545 Self::UnknownKey { .. } => "fork.unknown_key",
546 Self::ThreadExists { .. } => "fork.thread_exists",
547 Self::Checkpointer(_) => "fork.checkpointer",
548 }
549 }
550}
551
552impl From<ForkError> for GraphError {
553 fn from(error: ForkError) -> Self {
554 match error {
555 ForkError::Checkpointer(error) => error,
556 refusal => GraphError::CheckpointError(refusal.to_string()),
557 }
558 }
559}
560
561/// Forks the checkpoint `spec.from` into the new thread `spec.new_thread_id`, with the
562/// channels in `spec.set` overwritten (spec 3.3 §12).
563///
564/// | Carried | Dropped |
565/// |---------|---------|
566/// | State (with the edits), step, pending nodes, the arrivals of joins still waiting, each governed node's completed runs | The retry budget, the answered gate, pending writes, finished children, the paused marker and its waiting requests, the run and its step records |
567///
568/// A pause asks again in the fork, and the fork opens its own run when it first runs. The
569/// fork records its [`Lineage`]: `root` is the source's root, else the source's thread.
570/// Edits overwrite whole channels and never go through reducers. With `schema`, each
571/// edited key must be a declared channel and the lineage records `checked: true`;
572/// without one, only keys the source state holds are accepted and it records
573/// `checked: false`. The source thread is never written.
574///
575/// # Errors
576///
577/// Returns a [`ForkError`] for an unknown id, a pause, a checkpoint with no pending nodes,
578/// an edit that names an undeclared channel or an unknown key, a target thread that
579/// already has checkpoints, or a checkpointer failure.
580///
581/// # Example
582///
583/// ```
584/// use adk_graph::checkpoint::{Checkpointer, MemoryCheckpointer};
585/// use adk_graph::state::{Checkpoint, State};
586/// use adk_graph::time_travel::{ForkSpec, fork_thread};
587/// use serde_json::json;
588///
589/// # #[tokio::main(flavor = "current_thread")]
590/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
591/// let checkpointer = MemoryCheckpointer::new();
592/// let state = State::from([("note".to_string(), json!("v1"))]);
593/// let source = Checkpoint::new("t1", state, 1, vec!["send".to_string()]);
594/// checkpointer.save(&source).await?;
595///
596/// let fork = fork_thread(
597/// &checkpointer,
598/// ForkSpec::new(&source.checkpoint_id, "t2").set("note", json!("v2")),
599/// None,
600/// )
601/// .await?;
602/// let lineage = fork.lineage()?.expect("a fork records its lineage");
603/// assert_eq!((lineage.root.as_str(), lineage.checked), ("t1", false));
604/// # Ok(())
605/// # }
606/// ```
607pub async fn fork_thread(
608 checkpointer: &dyn Checkpointer,
609 spec: ForkSpec,
610 schema: Option<&StateSchema>,
611) -> std::result::Result<Checkpoint, ForkError> {
612 let source = checkpointer
613 .load_by_id(&spec.from)
614 .await?
615 .ok_or_else(|| ForkError::UnknownCheckpoint { id: spec.from.clone() })?;
616 if source.is_paused() {
617 return Err(ForkError::Paused { id: spec.from });
618 }
619 if source.pending_nodes.is_empty() {
620 return Err(ForkError::NothingToRun { id: spec.from });
621 }
622 let schema = schema.filter(|schema| !schema.channels.is_empty());
623 for key in spec.set.keys() {
624 match schema {
625 Some(schema) if !schema.channels.contains_key(key) => {
626 return Err(ForkError::UndeclaredChannel { key: key.clone() });
627 }
628 None if !source.state.contains_key(key) => {
629 return Err(ForkError::UnknownKey { key: key.clone() });
630 }
631 _ => {}
632 }
633 }
634 if spec.new_thread_id == source.thread_id
635 || checkpointer.load(&spec.new_thread_id).await?.is_some()
636 {
637 return Err(ForkError::ThreadExists { thread: spec.new_thread_id });
638 }
639 let fork = forked_checkpoint(&source, &spec.new_thread_id, 1, &spec.set, schema.is_some())?;
640 checkpointer.save(&fork).await?;
641 tracing::info!(
642 thread_id = %source.thread_id,
643 fork.thread_id = %spec.new_thread_id,
644 fork.edited = spec.set.len(),
645 "forked a graph thread"
646 );
647 Ok(fork)
648}
649
650/// The first checkpoint of a fork of `source` into `thread`.
651fn forked_checkpoint(
652 source: &Checkpoint,
653 thread: &str,
654 version: u64,
655 set: &BTreeMap<String, Value>,
656 checked: bool,
657) -> Result<Checkpoint> {
658 let mut state = source.state.clone();
659 for (key, value) in set {
660 state.insert(key.clone(), value.clone());
661 }
662 let mut fork = Checkpoint::new(thread, state, source.step, source.pending_nodes.clone())
663 .with_version(version);
664 for key in [crate::deferred::FAN_IN_METADATA_KEY, crate::executor::OCCURRENCES_METADATA_KEY] {
665 if let Some(value) = source.metadata.get(key) {
666 fork.metadata.insert(key.to_string(), value.clone());
667 }
668 }
669 let root = source.lineage()?.map_or_else(|| source.thread_id.clone(), |lineage| lineage.root);
670 let lineage = Lineage {
671 root,
672 parent: source.thread_id.clone(),
673 parent_checkpoint: source.checkpoint_id.clone(),
674 parent_step: source.step_label(),
675 edited: set.keys().cloned().collect(),
676 checked,
677 };
678 fork.metadata.insert(LINEAGE_METADATA_KEY.to_string(), serde_json::to_value(lineage)?);
679 Ok(fork)
680}
681
682impl CompiledGraph {
683 /// Create a [`TimeTravelHandle`] for navigating the execution history of a thread.
684 ///
685 /// Requires that the graph was compiled with a checkpointer. If no checkpointer
686 /// is configured, this method panics.
687 ///
688 /// # Arguments
689 ///
690 /// * `thread_id` - The thread identifier whose history to navigate
691 ///
692 /// # Panics
693 ///
694 /// Panics if the graph was compiled without a checkpointer.
695 ///
696 /// # Example
697 ///
698 /// ```rust,ignore
699 /// use adk_graph::prelude::*;
700 ///
701 /// let checkpointer = Arc::new(MemoryCheckpointer::new());
702 /// let graph = StateGraph::new(StateSchema::simple(&["data"]))
703 /// .add_node("process", process_fn)
704 /// .add_edge(START, "process")
705 /// .add_edge("process", END)
706 /// .compile(Some(checkpointer));
707 ///
708 /// let handle = graph.time_travel("thread_1").unwrap();
709 /// let steps = handle.steps().await?;
710 /// ```
711 /// # Errors
712 ///
713 /// Returns [`GraphError::CheckpointError`] when the graph has no
714 /// checkpointer, because every operation on the handle reads checkpoints.
715 pub fn time_travel(&self, thread_id: &str) -> Result<TimeTravelHandle<'_>> {
716 let checkpointer = self.checkpointer.clone().ok_or_else(|| {
717 GraphError::CheckpointError(
718 "time travel needs a checkpointer. Add one with with_checkpointer before calling time_travel"
719 .to_string(),
720 )
721 })?;
722 Ok(TimeTravelHandle::new(self, thread_id, checkpointer))
723 }
724}
725
726#[cfg(test)]
727mod tests {
728 use super::*;
729 use crate::checkpoint::MemoryCheckpointer;
730 use crate::graph::StateGraph;
731 use crate::node::{ExecutionConfig, FunctionNode, NodeContext, NodeOutput};
732 use crate::state::{Checkpoint, State, StateSchema};
733 use serde_json::json;
734
735 /// Helper: build a simple graph with a checkpointer for testing.
736 fn build_test_graph() -> (CompiledGraph, Arc<MemoryCheckpointer>) {
737 let checkpointer = Arc::new(MemoryCheckpointer::new());
738
739 let node = FunctionNode::new("increment", |ctx: NodeContext| {
740 let count = ctx.get("count").and_then(|v| v.as_i64()).unwrap_or(0);
741 Box::pin(async move { Ok(NodeOutput::new().with_update("count", json!(count + 1))) })
742 });
743
744 let graph = StateGraph::new(StateSchema::simple(&["count"]))
745 .add_node(node)
746 .add_edge("__start__", "increment")
747 .add_edge("increment", "__end__")
748 .compile()
749 .unwrap()
750 .with_checkpointer_arc(checkpointer.clone());
751
752 (graph, checkpointer)
753 }
754
755 /// Helper: seed checkpoints for a thread.
756 async fn seed_checkpoints(checkpointer: &MemoryCheckpointer, thread_id: &str, count: usize) {
757 for step in 0..count {
758 let mut state = State::new();
759 state.insert("count".to_string(), json!(step));
760 let cp = Checkpoint::new(thread_id, state, step, vec!["increment".to_string()])
761 .with_version(step as u64 + 1);
762 checkpointer.save(&cp).await.unwrap();
763 }
764 }
765
766 #[tokio::test]
767 async fn test_fork_at_creates_new_thread() {
768 let (graph, checkpointer) = build_test_graph();
769 seed_checkpoints(&checkpointer, "thread_1", 5).await;
770
771 let handle = graph.time_travel("thread_1").unwrap();
772
773 // Fork at step 2
774 handle.fork_at(2, "thread_1_fork").await.unwrap();
775
776 // Verify the forked thread has a checkpoint
777 let forked_checkpoints = checkpointer.list("thread_1_fork").await.unwrap();
778 assert_eq!(forked_checkpoints.len(), 1);
779 assert_eq!(forked_checkpoints[0].step, 2);
780 assert_eq!(forked_checkpoints[0].state.get("count"), Some(&json!(2)));
781
782 // Verify original thread is unchanged
783 let original_checkpoints = checkpointer.list("thread_1").await.unwrap();
784 assert_eq!(original_checkpoints.len(), 5);
785 }
786
787 #[tokio::test]
788 async fn test_fork_at_nonexistent_step_errors() {
789 let (graph, checkpointer) = build_test_graph();
790 seed_checkpoints(&checkpointer, "thread_1", 3).await;
791
792 let handle = graph.time_travel("thread_1").unwrap();
793
794 let result = handle.fork_at(99, "new_thread").await;
795 assert!(result.is_err());
796 let err_msg = result.unwrap_err().to_string();
797 assert!(err_msg.contains("no checkpoint found at step 99"));
798 }
799
800 #[tokio::test]
801 async fn test_state_history_returns_states_in_range() {
802 let (graph, checkpointer) = build_test_graph();
803 seed_checkpoints(&checkpointer, "thread_1", 5).await;
804
805 let handle = graph.time_travel("thread_1").unwrap();
806
807 // Replay steps 1 through 3
808 let results = handle.state_history(1, Some(3)).await.unwrap();
809 assert_eq!(results.len(), 3);
810 assert_eq!(
811 results[0],
812 (1, {
813 let mut s = State::new();
814 s.insert("count".to_string(), json!(1));
815 s
816 })
817 );
818 assert_eq!(results[1].0, 2);
819 assert_eq!(results[2].0, 3);
820 }
821
822 #[tokio::test]
823 async fn test_state_history_to_end() {
824 let (graph, checkpointer) = build_test_graph();
825 seed_checkpoints(&checkpointer, "thread_1", 5).await;
826
827 let handle = graph.time_travel("thread_1").unwrap();
828
829 // Replay from step 2 to end (None)
830 let results = handle.state_history(2, None).await.unwrap();
831 assert_eq!(results.len(), 3); // steps 2, 3, 4
832 assert_eq!(results[0].0, 2);
833 assert_eq!(results[1].0, 3);
834 assert_eq!(results[2].0, 4);
835 }
836
837 #[tokio::test]
838 async fn test_replay_nonexistent_from_step_errors() {
839 let (graph, checkpointer) = build_test_graph();
840 seed_checkpoints(&checkpointer, "thread_1", 3).await;
841
842 let handle = graph.time_travel("thread_1").unwrap();
843
844 let result = handle.state_history(99, None).await;
845 assert!(result.is_err());
846 let err_msg = result.unwrap_err().to_string();
847 assert!(err_msg.contains("no checkpoint found at step 99"));
848 }
849
850 #[tokio::test]
851 async fn test_resume_from_executes_graph() {
852 let (graph, checkpointer) = build_test_graph();
853
854 // Seed a checkpoint at step 0 with count=5
855 let mut state = State::new();
856 state.insert("count".to_string(), json!(5));
857 let cp =
858 Checkpoint::new("thread_1", state, 0, vec!["increment".to_string()]).with_version(1);
859 checkpointer.save(&cp).await.unwrap();
860
861 let handle = graph.time_travel("thread_1").unwrap();
862
863 // Resume from step 0 — the graph should execute "increment" and produce count=6
864 let config = ExecutionConfig::new("thread_1");
865 let final_state = handle.resume_from(0, config).await.unwrap();
866 assert_eq!(final_state.get("count"), Some(&json!(6)));
867 }
868
869 #[tokio::test]
870 async fn test_resume_from_nonexistent_step_errors() {
871 let (graph, checkpointer) = build_test_graph();
872 seed_checkpoints(&checkpointer, "thread_1", 3).await;
873
874 let handle = graph.time_travel("thread_1").unwrap();
875
876 let config = ExecutionConfig::new("thread_1");
877 let result = handle.resume_from(99, config).await;
878 assert!(result.is_err());
879 let err_msg = result.unwrap_err().to_string();
880 assert!(err_msg.contains("no checkpoint found at step 99"));
881 }
882
883 #[tokio::test]
884 async fn test_fork_independence() {
885 let (graph, checkpointer) = build_test_graph();
886 seed_checkpoints(&checkpointer, "thread_1", 5).await;
887
888 let handle = graph.time_travel("thread_1").unwrap();
889
890 // Fork at step 2
891 handle.fork_at(2, "forked").await.unwrap();
892
893 // Modify the forked thread by adding another checkpoint
894 let mut new_state = State::new();
895 new_state.insert("count".to_string(), json!(100));
896 let new_cp = Checkpoint::new("forked", new_state, 3, vec![]).with_version(2);
897 checkpointer.save(&new_cp).await.unwrap();
898
899 // Verify original thread is unchanged
900 let original = checkpointer.list("thread_1").await.unwrap();
901 assert_eq!(original.len(), 5);
902 for cp in &original {
903 assert_ne!(cp.state.get("count"), Some(&json!(100)));
904 }
905 }
906}