Skip to main content

adk_graph/
timeout.rs

1//! Timeout enforcement for graph node execution.
2//!
3//! Provides wall-clock and idle timeout enforcement for individual graph nodes,
4//! with configurable recovery actions (fail, retry, skip).
5//!
6//! # Overview
7//!
8//! The [`TimeoutPolicy`] struct configures timeout behavior for a node:
9//! - `run_timeout`: Hard wall-clock limit from when the node starts executing.
10//! - `idle_timeout`: Resets each time `report_progress()` is called on the progress handle.
11//! - `on_timeout`: What to do when a timeout fires ([`OnTimeout`]).
12//!
13//! # Example
14//!
15//! ```rust,ignore
16//! use std::time::Duration;
17//! use adk_graph::timeout::{TimeoutPolicy, OnTimeout};
18//!
19//! let policy = TimeoutPolicy {
20//!     run_timeout: Some(Duration::from_secs(30)),
21//!     idle_timeout: Some(Duration::from_secs(5)),
22//!     on_timeout: OnTimeout::Retry { max_attempts: 3 },
23//! };
24//! ```
25
26use std::sync::Arc;
27use std::sync::atomic::{AtomicU64, Ordering};
28use std::time::Duration;
29
30use crate::error::{GraphError, Result};
31use crate::node::{Node, NodeContext, NodeOutput};
32
33/// Recovery action when a node times out.
34#[derive(Debug, Clone, Default)]
35pub enum OnTimeout {
36    /// Fail the graph with `GraphError::NodeTimedOut`.
37    #[default]
38    Fail,
39    /// Retry the node up to `max_attempts` times before failing.
40    Retry { max_attempts: usize },
41    /// Skip the node and proceed with an empty output.
42    Skip,
43}
44
45/// Timeout configuration for a graph node.
46///
47/// # Example
48///
49/// ```rust,ignore
50/// use std::time::Duration;
51/// use adk_graph::timeout::{TimeoutPolicy, OnTimeout};
52///
53/// let policy = TimeoutPolicy {
54///     run_timeout: Some(Duration::from_secs(10)),
55///     idle_timeout: None,
56///     on_timeout: OnTimeout::Fail,
57/// };
58/// ```
59#[derive(Debug, Clone, Default)]
60pub struct TimeoutPolicy {
61    /// Hard wall-clock limit. Timer starts when node begins execution.
62    pub run_timeout: Option<Duration>,
63    /// Idle timeout: resets each time `report_progress()` is called.
64    pub idle_timeout: Option<Duration>,
65    /// Recovery action on timeout.
66    pub on_timeout: OnTimeout,
67}
68
69/// A shared progress handle that nodes can use to report progress,
70/// resetting the idle timeout counter.
71///
72/// The handle stores the last progress timestamp as milliseconds since
73/// the UNIX epoch using an atomic u64 for lock-free updates.
74#[derive(Debug, Clone)]
75pub struct ProgressHandle {
76    last_progress_ms: Arc<AtomicU64>,
77}
78
79impl ProgressHandle {
80    /// Create a new progress handle initialized to the current time.
81    pub fn new() -> Self {
82        let now_ms = current_time_ms();
83        Self { last_progress_ms: Arc::new(AtomicU64::new(now_ms)) }
84    }
85
86    /// Report progress, resetting the idle timeout counter.
87    pub fn report_progress(&self) {
88        let now_ms = current_time_ms();
89        self.last_progress_ms.store(now_ms, Ordering::Release);
90    }
91
92    /// Get the last progress timestamp in milliseconds since epoch.
93    pub(crate) fn last_progress_ms(&self) -> u64 {
94        self.last_progress_ms.load(Ordering::Acquire)
95    }
96}
97
98impl Default for ProgressHandle {
99    fn default() -> Self {
100        Self::new()
101    }
102}
103
104/// Execute a node with timeout enforcement.
105///
106/// Uses `tokio::select!` to race node execution against configured timeouts.
107/// When a timeout fires, the configured [`OnTimeout`] recovery action is applied:
108///
109/// - [`OnTimeout::Fail`]: Returns `GraphError::NodeTimedOut`.
110/// - [`OnTimeout::Retry`]: Re-executes the node up to `max_attempts` times.
111/// - [`OnTimeout::Skip`]: Returns an empty [`NodeOutput`].
112///
113/// A `tracing::warn!` is emitted whenever a timeout triggers a recovery action.
114///
115/// # Arguments
116///
117/// * `node` - The node to execute.
118/// * `ctx` - The node execution context.
119/// * `policy` - The timeout policy to enforce.
120///
121/// # Example
122///
123/// ```rust,ignore
124/// use adk_graph::timeout::{execute_with_timeout, TimeoutPolicy, OnTimeout};
125/// use std::time::Duration;
126///
127/// let policy = TimeoutPolicy {
128///     run_timeout: Some(Duration::from_secs(5)),
129///     idle_timeout: None,
130///     on_timeout: OnTimeout::Fail,
131/// };
132///
133/// let result = execute_with_timeout(&my_node, &ctx, &policy).await;
134/// ```
135pub async fn execute_with_timeout(
136    node: &dyn Node,
137    ctx: &NodeContext,
138    policy: &TimeoutPolicy,
139) -> Result<NodeOutput> {
140    // If no timeouts are configured, execute directly
141    if policy.run_timeout.is_none() && policy.idle_timeout.is_none() {
142        return node.execute(ctx).await;
143    }
144
145    let mut attempts = 0;
146
147    loop {
148        attempts += 1;
149        crate::executor::begin_attempt(ctx);
150        let result = execute_once_with_timeout(node, ctx, policy).await;
151
152        match result {
153            Ok(output) => return Ok(output),
154            Err(GraphError::NodeTimedOut { ref node, ref elapsed }) => {
155                match &policy.on_timeout {
156                    OnTimeout::Fail => {
157                        tracing::warn!(
158                            node = %node,
159                            elapsed_ms = elapsed.as_millis(),
160                            action = "fail",
161                            "node timed out, failing execution"
162                        );
163                        return result;
164                    }
165                    OnTimeout::Retry { max_attempts } => {
166                        if attempts >= *max_attempts {
167                            tracing::warn!(
168                                node = %node,
169                                elapsed_ms = elapsed.as_millis(),
170                                attempts = attempts,
171                                action = "fail_after_retries",
172                                "node timed out after all retry attempts exhausted"
173                            );
174                            return result;
175                        }
176                        tracing::warn!(
177                            node = %node,
178                            elapsed_ms = elapsed.as_millis(),
179                            attempt = attempts,
180                            max_attempts = *max_attempts,
181                            action = "retry",
182                            "node timed out, retrying"
183                        );
184                        // Continue loop to retry
185                    }
186                    OnTimeout::Skip => {
187                        tracing::warn!(
188                            node = %node,
189                            elapsed_ms = elapsed.as_millis(),
190                            action = "skip",
191                            "node timed out, skipping with empty output"
192                        );
193                        return Ok(NodeOutput::new());
194                    }
195                }
196            }
197            Err(other) => return Err(other),
198        }
199    }
200}
201
202/// Execute a single attempt of a node with timeout enforcement.
203async fn execute_once_with_timeout(
204    node: &dyn Node,
205    ctx: &NodeContext,
206    policy: &TimeoutPolicy,
207) -> Result<NodeOutput> {
208    let node_name = node.name().to_string();
209    let progress_handle = ProgressHandle::new();
210
211    // The node keeps everything the executor attached, such as its child invoker
212    // and its graph's schema, with a fresh progress handle so it can call
213    // `report_progress()` to reset the idle timeout.
214    let mut timeout_ctx = ctx.clone();
215    timeout_ctx.set_progress_handle(progress_handle.clone());
216
217    tokio::select! {
218        result = node.execute(&timeout_ctx) => {
219            result
220        }
221        elapsed = wait_for_run_timeout(policy.run_timeout) => {
222            Err(GraphError::NodeTimedOut {
223                node: node_name,
224                elapsed,
225            })
226        }
227        elapsed = wait_for_idle_timeout(policy.idle_timeout, &progress_handle) => {
228            Err(GraphError::NodeTimedOut {
229                node: node_name,
230                elapsed,
231            })
232        }
233    }
234}
235
236/// Wait for the run timeout to expire. If no run timeout is configured,
237/// this future never completes (allowing the select to be driven by other branches).
238async fn wait_for_run_timeout(run_timeout: Option<Duration>) -> Duration {
239    match run_timeout {
240        Some(duration) => {
241            tokio::time::sleep(duration).await;
242            duration
243        }
244        None => {
245            // Never completes — effectively infinite timeout
246            std::future::pending::<()>().await;
247            unreachable!()
248        }
249    }
250}
251
252/// Poll for idle timeout expiry. Checks every 100ms whether the time since
253/// last progress exceeds the idle timeout. If no idle timeout is configured,
254/// this future never completes.
255async fn wait_for_idle_timeout(
256    idle_timeout: Option<Duration>,
257    progress_handle: &ProgressHandle,
258) -> Duration {
259    match idle_timeout {
260        Some(idle_duration) => {
261            let start_ms = current_time_ms();
262            let idle_ms = idle_duration.as_millis() as u64;
263            let poll_interval = Duration::from_millis(100);
264
265            loop {
266                tokio::time::sleep(poll_interval).await;
267                let now_ms = current_time_ms();
268                let last_progress = progress_handle.last_progress_ms();
269                let idle_elapsed = now_ms.saturating_sub(last_progress);
270
271                if idle_elapsed >= idle_ms {
272                    let total_elapsed_ms = now_ms.saturating_sub(start_ms);
273                    return Duration::from_millis(total_elapsed_ms);
274                }
275            }
276        }
277        None => {
278            // Never completes — effectively infinite timeout
279            std::future::pending::<()>().await;
280            unreachable!()
281        }
282    }
283}
284
285/// Get the current time in milliseconds since the UNIX epoch.
286fn current_time_ms() -> u64 {
287    std::time::SystemTime::now()
288        .duration_since(std::time::UNIX_EPOCH)
289        .unwrap_or_default()
290        .as_millis() as u64
291}
292
293/// Returns how long a streaming node may take to produce its next event.
294///
295/// The budget is the smaller of the remaining run timeout and the idle timeout.
296/// For a stream, "idle" means no event was produced within `idle_timeout`, which
297/// is the streaming analogue of a node that never calls `report_progress()`.
298/// Returns `None` when the policy sets no applicable limit.
299pub fn item_timeout_budget(policy: &TimeoutPolicy, elapsed: Duration) -> Option<Duration> {
300    let remaining_run = policy.run_timeout.map(|limit| limit.saturating_sub(elapsed));
301    match (remaining_run, policy.idle_timeout) {
302        (Some(run), Some(idle)) => Some(run.min(idle)),
303        (Some(run), None) => Some(run),
304        (None, Some(idle)) => Some(idle),
305        (None, None) => None,
306    }
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312    use crate::node::{ExecutionConfig, FunctionNode, NodeContext, NodeOutput};
313    use crate::state::State;
314
315    #[tokio::test]
316    async fn test_no_timeout_executes_normally() {
317        let node = FunctionNode::new("fast", |_ctx| async {
318            Ok(NodeOutput::new().with_update("done", serde_json::json!(true)))
319        });
320
321        let ctx = NodeContext::new(State::new(), ExecutionConfig::default(), 0);
322        let policy = TimeoutPolicy::default();
323
324        let result = execute_with_timeout(&node, &ctx, &policy).await;
325        assert!(result.is_ok());
326        let output = result.unwrap();
327        assert_eq!(output.updates.get("done"), Some(&serde_json::json!(true)));
328    }
329
330    #[tokio::test]
331    async fn test_run_timeout_fires_on_slow_node() {
332        let node = FunctionNode::new("slow", |_ctx| async {
333            tokio::time::sleep(Duration::from_secs(10)).await;
334            Ok(NodeOutput::new())
335        });
336
337        let ctx = NodeContext::new(State::new(), ExecutionConfig::default(), 0);
338        let policy = TimeoutPolicy {
339            run_timeout: Some(Duration::from_millis(100)),
340            idle_timeout: None,
341            on_timeout: OnTimeout::Fail,
342        };
343
344        let result = execute_with_timeout(&node, &ctx, &policy).await;
345        assert!(result.is_err());
346        match result {
347            Err(GraphError::NodeTimedOut { node, .. }) => {
348                assert_eq!(node, "slow");
349            }
350            Err(other) => panic!("expected NodeTimedOut, got: {other:?}"),
351            Ok(_) => panic!("expected error, got Ok"),
352        }
353    }
354
355    #[tokio::test]
356    async fn test_skip_returns_empty_output() {
357        let node = FunctionNode::new("slow", |_ctx| async {
358            tokio::time::sleep(Duration::from_secs(10)).await;
359            Ok(NodeOutput::new().with_update("should_not_appear", serde_json::json!(true)))
360        });
361
362        let ctx = NodeContext::new(State::new(), ExecutionConfig::default(), 0);
363        let policy = TimeoutPolicy {
364            run_timeout: Some(Duration::from_millis(50)),
365            idle_timeout: None,
366            on_timeout: OnTimeout::Skip,
367        };
368
369        let result = execute_with_timeout(&node, &ctx, &policy).await;
370        assert!(result.is_ok());
371        let output = result.unwrap();
372        assert!(output.updates.is_empty());
373    }
374
375    #[tokio::test]
376    async fn test_retry_retries_up_to_max_attempts() {
377        use std::sync::atomic::AtomicUsize;
378
379        let attempt_count = Arc::new(AtomicUsize::new(0));
380        let count_clone = attempt_count.clone();
381
382        let node = FunctionNode::new("flaky", move |_ctx| {
383            let count = count_clone.clone();
384            async move {
385                count.fetch_add(1, Ordering::SeqCst);
386                tokio::time::sleep(Duration::from_secs(10)).await;
387                Ok(NodeOutput::new())
388            }
389        });
390
391        let ctx = NodeContext::new(State::new(), ExecutionConfig::default(), 0);
392        let policy = TimeoutPolicy {
393            run_timeout: Some(Duration::from_millis(50)),
394            idle_timeout: None,
395            on_timeout: OnTimeout::Retry { max_attempts: 3 },
396        };
397
398        let result = execute_with_timeout(&node, &ctx, &policy).await;
399        assert!(result.is_err());
400        assert_eq!(attempt_count.load(Ordering::SeqCst), 3);
401    }
402
403    #[tokio::test]
404    async fn test_fast_node_with_timeout_succeeds() {
405        let node = FunctionNode::new("fast", |_ctx| async {
406            Ok(NodeOutput::new().with_update("value", serde_json::json!(42)))
407        });
408
409        let ctx = NodeContext::new(State::new(), ExecutionConfig::default(), 0);
410        let policy = TimeoutPolicy {
411            run_timeout: Some(Duration::from_secs(5)),
412            idle_timeout: None,
413            on_timeout: OnTimeout::Fail,
414        };
415
416        let result = execute_with_timeout(&node, &ctx, &policy).await;
417        assert!(result.is_ok());
418        let output = result.unwrap();
419        assert_eq!(output.updates.get("value"), Some(&serde_json::json!(42)));
420    }
421
422    #[test]
423    fn test_progress_handle_updates_timestamp() {
424        let handle = ProgressHandle::new();
425        let initial = handle.last_progress_ms();
426
427        // Small sleep to ensure time advances
428        std::thread::sleep(Duration::from_millis(10));
429        handle.report_progress();
430
431        let updated = handle.last_progress_ms();
432        assert!(updated >= initial);
433    }
434}