Skip to main content

adk_graph/
record.rs

1//! Run, step and lineage records carried in checkpoint metadata (spec 3.3 §12, developer
2//! track).
3//!
4//! Every checkpoint a run writes carries three metadata keys:
5//!
6//! | Key | Type | Content |
7//! |-----|------|---------|
8//! | [`RUN_METADATA_KEY`] | [`RunRecord`] | The run the checkpoint belongs to |
9//! | [`STEPS_METADATA_KEY`] | `Vec<`[`StepRecord`]`>` | The steps finished since the previous saved checkpoint |
10//! | [`LINEAGE_METADATA_KEY`] | [`Lineage`] | Where a forked thread came from; absent on a thread that was not forked |
11//! | [`OPEN_PAUSES_METADATA_KEY`] | `Vec<String>` | The checkpoints of the thread's pauses that no run has resumed; absent when there are none |
12//!
13//! A run is the work that started a thread from its entry nodes. It continues across
14//! pauses, approval turns and resumes; a finished thread that starts again from its entry
15//! opens a new run. Node lifecycle is recorded here, durably, rather than forwarded to a
16//! runner's event stream.
17//!
18//! A pause checkpoint has the same [`Checkpoint::step`] as the completed checkpoint before
19//! it, so checkpoints are addressed by id; a step number is a label. Checkpoints written
20//! before these records existed read as empty.
21//!
22//! # Example
23//!
24//! ```
25//! use adk_graph::checkpoint::{Checkpointer, MemoryCheckpointer};
26//! use adk_graph::edge::{END, START};
27//! use adk_graph::graph::StateGraph;
28//! use adk_graph::node::{ExecutionConfig, NodeOutput};
29//! use adk_graph::record::{NodeStatus, StepKind};
30//! use adk_graph::state::State;
31//! use serde_json::json;
32//! use std::sync::Arc;
33//!
34//! # #[tokio::main(flavor = "current_thread")]
35//! # async fn main() -> adk_graph::Result<()> {
36//! let checkpointer = Arc::new(MemoryCheckpointer::new());
37//! let graph = StateGraph::with_channels(&["invoice"])
38//!     .add_node_fn("draft", |_ctx| async {
39//!         Ok(NodeOutput::new().with_update("invoice", json!({ "amountCents": 4200 })))
40//!     })
41//!     .add_edge(START, "draft")
42//!     .add_edge("draft", END)
43//!     .compile()?
44//!     .with_checkpointer_arc(checkpointer.clone());
45//! graph.invoke(State::new(), ExecutionConfig::new("t1")).await?;
46//!
47//! let last = checkpointer.load("t1").await?.expect("a checkpoint");
48//! let steps = last.step_records()?;
49//! assert_eq!(steps[0].kind, StepKind::Completed);
50//! assert_eq!(steps[0].nodes[0].status, NodeStatus::Done);
51//! assert_eq!(steps[0].nodes[0].writes, vec!["invoice".to_string()]);
52//! assert!(last.run_record()?.is_some());
53//! assert!(last.lineage()?.is_none());
54//! # Ok(())
55//! # }
56//! ```
57
58use crate::error::{GraphError, Result};
59use crate::state::Checkpoint;
60use chrono::{DateTime, Utc};
61use serde::de::DeserializeOwned;
62use serde::{Deserialize, Serialize};
63
64/// Checkpoint metadata key holding the [`RunRecord`].
65pub const RUN_METADATA_KEY: &str = "adk.graph.run";
66/// Checkpoint metadata key holding the [`StepRecord`]s finished since the previous save.
67pub const STEPS_METADATA_KEY: &str = "adk.graph.steps";
68/// Checkpoint metadata key holding a forked thread's [`Lineage`].
69pub const LINEAGE_METADATA_KEY: &str = "adk.graph.lineage";
70/// Checkpoint metadata key holding the IDs of the thread's checkpoints where a run paused
71/// and no run has resumed since.
72///
73/// Every checkpoint a run writes carries the list as it stands, so the newest checkpoint
74/// always holds the current one; [`RetentionPolicy`](crate::checkpoint::RetentionPolicy)
75/// keeps the checkpoints it names.
76pub const OPEN_PAUSES_METADATA_KEY: &str = "adk.graph.open_pauses";
77
78/// The run a checkpoint belongs to (spec 3.3 §12).
79///
80/// The run id is the invocation that started the thread from its entry nodes: the
81/// parent invocation's id under a `Runner`, otherwise a new id.
82///
83/// # Example
84///
85/// ```
86/// use adk_graph::record::RunRecord;
87///
88/// let run = RunRecord::new("inv-1");
89/// assert_eq!(serde_json::to_value(&run)?["runId"], "inv-1");
90/// # Ok::<(), serde_json::Error>(())
91/// ```
92#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
93#[serde(rename_all = "camelCase")]
94pub struct RunRecord {
95    /// The invocation that started the run.
96    pub run_id: String,
97    /// When the run started, to the microsecond.
98    pub started_at: DateTime<Utc>,
99}
100
101impl RunRecord {
102    /// A run with id `run_id` that starts now.
103    pub fn new(run_id: impl Into<String>) -> Self {
104        Self { run_id: run_id.into(), started_at: now() }
105    }
106}
107
108/// How a step ended (spec 3.3 §12).
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub enum StepKind {
112    /// Every node of the step finished and the run moved on.
113    Completed,
114    /// A node paused, or the run stopped at an interrupt gate.
115    Paused,
116    /// A node failed and the step did not complete.
117    Failed,
118}
119
120/// What became of one node in one step (spec 3.3 §12).
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
122#[serde(rename_all = "camelCase")]
123pub enum NodeStatus {
124    /// The node ran and finished.
125    Done,
126    /// The node paused, or the run stopped at its interrupt gate.
127    Paused,
128    /// The node failed.
129    Failed,
130    /// A governed node whose call already happened: its record answered it and nothing
131    /// was sent again.
132    Recorded,
133    /// A governed node whose call was refused: by policy, by a person, or by the kill
134    /// switch.
135    Refused,
136    /// The node did not run: the step failed before it started, or a governed node had
137    /// no approval gate.
138    NotRun,
139}
140
141/// One node's part in a step (spec 3.3 §12).
142///
143/// # Example
144///
145/// ```
146/// use adk_graph::record::{NodeRecord, NodeStatus};
147///
148/// let record = NodeRecord {
149///     node: "pay".to_string(),
150///     started_at: chrono::Utc::now(),
151///     duration_ms: 300,
152///     status: NodeStatus::Done,
153///     writes: vec!["charge".to_string()],
154///     attempt: 1,
155///     effect_key: Some("graph/urn:adk:agent:app/invoice-run/t1/pay/1/fnv1a128:00".to_string()),
156///     error: None,
157/// };
158/// assert_eq!(serde_json::to_value(&record)?["durationMs"], 300);
159/// # Ok::<(), serde_json::Error>(())
160/// ```
161#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
162#[serde(rename_all = "camelCase")]
163pub struct NodeRecord {
164    /// The node's name.
165    pub node: String,
166    /// When the node started, to the microsecond.
167    pub started_at: DateTime<Utc>,
168    /// How long the node ran, in milliseconds.
169    pub duration_ms: u64,
170    /// What became of the node.
171    pub status: NodeStatus,
172    /// The state keys the node wrote, sorted.
173    pub writes: Vec<String>,
174    /// The node's attempt count when it finished; 0 when it did not start.
175    pub attempt: u32,
176    /// The action-ledger key of a governed node's call.
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub effect_key: Option<String>,
179    /// The error a failed or refused node ended with.
180    #[serde(default, skip_serializing_if = "Option::is_none")]
181    pub error: Option<String>,
182}
183
184/// One super-step of a run (spec 3.3 §12).
185///
186/// `step` is the step's label: the [`Checkpoint::step`] of the completed checkpoint the
187/// step produces. A paused or failed step keeps the label it would have had.
188///
189/// # Example
190///
191/// ```
192/// use adk_graph::record::{StepKind, StepRecord};
193///
194/// let record = StepRecord { step: 2, kind: StepKind::Paused, nodes: Vec::new() };
195/// assert_eq!(serde_json::to_value(&record)?["kind"], "paused");
196/// # Ok::<(), serde_json::Error>(())
197/// ```
198#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
199#[serde(rename_all = "camelCase")]
200pub struct StepRecord {
201    /// The step's label.
202    pub step: usize,
203    /// How the step ended.
204    pub kind: StepKind,
205    /// The step's nodes, sorted by name.
206    pub nodes: Vec<NodeRecord>,
207}
208
209/// Where a forked thread came from (spec 3.3 §12).
210///
211/// # Example
212///
213/// ```
214/// use adk_graph::record::Lineage;
215///
216/// let lineage = Lineage {
217///     root: "t1".to_string(),
218///     parent: "t1".to_string(),
219///     parent_checkpoint: "c1".to_string(),
220///     parent_step: 1,
221///     edited: vec!["note".to_string()],
222///     checked: true,
223/// };
224/// assert_eq!(serde_json::to_value(&lineage)?["parentCheckpoint"], "c1");
225/// # Ok::<(), serde_json::Error>(())
226/// ```
227#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
228#[serde(rename_all = "camelCase")]
229pub struct Lineage {
230    /// The thread the whole family of forks started from.
231    pub root: String,
232    /// The thread this one was forked from.
233    pub parent: String,
234    /// The checkpoint of `parent` this thread was forked at.
235    pub parent_checkpoint: String,
236    /// That checkpoint's step label.
237    pub parent_step: usize,
238    /// The state keys the fork overwrote, sorted.
239    pub edited: Vec<String>,
240    /// Whether the edits were checked against the graph's declared channels.
241    pub checked: bool,
242}
243
244impl Checkpoint {
245    /// The run this checkpoint belongs to, or `None` for a checkpoint without one.
246    ///
247    /// # Errors
248    ///
249    /// Returns [`GraphError::SerializationError`] when the record is malformed.
250    ///
251    /// # Example
252    ///
253    /// ```
254    /// use adk_graph::state::{Checkpoint, State};
255    ///
256    /// let checkpoint = Checkpoint::new("t1", State::new(), 0, vec![]);
257    /// assert!(checkpoint.run_record()?.is_none());
258    /// # Ok::<(), adk_graph::GraphError>(())
259    /// ```
260    pub fn run_record(&self) -> Result<Option<RunRecord>> {
261        read_key(self, RUN_METADATA_KEY)
262    }
263
264    /// The steps finished since the previous saved checkpoint of the thread, oldest first;
265    /// empty for a checkpoint without them.
266    ///
267    /// # Errors
268    ///
269    /// Returns [`GraphError::SerializationError`] when the records are malformed.
270    ///
271    /// # Example
272    ///
273    /// ```
274    /// use adk_graph::state::{Checkpoint, State};
275    ///
276    /// let checkpoint = Checkpoint::new("t1", State::new(), 0, vec![]);
277    /// assert!(checkpoint.step_records()?.is_empty());
278    /// # Ok::<(), adk_graph::GraphError>(())
279    /// ```
280    pub fn step_records(&self) -> Result<Vec<StepRecord>> {
281        Ok(read_key(self, STEPS_METADATA_KEY)?.unwrap_or_default())
282    }
283
284    /// Where this checkpoint's thread was forked from, or `None` for a thread that was not
285    /// forked.
286    ///
287    /// # Errors
288    ///
289    /// Returns [`GraphError::SerializationError`] when the record is malformed.
290    ///
291    /// # Example
292    ///
293    /// ```
294    /// use adk_graph::state::{Checkpoint, State};
295    ///
296    /// let checkpoint = Checkpoint::new("t1", State::new(), 0, vec![]);
297    /// assert!(checkpoint.lineage()?.is_none());
298    /// # Ok::<(), adk_graph::GraphError>(())
299    /// ```
300    pub fn lineage(&self) -> Result<Option<Lineage>> {
301        read_key(self, LINEAGE_METADATA_KEY)
302    }
303
304    /// The IDs of the thread's checkpoints where a run paused and no run has resumed, as
305    /// they stood when this checkpoint was written.
306    ///
307    /// Read from the newest checkpoint, this lists every pause of the thread a caller can
308    /// still resume by ID. A checkpoint written before the list existed reads as empty.
309    ///
310    /// # Errors
311    ///
312    /// Returns [`GraphError::SerializationError`] when the list is malformed.
313    ///
314    /// # Example
315    ///
316    /// ```
317    /// use adk_graph::record::OPEN_PAUSES_METADATA_KEY;
318    /// use adk_graph::state::{Checkpoint, State};
319    /// use serde_json::json;
320    ///
321    /// let newest = Checkpoint::new("t1", State::new(), 3, vec!["pay".into()])
322    ///     .with_metadata(OPEN_PAUSES_METADATA_KEY, json!(["cp-2"]));
323    /// assert_eq!(newest.open_pauses()?, vec!["cp-2".to_string()]);
324    /// # Ok::<(), adk_graph::GraphError>(())
325    /// ```
326    pub fn open_pauses(&self) -> Result<Vec<String>> {
327        Ok(read_key(self, OPEN_PAUSES_METADATA_KEY)?.unwrap_or_default())
328    }
329
330    /// Whether a node of this checkpoint's frontier waits mid-step: the run stopped before
331    /// a gated node, or a node paused itself.
332    ///
333    /// # Example
334    ///
335    /// ```
336    /// use adk_graph::state::{Checkpoint, State};
337    ///
338    /// let completed = Checkpoint::new("t1", State::new(), 1, vec!["pay".into()]);
339    /// assert!(!completed.is_paused());
340    /// assert!(completed.with_cleared_interrupt("pay").is_paused());
341    /// ```
342    pub fn is_paused(&self) -> bool {
343        self.cleared_interrupt.is_some()
344            || self.metadata.contains_key(crate::executor::PAUSED_NODES_METADATA_KEY)
345    }
346
347    /// How far the step labels of this checkpoint's thread run ahead of
348    /// [`Checkpoint::step`].
349    ///
350    /// A run that stops at an `interrupt_after` gate saves its finished step without
351    /// advancing `step`, so the step that resumes it takes the next label rather than the
352    /// gated step's. A step that paused before its nodes finished, or failed, keeps its
353    /// label when it runs again.
354    pub(crate) fn label_offset(&self) -> usize {
355        match self.step_records().ok().and_then(|mut steps| steps.pop()) {
356            Some(last) => {
357                let again = last.kind == StepKind::Failed
358                    || (last.kind == StepKind::Paused
359                        && last.nodes.iter().any(|node| node.status == NodeStatus::Paused));
360                last.step.saturating_sub(self.step + usize::from(again))
361            }
362            // A fork's first checkpoint carries no steps; its lineage names the label.
363            None => self
364                .lineage()
365                .ok()
366                .flatten()
367                .map_or(0, |lineage| lineage.parent_step.saturating_sub(self.step)),
368        }
369    }
370
371    /// The label of the step this checkpoint completed, as its records name it.
372    #[cfg(feature = "time-travel")]
373    pub(crate) fn step_label(&self) -> usize {
374        self.step + self.label_offset()
375    }
376}
377
378/// Reads one record key, `None` when the checkpoint does not carry it.
379fn read_key<T: DeserializeOwned>(checkpoint: &Checkpoint, key: &str) -> Result<Option<T>> {
380    let Some(value) = checkpoint.metadata.get(key) else { return Ok(None) };
381    serde_json::from_value(value.clone()).map(Some).map_err(|error| {
382        GraphError::SerializationError(format!(
383            "checkpoint '{}' metadata '{key}' is malformed: {error}",
384            checkpoint.checkpoint_id
385        ))
386    })
387}
388
389/// The current time to the microsecond, the finest precision every backend stores.
390pub(crate) fn now() -> DateTime<Utc> {
391    chrono::SubsecRound::trunc_subsecs(Utc::now(), 6)
392}