1use std::sync::Arc;
20
21use gadk_agent::AgentError;
22
23#[non_exhaustive]
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum WorkflowErrorKind {
27 NodeFailed,
29 NodeInterrupted,
31 NodeWaitingForOutput,
33 InvalidRunNodeContext,
35 InvalidRunId,
37 ParallelHitlUnsupported,
39 InputValidation,
41 OutputValidation,
43 OutputAlreadyDelegated,
45 MultipleOutputs,
47 MultipleRoutingEvents,
49 MultipleTerminalOutputs,
51 DuplicateNodeName,
53 NoStartNode,
55 NodePointsToStart,
57 DuplicateEdge,
59 MultipleDefaultRoutes,
61 NodesNotReachable,
63 UnconditionalCycle,
65 SubWorkflowNameCollision,
67 UnsupportedFanIn,
69 InvalidResumeResponse,
71 NothingToResume,
73 RetryExhausted,
75 Persistence,
77 Other,
79}
80
81#[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#[derive(Debug, Clone)]
92pub struct NodeRunError {
93 pub child_name: String,
95 pub child_path: String,
97 pub run_id: String,
99 pub cause: Option<Arc<AgentError>>,
101}
102
103impl WorkflowError {
104 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 pub fn with_source(mut self, source: AgentError) -> Self {
117 self.source = Some(Arc::new(source));
118 self
119 }
120
121 pub fn kind(&self) -> WorkflowErrorKind {
123 self.kind
124 }
125
126 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 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: run_node 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 pub fn sentinel(kind: WorkflowErrorKind) -> Self {
183 Self::new(kind, Self::sentinel_text(kind))
184 }
185
186 pub fn cause(&self) -> Option<&AgentError> {
188 self.source.as_deref()
189 }
190
191 pub fn node_run(info: NodeRunError) -> Self {
195 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}: <no 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 pub fn node_run_error(&self) -> Option<&NodeRunError> {
221 self.node_run.as_ref()
222 }
223}
224
225pub(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
253pub 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 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: <no cause>"
336 );
337 assert_eq!(nil_cause.kind(), WorkflowErrorKind::NodeFailed);
338 assert!(nil_cause.cause().is_none());
339 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}