Skip to main content

gadk_engine/
error.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Workflow errors: the sentinel kinds, [`WorkflowError`] and the dynamic child failure
17//! [`NodeRunError`].
18
19use std::sync::Arc;
20
21use gadk_agent::AgentError;
22
23/// The sentinel kinds of [`WorkflowError`].
24#[non_exhaustive]
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum WorkflowErrorKind {
27    /// A dynamic child node failed.
28    NodeFailed,
29    /// A dynamic child node was interrupted.
30    NodeInterrupted,
31    /// A dynamic child node is waiting for output; also counts as [`Self::NodeInterrupted`].
32    NodeWaitingForOutput,
33    /// `RunNode` was called outside a dynamic node.
34    InvalidRunNodeContext,
35    /// The run id is invalid.
36    InvalidRunId,
37    /// Parallel human-in-the-loop interrupts are not supported.
38    ParallelHitlUnsupported,
39    /// Node input failed validation.
40    InputValidation,
41    /// Output validation failed; also counts as [`Self::NodeFailed`].
42    OutputValidation,
43    /// The parent already has a `use_as_output` delegate.
44    OutputAlreadyDelegated,
45    /// A node produced more than one event carrying an output value.
46    MultipleOutputs,
47    /// A node produced more than one event carrying route tags.
48    MultipleRoutingEvents,
49    /// More than one terminal node produced output.
50    MultipleTerminalOutputs,
51    /// Two nodes share a name.
52    DuplicateNodeName,
53    /// The graph has no start node.
54    NoStartNode,
55    /// An edge points to the start node.
56    NodePointsToStart,
57    /// The same edge was declared twice.
58    DuplicateEdge,
59    /// A node has more than one default route.
60    MultipleDefaultRoutes,
61    /// Some nodes are not reachable from the start node.
62    NodesNotReachable,
63    /// The graph has a cycle of unconditional edges.
64    UnconditionalCycle,
65    /// Two sub-workflows share a name.
66    SubWorkflowNameCollision,
67    /// Fan-in into a node that is not a join node is not supported.
68    UnsupportedFanIn,
69    /// A resume response does not match the request's schema.
70    InvalidResumeResponse,
71    /// No waiting node matched the supplied resume responses.
72    NothingToResume,
73    /// Retries were exhausted (Rust-only kind).
74    RetryExhausted,
75    /// A persistence operation failed (Rust-only kind).
76    Persistence,
77    /// Any other workflow error (Rust-only kind).
78    Other,
79}
80
81/// A workflow error: a sentinel kind, its full message text, and an optional cause.
82#[derive(Debug, Clone)]
83pub struct WorkflowError {
84    kind: WorkflowErrorKind,
85    message: String,
86    source: Option<Arc<AgentError>>,
87    node_run: Option<NodeRunError>,
88}
89
90/// A dynamic child run failed. `cause: None` means the child reported no cause.
91#[derive(Debug, Clone)]
92pub struct NodeRunError {
93    /// The child node's name.
94    pub child_name: String,
95    /// The child node's path (`<parent>/<child>@<run_id>`); may be empty.
96    pub child_path: String,
97    /// The child run's id.
98    pub run_id: String,
99    /// The error the child run failed with.
100    pub cause: Option<Arc<AgentError>>,
101}
102
103impl WorkflowError {
104    /// A workflow error of `kind` whose text is `message`, the full text built by the caller (e.g.
105    /// `"<sentinel text>: <detail>"`).
106    pub fn new(kind: WorkflowErrorKind, message: impl Into<String>) -> Self {
107        Self {
108            kind,
109            message: message.into(),
110            source: None,
111            node_run: None,
112        }
113    }
114
115    /// Sets the wrapped cause; the message is unchanged, since the caller already formatted it.
116    pub fn with_source(mut self, source: AgentError) -> Self {
117        self.source = Some(Arc::new(source));
118        self
119    }
120
121    /// The error's kind.
122    pub fn kind(&self) -> WorkflowErrorKind {
123        self.kind
124    }
125
126    /// Whether this error is of `kind`: its own kind, a kind it implies (`NodeWaitingForOutput`
127    /// implies `NodeInterrupted`, `OutputValidation` implies `NodeFailed`), or the same test on the
128    /// wrapped cause.
129    pub fn is(&self, kind: WorkflowErrorKind) -> bool {
130        self.kind == kind
131            || (self.kind == WorkflowErrorKind::NodeWaitingForOutput
132                && kind == WorkflowErrorKind::NodeInterrupted)
133            || (self.kind == WorkflowErrorKind::OutputValidation
134                && kind == WorkflowErrorKind::NodeFailed)
135            || self
136                .source
137                .as_deref()
138                .and_then(workflow_error)
139                .is_some_and(|w| w.is(kind))
140    }
141
142    /// The message text of the bare sentinel for `kind`.
143    pub fn sentinel_text(kind: WorkflowErrorKind) -> &'static str {
144        use WorkflowErrorKind as K;
145        match kind {
146            K::NodeFailed => "workflow: dynamic child failed",
147            K::NodeInterrupted => "workflow: dynamic child interrupted",
148            K::NodeWaitingForOutput => "workflow: dynamic child interrupted: waiting for output",
149            K::InvalidRunNodeContext => "workflow: RunNode called outside a dynamic node",
150            K::InvalidRunId => "workflow: invalid run id",
151            K::ParallelHitlUnsupported => "workflow: parallel HITL is not supported",
152            K::InputValidation => "workflow: input validation failed",
153            K::OutputValidation => "output validation failed",
154            K::OutputAlreadyDelegated => "workflow: parent already has a use_as_output delegate",
155            K::MultipleOutputs => {
156                "workflow: node produced multiple events with output values; only one event per execution can carry output"
157            }
158            K::MultipleRoutingEvents => {
159                "workflow: node produced multiple events with route tags; only one event per execution can specify routes"
160            }
161            K::MultipleTerminalOutputs => {
162                "workflow: multiple terminal nodes produced output; a workflow must have at most one terminal output"
163            }
164            K::DuplicateNodeName => "duplicate node name",
165            K::NoStartNode => "no start node found",
166            K::NodePointsToStart => "node points to start node",
167            K::DuplicateEdge => "duplicate edge",
168            K::MultipleDefaultRoutes => "node has more than one default route",
169            K::NodesNotReachable => "nodes not reachable from start node",
170            K::UnconditionalCycle => "unconditional cycle detected",
171            K::SubWorkflowNameCollision => "sub-workflow name collision",
172            K::UnsupportedFanIn => "non-JoinNode fan-in is not yet supported",
173            K::InvalidResumeResponse => "workflow: resume response does not match request schema",
174            K::NothingToResume => "workflow: no waiting node matched the supplied responses",
175            K::RetryExhausted => "workflow: retries exhausted",
176            K::Persistence => "workflow: persistence error",
177            K::Other => "workflow: error",
178        }
179    }
180
181    /// The bare sentinel error of `kind`, carrying [`Self::sentinel_text`].
182    pub fn sentinel(kind: WorkflowErrorKind) -> Self {
183        Self::new(kind, Self::sentinel_text(kind))
184    }
185
186    /// The wrapped cause, if any.
187    pub fn cause(&self) -> Option<&AgentError> {
188        self.source.as_deref()
189    }
190
191    /// A dynamic child run failure: the kind is the cause's workflow kind, else `NodeFailed`; the
192    /// message names the child by path (or by name when the path is empty), followed by the cause,
193    /// or `<nil cause>` when there is none.
194    pub fn node_run(info: NodeRunError) -> Self {
195        // Before any such error can reach a span's `error.type`.
196        crate::telemetry::install_go_error_type_resolver();
197        let path = if info.child_path.is_empty() {
198            &info.child_name
199        } else {
200            &info.child_path
201        };
202        let message = match &info.cause {
203            Some(cause) => format!("workflow: dynamic child {path}: {cause}"),
204            None => format!("workflow: dynamic child {path}: <nil cause>"),
205        };
206        let kind = info
207            .cause
208            .as_deref()
209            .and_then(workflow_error)
210            .map_or(WorkflowErrorKind::NodeFailed, |w| w.kind());
211        Self {
212            kind,
213            message,
214            source: info.cause.clone(),
215            node_run: Some(info),
216        }
217    }
218
219    /// The dynamic child run failure this error reports, if it is one.
220    pub fn node_run_error(&self) -> Option<&NodeRunError> {
221        self.node_run.as_ref()
222    }
223}
224
225/// The fixed type name reported as a span's `error.type` for a [`WorkflowError`] that reports a
226/// dynamic child run failure (the literal below); other errors are not named.
227pub(crate) fn go_error_type(err: &(dyn std::error::Error + 'static)) -> Option<&'static str> {
228    err.downcast_ref::<WorkflowError>()
229        .and_then(WorkflowError::node_run_error)
230        .map(|_| "*workflow.NodeRunError")
231}
232
233impl std::fmt::Display for WorkflowError {
234    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235        f.write_str(&self.message)
236    }
237}
238
239impl std::error::Error for WorkflowError {
240    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
241        self.source
242            .as_deref()
243            .map(|e| e as &(dyn std::error::Error + 'static))
244    }
245}
246
247impl From<WorkflowError> for AgentError {
248    fn from(e: WorkflowError) -> Self {
249        AgentError::Workflow(Box::new(e))
250    }
251}
252
253/// The [`WorkflowError`] carried by `err`, if any (`AgentError::Workflow` or `AgentError::Other`).
254pub fn workflow_error(err: &AgentError) -> Option<&WorkflowError> {
255    match err {
256        AgentError::Workflow(b) | AgentError::Other(b) => b.downcast_ref::<WorkflowError>(),
257        _ => None,
258    }
259}
260
261#[cfg(test)]
262#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
263mod tests {
264    use super::*;
265
266    #[test]
267    fn waiting_for_output_is_also_interrupted() {
268        let e = WorkflowError::sentinel(WorkflowErrorKind::NodeWaitingForOutput);
269        assert!(e.is(WorkflowErrorKind::NodeWaitingForOutput));
270        assert!(e.is(WorkflowErrorKind::NodeInterrupted));
271        assert!(!e.is(WorkflowErrorKind::NodeFailed));
272        assert_eq!(
273            e.to_string(),
274            "workflow: dynamic child interrupted: waiting for output"
275        );
276    }
277
278    #[test]
279    fn output_validation_is_also_node_failed() {
280        let e = WorkflowError::new(WorkflowErrorKind::OutputValidation, "x");
281        assert!(e.is(WorkflowErrorKind::NodeFailed));
282    }
283
284    #[test]
285    fn is_walks_the_source_chain() {
286        let inner = WorkflowError::sentinel(WorkflowErrorKind::InputValidation);
287        let outer =
288            WorkflowError::new(WorkflowErrorKind::NodeFailed, "outer").with_source(inner.into());
289        assert!(outer.is(WorkflowErrorKind::InputValidation));
290        assert!(std::error::Error::source(&outer).is_some());
291    }
292
293    fn cause(kind: WorkflowErrorKind) -> Option<Arc<AgentError>> {
294        Some(Arc::new(WorkflowError::sentinel(kind).into()))
295    }
296
297    #[test]
298    fn node_run_formats_like_go() {
299        let e = WorkflowError::node_run(NodeRunError {
300            child_name: "fixer".into(),
301            child_path: "code_workflow/fixer@2".into(),
302            run_id: "2".into(),
303            cause: cause(WorkflowErrorKind::NodeFailed),
304        });
305        assert_eq!(
306            e.to_string(),
307            "workflow: dynamic child code_workflow/fixer@2: workflow: dynamic child failed"
308        );
309        assert!(e.is(WorkflowErrorKind::NodeFailed));
310        assert_eq!(e.node_run_error().unwrap().run_id, "2");
311        assert_eq!(
312            e.cause().unwrap().to_string(),
313            "workflow: dynamic child failed"
314        );
315        let by_name = WorkflowError::node_run(NodeRunError {
316            child_name: "fixer".into(),
317            child_path: String::new(),
318            run_id: String::new(),
319            cause: cause(WorkflowErrorKind::NodeInterrupted),
320        });
321        assert_eq!(
322            by_name.to_string(),
323            "workflow: dynamic child fixer: workflow: dynamic child interrupted"
324        );
325        assert_eq!(by_name.kind(), WorkflowErrorKind::NodeInterrupted);
326        // Go "<nil cause>": no source, kind falls back to NodeFailed.
327        let nil_cause = WorkflowError::node_run(NodeRunError {
328            child_name: String::new(),
329            child_path: "x/y@1".into(),
330            run_id: String::new(),
331            cause: None,
332        });
333        assert_eq!(
334            nil_cause.to_string(),
335            "workflow: dynamic child x/y@1: <nil cause>"
336        );
337        assert_eq!(nil_cause.kind(), WorkflowErrorKind::NodeFailed);
338        assert!(nil_cause.cause().is_none());
339        // A non-workflow cause also falls back to NodeFailed.
340        let plain = WorkflowError::node_run(NodeRunError {
341            child_name: "c".into(),
342            child_path: String::new(),
343            run_id: String::new(),
344            cause: Some(Arc::new(AgentError::other("boom"))),
345        });
346        assert_eq!(plain.kind(), WorkflowErrorKind::NodeFailed);
347        assert_eq!(plain.to_string(), "workflow: dynamic child c: boom");
348    }
349
350    #[test]
351    fn rust_only_sentinel_texts() {
352        assert_eq!(
353            WorkflowError::sentinel_text(WorkflowErrorKind::OutputValidation),
354            "output validation failed"
355        );
356        assert_eq!(
357            WorkflowError::sentinel_text(WorkflowErrorKind::RetryExhausted),
358            "workflow: retries exhausted"
359        );
360        assert_eq!(
361            WorkflowError::sentinel_text(WorkflowErrorKind::Persistence),
362            "workflow: persistence error"
363        );
364        assert_eq!(
365            WorkflowError::sentinel_text(WorkflowErrorKind::Other),
366            "workflow: error"
367        );
368    }
369
370    #[test]
371    fn workflow_error_downcasts_from_agent_error() {
372        let a: AgentError = WorkflowError::sentinel(WorkflowErrorKind::NoStartNode).into();
373        assert!(matches!(a, AgentError::Workflow(_)));
374        assert_eq!(
375            workflow_error(&a).unwrap().kind(),
376            WorkflowErrorKind::NoStartNode
377        );
378        assert_eq!(a.to_string(), "no start node found");
379        assert!(workflow_error(&AgentError::Cancelled).is_none());
380    }
381}