Skip to main content

adk_graph/
error.rs

1//! Error types for adk-graph
2
3use std::time::Duration;
4
5use crate::interrupt::Interrupt;
6use thiserror::Error;
7
8/// Result type for graph operations
9pub type Result<T> = std::result::Result<T, GraphError>;
10
11/// Errors that can occur during graph operations
12#[derive(Error, Debug)]
13#[non_exhaustive]
14pub enum GraphError {
15    /// Graph structure is invalid
16    #[error("Invalid graph structure: {0}")]
17    InvalidGraph(String),
18
19    /// Node not found
20    #[error("Node not found: {0}")]
21    NodeNotFound(String),
22
23    /// Edge target not found
24    #[error("Edge target not found: {0}")]
25    EdgeTargetNotFound(String),
26
27    /// No entry point defined
28    #[error("No entry point defined (missing edge from START)")]
29    NoEntryPoint,
30
31    /// Recursion limit exceeded
32    #[error("Recursion limit exceeded: {0} steps")]
33    RecursionLimitExceeded(usize),
34
35    /// Execution was interrupted
36    #[error("Execution interrupted: {0:?}")]
37    Interrupted(Box<InterruptedExecution>),
38
39    /// Node execution failed
40    #[error("Node '{node}' execution failed: {message}")]
41    NodeExecutionFailed { node: String, message: String },
42
43    /// The agent an [`AgentNode`](crate::node::AgentNode) runs failed.
44    ///
45    /// Carries the agent's own error, so its category, code, retry hint, and
46    /// upstream status reach the caller: a rate-limited model is still
47    /// `RateLimited` once the graph reports it.
48    #[error("node '{node}' agent failed: {source}")]
49    AgentFailed {
50        /// The node whose agent failed.
51        node: String,
52        /// The error the agent returned or yielded.
53        #[source]
54        source: Box<adk_core::AdkError>,
55    },
56
57    /// Node timed out
58    #[error("Node '{node}' timed out after {elapsed:?}")]
59    NodeTimedOut { node: String, elapsed: Duration },
60
61    /// Fan-in node timed out waiting for upstream paths
62    #[error("Fan-in node '{node}' timed out: received {received}/{expected} upstream outputs")]
63    FanInTimedOut { node: String, received: usize, expected: usize },
64
65    /// A fan-in node's remaining predecessors can no longer run, and fewer than
66    /// its `min_predecessors` arrived.
67    #[error(
68        "fan-in node '{node}' needs {required} upstream outputs but received {received}, and no \
69         other predecessor can still run in this pass. Lower `min_predecessors`, or route every \
70         required branch to the node"
71    )]
72    FanInIncomplete {
73        /// The fan-in node.
74        node: String,
75        /// How many predecessors arrived.
76        received: usize,
77        /// The `min_predecessors` it was configured with.
78        required: usize,
79    },
80
81    /// State serialization error
82    #[error("State serialization error: {0}")]
83    SerializationError(String),
84
85    /// Checkpoint error, including a failure of the checkpointer's database.
86    #[error("Checkpoint error: {0}")]
87    CheckpointError(String),
88
89    /// A checkpoint was refused because its thread already holds a checkpoint with an
90    /// equal or higher version.
91    ///
92    /// Raised when two writers continue one thread: the writer that falls behind is
93    /// refused instead of interleaving its checkpoints with the other's.
94    #[error(
95        "checkpoint version {version} for thread '{thread_id}' conflicts with stored version {head}. \
96         Another writer advanced the thread; reload its newest checkpoint and continue from version {head} + 1"
97    )]
98    CheckpointConflict {
99        /// The thread the checkpoint belongs to.
100        thread_id: String,
101        /// The version the writer tried to store.
102        version: u64,
103        /// The highest version already stored for the thread.
104        head: u64,
105    },
106
107    /// A node wrote a channel the state schema does not declare.
108    ///
109    /// Only raised when channel enforcement is on. An undeclared channel
110    /// otherwise takes the overwrite reducer, which silently discards the
111    /// appends a list channel was meant to collect.
112    #[error(
113        "node '{node}' wrote undeclared channel '{channel}'. Declare it on the graph, or drop the write"
114    )]
115    UndeclaredChannel {
116        /// The node that produced the update.
117        node: String,
118        /// The channel name that is not declared.
119        channel: String,
120    },
121
122    /// A subgraph mapping names a channel the relevant side does not declare.
123    #[error("subgraph '{subgraph}' maps channel '{channel}', which the {side} does not declare")]
124    SubgraphChannelMismatch {
125        /// The subgraph node's name.
126        subgraph: String,
127        /// The channel that is not declared.
128        channel: String,
129        /// Which side is missing it, the parent or the subgraph.
130        side: String,
131    },
132
133    /// Router returned unknown target
134    #[error("Router returned unknown target: {0}")]
135    UnknownRouteTarget(String),
136
137    /// IO error
138    #[error("IO error: {0}")]
139    IoError(#[from] std::io::Error),
140
141    /// JSON error
142    #[error("JSON error: {0}")]
143    JsonError(#[from] serde_json::Error),
144
145    /// A functional-API workflow suspended at an interrupt and needs an answer.
146    ///
147    /// Supply the answer under `continuation_key` with
148    /// [`ExecutionConfig::with_resume_value`](crate::node::ExecutionConfig::with_resume_value)
149    /// and invoke the entrypoint again. A `#[task]` retry policy does not retry it.
150    #[error("workflow suspended at interrupt '{continuation_key}': {message}")]
151    Suspended {
152        /// Key identifying the interrupt site within the thread.
153        continuation_key: String,
154        /// The message passed to the interrupt.
155        message: String,
156    },
157
158    /// A resume answer was refused before any node ran: it does not satisfy the
159    /// pause's `response_schema`, or, under
160    /// [`ExecutionConfig::strict_resume`](crate::node::ExecutionConfig::strict_resume),
161    /// its key is not the id of a pause pending in the thread. The checkpoint is
162    /// unchanged, so the run can be resumed again with a valid answer.
163    #[error("resume answer '{key}' refused: {reason}")]
164    ResumeRejected {
165        /// The key the answer was supplied under: an interrupt id or a node name.
166        key: String,
167        /// Why it was refused.
168        reason: String,
169    },
170
171    /// The caller cancelled a functional-API run.
172    ///
173    /// Raised when the run's
174    /// [`ExecutionConfig::cancellation_token`](crate::node::ExecutionConfig) is
175    /// cancelled. A `#[task]` retry policy does not retry it.
176    #[error("workflow cancelled")]
177    Cancelled,
178
179    /// Other error (used by extensions like the functional API)
180    #[error("{0}")]
181    Other(String),
182}
183
184/// Information about an interrupted execution
185#[derive(Debug, Clone)]
186pub struct InterruptedExecution {
187    /// Thread ID for resumption
188    pub thread_id: String,
189    /// Checkpoint ID for resumption
190    pub checkpoint_id: String,
191    /// The interrupt that occurred: the first of [`Self::interrupts`].
192    pub interrupt: Interrupt,
193    /// Every pause of the step, in node-name order.
194    ///
195    /// Nodes of one super-step run together, so several can pause at once, such
196    /// as two agent nodes each asking to confirm a tool call. A static gate is a
197    /// single pause.
198    pub interrupts: Vec<Interrupt>,
199    /// Current state at interruption
200    pub state: crate::state::State,
201    /// Step number when interrupted
202    pub step: usize,
203}
204
205impl InterruptedExecution {
206    /// Create a new interrupted execution with a single pause.
207    pub fn new(
208        thread_id: String,
209        checkpoint_id: String,
210        interrupt: Interrupt,
211        state: crate::state::State,
212        step: usize,
213    ) -> Self {
214        let interrupts = vec![interrupt.clone()];
215        Self { thread_id, checkpoint_id, interrupt, interrupts, state, step }
216    }
217
218    /// Records every pause of the step; the first stays [`Self::interrupt`].
219    ///
220    /// An empty list leaves the single pause given to [`Self::new`].
221    #[must_use]
222    pub fn with_interrupts(mut self, interrupts: Vec<Interrupt>) -> Self {
223        if let Some(first) = interrupts.first() {
224            self.interrupt = first.clone();
225            self.interrupts = interrupts;
226        }
227        self
228    }
229}
230
231/// Converts a graph error into the structured ADK error.
232///
233/// A [`GraphError::AgentFailed`] becomes the agent's own error, with the node
234/// named in its message, so its category, code, and retry hint are unchanged.
235/// Every other variant maps to an `ErrorComponent::Graph` error that carries the
236/// graph error as its source.
237impl From<GraphError> for adk_core::AdkError {
238    fn from(err: GraphError) -> Self {
239        use adk_core::{ErrorCategory, ErrorComponent};
240        if let GraphError::AgentFailed { node, source } = err {
241            let mut error = *source;
242            error.message = format!("graph node '{node}': {}", error.message);
243            return error;
244        }
245        let (category, code) = match &err {
246            GraphError::InvalidGraph(_) => (ErrorCategory::InvalidInput, "graph.invalid"),
247            GraphError::NodeNotFound(_) => (ErrorCategory::NotFound, "graph.node_not_found"),
248            GraphError::EdgeTargetNotFound(_) => {
249                (ErrorCategory::NotFound, "graph.edge_target_not_found")
250            }
251            GraphError::NoEntryPoint => (ErrorCategory::InvalidInput, "graph.no_entry_point"),
252            GraphError::RecursionLimitExceeded(_) => {
253                (ErrorCategory::Internal, "graph.recursion_limit")
254            }
255            GraphError::Interrupted(_) => (ErrorCategory::Cancelled, "graph.interrupted"),
256            GraphError::NodeExecutionFailed { .. } => {
257                (ErrorCategory::Internal, "graph.node_execution_failed")
258            }
259            GraphError::AgentFailed { source, .. } => (source.category, source.code),
260            GraphError::NodeTimedOut { .. } => (ErrorCategory::Timeout, "graph.node_timed_out"),
261            GraphError::FanInTimedOut { .. } => (ErrorCategory::Timeout, "graph.fan_in_timed_out"),
262            GraphError::FanInIncomplete { .. } => {
263                (ErrorCategory::Internal, "graph.fan_in_incomplete")
264            }
265            GraphError::SerializationError(_) => (ErrorCategory::Internal, "graph.serialization"),
266            GraphError::CheckpointError(_) => (ErrorCategory::Internal, "graph.checkpoint"),
267            GraphError::CheckpointConflict { .. } => {
268                (ErrorCategory::InvalidInput, "graph.checkpoint.conflict")
269            }
270            GraphError::SubgraphChannelMismatch { .. } => {
271                (ErrorCategory::InvalidInput, "graph.subgraph_channel_mismatch")
272            }
273            GraphError::UndeclaredChannel { .. } => {
274                (ErrorCategory::InvalidInput, "graph.undeclared_channel")
275            }
276            GraphError::UnknownRouteTarget(_) => {
277                (ErrorCategory::NotFound, "graph.unknown_route_target")
278            }
279            GraphError::Suspended { .. } => (ErrorCategory::Cancelled, "graph.suspended"),
280            GraphError::ResumeRejected { .. } => {
281                (ErrorCategory::InvalidInput, "graph.resume_rejected")
282            }
283            GraphError::Cancelled => (ErrorCategory::Cancelled, "graph.cancelled"),
284            GraphError::IoError(_) => (ErrorCategory::Internal, "graph.io"),
285            GraphError::JsonError(_) => (ErrorCategory::Internal, "graph.json"),
286            GraphError::Other(_) => (ErrorCategory::Internal, "graph.other"),
287        };
288        adk_core::AdkError::new(ErrorComponent::Graph, category, code, err.to_string())
289            .with_source(err)
290    }
291}