Skip to main content

regula_core/
error.rs

1//! Error types for REGULA framework.
2//!
3//! This module defines the comprehensive error enum used throughout the framework,
4//! covering graph construction, execution, state management, checkpointing, and LLM errors.
5
6use std::time::Duration;
7use thiserror::Error;
8
9/// The main error type for REGULA operations.
10///
11/// This enum covers all possible error conditions that can occur during
12/// graph construction, compilation, and execution.
13#[derive(Error, Debug)]
14pub enum RegulaError {
15    // =========================================================================
16    // Graph Construction Errors
17    // =========================================================================
18    /// A node with this name already exists in the graph.
19    #[error("Node '{0}' already exists in graph")]
20    DuplicateNode(String),
21
22    /// The specified node was not found in the graph.
23    #[error("Node '{0}' not found in graph")]
24    NodeNotFound(String),
25
26    /// An edge references a non-existent source node.
27    #[error("Invalid edge: source node '{0}' does not exist")]
28    InvalidEdgeSource(String),
29
30    /// An edge references a non-existent target node.
31    #[error("Invalid edge: target node '{0}' does not exist")]
32    InvalidEdgeTarget(String),
33
34    /// The graph has no entry point (no edge from START).
35    #[error("Graph has no entry point (no edge from START)")]
36    NoEntryPoint,
37
38    /// The graph contains a cycle without a valid exit condition.
39    #[error("Graph contains a cycle without exit condition: {0}")]
40    InvalidCycle(String),
41
42    /// A node has no incoming edges and is unreachable.
43    #[error("Unreachable node: '{0}' has no incoming edges")]
44    UnreachableNode(String),
45
46    /// Multiple edges from the same source without conditional routing.
47    #[error("Ambiguous routing: node '{0}' has multiple outgoing edges without conditional routing")]
48    AmbiguousRouting(String),
49
50    /// A conditional edge has no valid targets defined.
51    #[error("Conditional edge from '{0}' has no valid targets")]
52    NoConditionalTargets(String),
53
54    // =========================================================================
55    // Execution Errors
56    // =========================================================================
57    /// A node's execution failed.
58    #[error("Node '{node}' execution failed: {message}")]
59    NodeExecution {
60        /// The name of the node that failed.
61        node: String,
62        /// The error message.
63        message: String,
64        /// The underlying error, if any.
65        #[source]
66        source: Option<Box<dyn std::error::Error + Send + Sync>>,
67    },
68
69    /// A router returned an invalid or unknown target node.
70    #[error("Router for node '{0}' returned invalid target: '{1}'")]
71    InvalidRouteTarget(String, String),
72
73    /// The graph exceeded the maximum number of iterations.
74    #[error("Maximum iterations ({0}) exceeded - possible infinite loop")]
75    MaxIterationsExceeded(usize),
76
77    /// Graph execution was interrupted by a breakpoint or interrupt() call.
78    #[error("Graph execution was interrupted at node '{0}'")]
79    Interrupted(String),
80
81    /// Graph execution was cancelled.
82    #[error("Graph execution was cancelled")]
83    Cancelled,
84
85    /// The graph has already completed and cannot continue.
86    #[error("Graph has already completed execution")]
87    AlreadyCompleted,
88
89    /// No pending tasks to execute.
90    #[error("No pending tasks to execute")]
91    NoPendingTasks,
92
93    // =========================================================================
94    // State / Channel Errors
95    // =========================================================================
96    /// Attempted to read from a channel that has no value.
97    #[error("Channel '{0}' is empty (no value set)")]
98    EmptyChannel(String),
99
100    /// Type mismatch when reading or writing a channel.
101    #[error("Channel '{channel}' type mismatch: expected {expected}, got {actual}")]
102    ChannelTypeMismatch {
103        /// The channel name.
104        channel: String,
105        /// The expected type.
106        expected: String,
107        /// The actual type encountered.
108        actual: String,
109    },
110
111    /// A reducer function failed to combine values.
112    #[error("Failed to apply reducer on channel '{channel}': {message}")]
113    ReducerFailed {
114        /// The channel name.
115        channel: String,
116        /// The error message.
117        message: String,
118    },
119
120    /// State serialization or deserialization failed.
121    #[error("State serialization failed: {0}")]
122    StateSerialization(#[from] serde_json::Error),
123
124    /// A required state field is missing.
125    #[error("Required state field '{0}' is missing")]
126    MissingStateField(String),
127
128    /// State update contained an unknown field.
129    #[error("Unknown field in state update: '{0}'")]
130    UnknownStateField(String),
131
132    // =========================================================================
133    // Checkpoint Errors
134    // =========================================================================
135    /// No checkpoint found for the given thread ID.
136    #[error("Checkpoint not found for thread '{0}'")]
137    CheckpointNotFound(String),
138
139    /// Checkpoint storage operation failed.
140    #[error("Checkpoint storage error: {0}")]
141    CheckpointStorage(String),
142
143    /// Failed to deserialize a checkpoint.
144    #[error("Checkpoint deserialization failed: {0}")]
145    CheckpointDeserialization(String),
146
147    /// Checkpoint version mismatch.
148    #[error("Checkpoint version mismatch: expected {expected}, got {actual}")]
149    CheckpointVersionMismatch {
150        /// The expected version.
151        expected: String,
152        /// The actual version.
153        actual: String,
154    },
155
156    /// No checkpointer configured but checkpoint operation requested.
157    #[error("No checkpointer configured")]
158    NoCheckpointer,
159
160    // =========================================================================
161    // LLM Errors
162    // =========================================================================
163    /// HTTP request to LLM API failed.
164    #[error("LLM API request failed: {0}")]
165    LlmRequest(String),
166
167    /// LLM API returned an error response.
168    #[error("LLM API error (status {status}): {message}")]
169    LlmApiError {
170        /// HTTP status code.
171        status: u16,
172        /// Error message from the API.
173        message: String,
174    },
175
176    /// Failed to parse LLM response.
177    #[error("LLM response parsing failed: {0}")]
178    LlmResponseParse(String),
179
180    /// LLM API rate limit exceeded.
181    #[error("LLM rate limited, retry after {retry_after:?}")]
182    LlmRateLimited {
183        /// Suggested retry delay, if provided.
184        retry_after: Option<Duration>,
185    },
186
187    /// Error during LLM streaming.
188    #[error("LLM streaming error: {0}")]
189    LlmStreaming(String),
190
191    /// LLM API key is missing or invalid.
192    #[error("LLM API key is missing or invalid")]
193    LlmApiKeyMissing,
194
195    /// LLM request timed out.
196    #[error("LLM request timed out after {0:?}")]
197    LlmTimeout(Duration),
198
199    // =========================================================================
200    // Configuration Errors
201    // =========================================================================
202    /// Invalid configuration value.
203    #[error("Invalid configuration: {0}")]
204    InvalidConfig(String),
205
206    /// Required configuration is missing.
207    #[error("Missing required configuration: {0}")]
208    MissingConfig(String),
209
210    /// Configuration key not found in context.
211    #[error("Configuration key '{0}' not found in context")]
212    ConfigKeyNotFound(String),
213
214    /// Configuration value type mismatch.
215    #[error("Configuration key '{key}' type mismatch: expected {expected}")]
216    ConfigTypeMismatch {
217        /// The configuration key.
218        key: String,
219        /// The expected type.
220        expected: String,
221    },
222
223    // =========================================================================
224    // Generic Errors
225    // =========================================================================
226    /// Internal framework error.
227    #[error("Internal error: {0}")]
228    Internal(String),
229
230    /// Lock acquisition failed (concurrency error).
231    #[error("Failed to acquire lock: {0}")]
232    LockError(String),
233
234    /// Generic I/O error.
235    #[error("I/O error: {0}")]
236    Io(#[from] std::io::Error),
237
238    /// Wrapper for other error types.
239    #[error(transparent)]
240    Other(#[from] anyhow::Error),
241}
242
243impl RegulaError {
244    /// Create a node execution error with a source error.
245    pub fn node_execution(
246        node: impl Into<String>,
247        source: impl std::error::Error + Send + Sync + 'static,
248    ) -> Self {
249        let message = source.to_string();
250        Self::NodeExecution {
251            node: node.into(),
252            message,
253            source: Some(Box::new(source)),
254        }
255    }
256
257    /// Create a node execution error with just a message.
258    pub fn node_execution_msg(node: impl Into<String>, message: impl Into<String>) -> Self {
259        Self::NodeExecution {
260            node: node.into(),
261            message: message.into(),
262            source: None,
263        }
264    }
265
266    /// Check if this error is retryable.
267    pub fn is_retryable(&self) -> bool {
268        matches!(
269            self,
270            Self::LlmRateLimited { .. }
271                | Self::LlmTimeout(_)
272                | Self::LlmRequest(_)
273                | Self::LockError(_)
274        )
275    }
276
277    /// Check if this error is a cancellation.
278    pub fn is_cancelled(&self) -> bool {
279        matches!(self, Self::Cancelled | Self::Interrupted(_))
280    }
281}
282
283/// Result type alias for REGULA operations.
284pub type Result<T> = std::result::Result<T, RegulaError>;
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    #[test]
291    fn test_error_display() {
292        let err = RegulaError::DuplicateNode("agent".to_string());
293        assert_eq!(err.to_string(), "Node 'agent' already exists in graph");
294    }
295
296    #[test]
297    fn test_node_execution_error() {
298        let err = RegulaError::node_execution_msg("agent", "connection refused");
299        assert!(err.to_string().contains("agent"));
300        assert!(err.to_string().contains("connection refused"));
301    }
302
303    #[test]
304    fn test_is_retryable() {
305        assert!(RegulaError::LlmRateLimited { retry_after: None }.is_retryable());
306        assert!(RegulaError::LlmTimeout(Duration::from_secs(30)).is_retryable());
307        assert!(!RegulaError::Cancelled.is_retryable());
308    }
309}