Skip to main content

adk_graph/functional/
execution_log.rs

1//! Execution log for tracking task completion status within a workflow run.
2//!
3//! The [`ExecutionLog`] is stored as part of checkpoint metadata and enables
4//! the resume-skip behavior: when a workflow resumes from a checkpoint, tasks
5//! that were already completed are skipped automatically.
6
7use std::collections::HashMap;
8
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12/// Tracks task completion status within a workflow run.
13/// Stored as part of the checkpoint metadata.
14///
15/// # Example
16///
17/// ```rust,ignore
18/// use adk_graph::functional::ExecutionLog;
19///
20/// let mut log = ExecutionLog::new();
21/// log.record_start("step_a");
22/// log.record_completion("step_a", serde_json::json!({"result": 42}));
23///
24/// assert!(log.is_completed("step_a"));
25/// assert_eq!(log.get_result("step_a"), Some(&serde_json::json!({"result": 42})));
26/// ```
27#[derive(Debug, Clone, Serialize, Deserialize, Default)]
28pub struct ExecutionLog {
29    /// Map of task_id -> completion record
30    pub tasks: HashMap<String, TaskRecord>,
31    /// Current workflow step counter
32    pub current_step: usize,
33}
34
35/// A record of a single task's execution state.
36///
37/// Contains status, optional result/error, timestamps, and retry attempt count.
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct TaskRecord {
40    /// Current status of the task
41    pub status: TaskStatus,
42    /// The result value if the task completed successfully
43    pub result: Option<Value>,
44    /// Error message if the task failed
45    pub error: Option<String>,
46    /// ISO 8601 timestamp when the task started
47    pub started_at: String,
48    /// ISO 8601 timestamp when the task completed (success or failure)
49    pub completed_at: Option<String>,
50    /// Number of execution attempts (starts at 1)
51    pub attempt: u32,
52}
53
54/// The lifecycle status of a task within a workflow execution.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "lowercase")]
57pub enum TaskStatus {
58    /// Task is currently executing
59    Running,
60    /// Task completed successfully
61    Completed,
62    /// Task failed after exhausting retries
63    Failed,
64    /// Task was interrupted (waiting for external input)
65    Interrupted,
66}
67
68impl ExecutionLog {
69    /// Create a new empty execution log.
70    pub fn new() -> Self {
71        Self { tasks: HashMap::new(), current_step: 0 }
72    }
73
74    /// Get the cached result for a completed task.
75    ///
76    /// Returns `Some(&Value)` if the task is completed and has a result,
77    /// `None` otherwise.
78    pub fn get_result(&self, task_id: &str) -> Option<&Value> {
79        self.tasks.get(task_id).and_then(|record| {
80            if record.status == TaskStatus::Completed { record.result.as_ref() } else { None }
81        })
82    }
83
84    /// Check if a task was already completed in a prior run.
85    pub fn is_completed(&self, task_id: &str) -> bool {
86        self.tasks.get(task_id).is_some_and(|record| record.status == TaskStatus::Completed)
87    }
88
89    /// Mark a task as running, recording the start timestamp.
90    pub fn record_start(&mut self, task_id: &str) {
91        let now = chrono::Utc::now().to_rfc3339();
92        let record = self.tasks.entry(task_id.to_string()).or_insert(TaskRecord {
93            status: TaskStatus::Running,
94            result: None,
95            error: None,
96            started_at: now.clone(),
97            completed_at: None,
98            attempt: 0,
99        });
100        record.status = TaskStatus::Running;
101        record.attempt += 1;
102        // Update started_at only on first attempt
103        if record.attempt == 1 {
104            record.started_at = now;
105        }
106    }
107
108    /// Mark a task as completed with a result value.
109    pub fn record_completion(&mut self, task_id: &str, result: Value) {
110        let now = chrono::Utc::now().to_rfc3339();
111        if let Some(record) = self.tasks.get_mut(task_id) {
112            record.status = TaskStatus::Completed;
113            record.result = Some(result);
114            record.error = None;
115            record.completed_at = Some(now);
116        } else {
117            // Task was completed without a prior record_start (edge case)
118            self.tasks.insert(
119                task_id.to_string(),
120                TaskRecord {
121                    status: TaskStatus::Completed,
122                    result: Some(result),
123                    error: None,
124                    started_at: now.clone(),
125                    completed_at: Some(now),
126                    attempt: 1,
127                },
128            );
129        }
130    }
131
132    /// Mark a task as failed with an error message.
133    pub fn record_failure(&mut self, task_id: &str, error: &str) {
134        let now = chrono::Utc::now().to_rfc3339();
135        if let Some(record) = self.tasks.get_mut(task_id) {
136            record.status = TaskStatus::Failed;
137            record.error = Some(error.to_string());
138            record.completed_at = Some(now);
139        } else {
140            self.tasks.insert(
141                task_id.to_string(),
142                TaskRecord {
143                    status: TaskStatus::Failed,
144                    result: None,
145                    error: Some(error.to_string()),
146                    started_at: now.clone(),
147                    completed_at: Some(now),
148                    attempt: 1,
149                },
150            );
151        }
152    }
153
154    /// Records the value an interrupt was answered with, under its continuation key.
155    ///
156    /// The answer is stored in [`Self::tasks`] as a completed record keyed by the
157    /// continuation key (`interrupt-N`), which cannot collide with a task call key
158    /// (`{task}#{ordinal}`). A run resumed from any later checkpoint replays the answer,
159    /// so it does not have to be supplied again.
160    ///
161    /// # Example
162    ///
163    /// ```
164    /// use adk_graph::functional::ExecutionLog;
165    /// use serde_json::json;
166    ///
167    /// let mut log = ExecutionLog::new();
168    /// log.record_interrupt_answer("interrupt-1", json!({"approved": true}));
169    ///
170    /// assert_eq!(log.interrupt_answer("interrupt-1"), Some(&json!({"approved": true})));
171    /// assert_eq!(log.interrupt_answer("interrupt-2"), None);
172    /// ```
173    pub fn record_interrupt_answer(&mut self, continuation_key: &str, value: Value) {
174        self.record_completion(continuation_key, value);
175    }
176
177    /// Returns the answer recorded for an interrupt, if a run already received one.
178    pub fn interrupt_answer(&self, continuation_key: &str) -> Option<&Value> {
179        self.get_result(continuation_key)
180    }
181
182    /// Get the current step number.
183    pub fn current_step(&self) -> usize {
184        self.current_step
185    }
186
187    /// Increment the step counter and return the new value.
188    pub fn advance_step(&mut self) -> usize {
189        self.current_step += 1;
190        self.current_step
191    }
192}