Skip to main content

a3s_code_core/
error.rs

1//! Typed error enum for A3S Code Core
2//!
3//! Provides categorized errors that SDK consumers can match on programmatically,
4//! instead of receiving opaque `anyhow::Error` strings.
5//!
6//! ## Migration Strategy
7//!
8//! The `Internal` variant wraps `anyhow::Error` via `#[from]`, allowing
9//! gradual migration: call sites that haven't been updated yet auto-convert
10//! through `?`. Over time, each call site replaces `anyhow::anyhow!(...)`
11//! with a specific variant like `CodeError::Config(...)`.
12
13use thiserror::Error;
14
15/// Async resource whose initialization is part of building a session.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum SessionBuildResource {
18    Capability,
19    MemoryStore,
20    MemoryMaintenance,
21    SessionStore,
22    Queue,
23    Mcp,
24    RlTrajectory,
25    WorkspaceRetrieval,
26}
27
28impl std::fmt::Display for SessionBuildResource {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        f.write_str(match self {
31            Self::Capability => "capability runtime",
32            Self::MemoryStore => "memory store",
33            Self::MemoryMaintenance => "memory maintenance",
34            Self::SessionStore => "session store",
35            Self::Queue => "session queue",
36            Self::Mcp => "MCP",
37            Self::RlTrajectory => "RL trajectory recorder",
38            Self::WorkspaceRetrieval => "workspace retrieval",
39        })
40    }
41}
42
43/// Crate-wide result type alias.
44pub type Result<T> = std::result::Result<T, CodeError>;
45
46/// Categorized error type for A3S Code Core.
47///
48/// SDK bindings (Python/Node) can match on the variant to expose typed
49/// exceptions (e.g., `CodeConfigError`, `CodeLlmError`).
50#[derive(Debug, Error)]
51pub enum CodeError {
52    /// Configuration loading or parsing error
53    #[error("Config error: {0}")]
54    Config(String),
55
56    /// LLM provider communication error
57    #[error("LLM error: {0}")]
58    Llm(String),
59
60    /// Tool execution error
61    #[error("Tool error: {tool}: {message}")]
62    Tool { tool: String, message: String },
63
64    /// Session management error
65    #[error("Session error: {0}")]
66    Session(String),
67
68    /// A session option is missing, malformed, or conflicts with another option.
69    #[error("Invalid session configuration for '{field}': {message}")]
70    SessionConfiguration {
71        field: &'static str,
72        message: String,
73    },
74
75    /// A session resource could not be initialized.
76    #[error("Failed to initialize {resource}: {message}")]
77    SessionInitialization {
78        resource: SessionBuildResource,
79        message: String,
80    },
81
82    /// The synchronous compatibility factory was asked to initialize an
83    /// async-only resource. Call `Agent::session_builder(...).build().await`.
84    #[error(
85        "{resource} requires asynchronous session construction; use Agent::session_builder(...).build().await"
86    )]
87    AsyncSessionBuildRequired { resource: SessionBuildResource },
88
89    /// Session has been closed; further operations are rejected.
90    ///
91    /// Returned by `send`/`stream` (and their variants) after
92    /// [`AgentSession::close`](crate::agent_api::AgentSession::close)
93    /// — or [`Agent::close`](crate::agent_api::Agent::close) — has been called.
94    #[error("Session '{session_id}' is closed")]
95    SessionClosed { session_id: String },
96
97    /// Another conversation operation is already active on this session.
98    ///
99    /// Sessions serialize conversation state, so callers must wait for the
100    /// active operation's returned future or stream handle to finish before
101    /// starting another one.
102    #[error("Session '{session_id}' already has an active operation")]
103    SessionBusy { session_id: String },
104
105    /// Global task admission was cancelled before an execution slot opened.
106    #[error("Task admission for session '{session_id}' was cancelled")]
107    TaskAdmissionCancelled { session_id: String },
108
109    /// The owning agent's global task scheduler no longer accepts work.
110    #[error("Task scheduler is closed")]
111    TaskSchedulerClosed,
112
113    /// A host replayed a run id with different immutable session or input
114    /// identity. The existing run is preserved and no work is started.
115    #[error("Run '{run_id}' is already bound to different immutable input")]
116    RunIdentityConflict { run_id: String },
117
118    /// A host-supplied [`BudgetGuard`](crate::budget::BudgetGuard) denied
119    /// the operation. The session is not closed — callers can re-try
120    /// after the host has re-allocated budget.
121    #[error("Budget exhausted on '{resource}': {reason}")]
122    BudgetExhausted { resource: String, reason: String },
123
124    /// Security subsystem error
125    #[error("Security error: {0}")]
126    Security(String),
127
128    /// Context provider or context store error
129    #[error("Context error: {0}")]
130    Context(String),
131
132    /// MCP (Model Context Protocol) error
133    #[error("MCP error: {0}")]
134    Mcp(String),
135
136    /// Queue or lane error
137    #[error("Queue error: {0}")]
138    Queue(String),
139
140    /// Atomic Session capability publication or Run admission failure.
141    #[error("Capability runtime error: {0}")]
142    Capability(#[from] crate::capability::CapabilityRuntimeError),
143
144    /// A3S Flow definition, replay, store, or runtime failure.
145    #[error("Flow error: {0}")]
146    Flow(#[from] a3s_flow::FlowError),
147
148    /// I/O error
149    #[error("IO error: {0}")]
150    Io(#[from] std::io::Error),
151
152    /// JSON serialization/deserialization error
153    #[error("Serialization error: {0}")]
154    Serialization(#[from] serde_json::Error),
155
156    /// Catch-all for errors not yet migrated to a specific variant.
157    ///
158    /// The `#[from] anyhow::Error` conversion enables gradual migration:
159    /// any function returning `anyhow::Result` can be called with `?` from
160    /// a function returning `crate::error::Result` without changes.
161    #[error("{0:#}")]
162    Internal(#[from] anyhow::Error),
163}
164
165impl CodeError {
166    /// Stable machine-readable code for SDK and service boundaries.
167    pub const fn code(&self) -> &'static str {
168        match self {
169            Self::Config(_) => "CONFIG_ERROR",
170            Self::Llm(_) => "LLM_ERROR",
171            Self::Tool { .. } => "TOOL_ERROR",
172            Self::Session(_) => "SESSION_ERROR",
173            Self::SessionConfiguration { .. } => "SESSION_CONFIGURATION_ERROR",
174            Self::SessionInitialization { .. } => "SESSION_INITIALIZATION_ERROR",
175            Self::AsyncSessionBuildRequired { .. } => "ASYNC_SESSION_BUILD_REQUIRED",
176            Self::SessionClosed { .. } => "SESSION_CLOSED",
177            Self::SessionBusy { .. } => "SESSION_BUSY",
178            Self::TaskAdmissionCancelled { .. } => "TASK_ADMISSION_CANCELLED",
179            Self::TaskSchedulerClosed => "TASK_SCHEDULER_CLOSED",
180            Self::RunIdentityConflict { .. } => "RUN_IDENTITY_CONFLICT",
181            Self::BudgetExhausted { .. } => "BUDGET_EXHAUSTED",
182            Self::Security(_) => "SECURITY_ERROR",
183            Self::Context(_) => "CONTEXT_ERROR",
184            Self::Mcp(_) => "MCP_ERROR",
185            Self::Queue(_) => "QUEUE_ERROR",
186            Self::Capability(_) => "CAPABILITY_RUNTIME_ERROR",
187            Self::Flow(_) => "FLOW_ERROR",
188            Self::Io(_) => "IO_ERROR",
189            Self::Serialization(_) => "SERIALIZATION_ERROR",
190            Self::Internal(_) => "INTERNAL_ERROR",
191        }
192    }
193}
194
195// ============================================================================
196// Lock Poisoning Helpers (Phase 3b)
197// ============================================================================
198
199/// Acquire a read guard, recovering from poison if the lock was poisoned.
200///
201/// Non-security code should never panic on a poisoned lock. The data may
202/// be in an inconsistent state, but crashing the entire process is worse
203/// than serving stale data in a coding agent context.
204pub(crate) fn read_or_recover<T>(lock: &std::sync::RwLock<T>) -> std::sync::RwLockReadGuard<'_, T> {
205    lock.read().unwrap_or_else(|p| p.into_inner())
206}
207
208/// Acquire a write guard, recovering from poison if the lock was poisoned.
209///
210/// See [`read_or_recover`] for rationale.
211pub(crate) fn write_or_recover<T>(
212    lock: &std::sync::RwLock<T>,
213) -> std::sync::RwLockWriteGuard<'_, T> {
214    lock.write().unwrap_or_else(|p| p.into_inner())
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220
221    #[test]
222    fn test_code_error_config() {
223        let err = CodeError::Config("missing API key".to_string());
224        assert!(err.to_string().contains("Config error"));
225        assert!(err.to_string().contains("missing API key"));
226    }
227
228    #[test]
229    fn test_code_error_llm() {
230        let err = CodeError::Llm("rate limited".to_string());
231        assert!(err.to_string().contains("LLM error"));
232    }
233
234    #[test]
235    fn test_code_error_tool() {
236        let err = CodeError::Tool {
237            tool: "bash".to_string(),
238            message: "command not found".to_string(),
239        };
240        let msg = err.to_string();
241        assert!(msg.contains("bash"));
242        assert!(msg.contains("command not found"));
243    }
244
245    #[test]
246    fn test_code_error_session() {
247        let err = CodeError::Session("not found".to_string());
248        assert!(err.to_string().contains("Session error"));
249    }
250
251    #[test]
252    fn test_code_error_session_configuration_keeps_field_identity() {
253        let err = CodeError::SessionConfiguration {
254            field: "session_id",
255            message: "must not be empty".to_string(),
256        };
257        assert!(err.to_string().contains("session_id"));
258        assert!(err.to_string().contains("must not be empty"));
259    }
260
261    #[test]
262    fn test_code_error_session_busy() {
263        let err = CodeError::SessionBusy {
264            session_id: "session-1".to_string(),
265        };
266        assert!(err.to_string().contains("session-1"));
267        assert!(err.to_string().contains("active operation"));
268    }
269
270    #[test]
271    fn test_code_error_security() {
272        let err = CodeError::Security("taint detected".to_string());
273        assert!(err.to_string().contains("Security error"));
274    }
275
276    #[test]
277    fn test_code_error_context() {
278        let err = CodeError::Context("provider failed".to_string());
279        assert!(err.to_string().contains("Context error"));
280    }
281
282    #[test]
283    fn test_code_error_mcp() {
284        let err = CodeError::Mcp("connection refused".to_string());
285        assert!(err.to_string().contains("MCP error"));
286    }
287
288    #[test]
289    fn test_code_error_queue() {
290        let err = CodeError::Queue("lane full".to_string());
291        assert!(err.to_string().contains("Queue error"));
292    }
293
294    #[test]
295    fn test_code_error_from_io() {
296        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
297        let err: CodeError = io_err.into();
298        assert!(matches!(err, CodeError::Io(_)));
299        assert!(err.to_string().contains("file missing"));
300    }
301
302    #[test]
303    fn test_code_error_from_serde_json() {
304        let json_err = serde_json::from_str::<serde_json::Value>("invalid").unwrap_err();
305        let err: CodeError = json_err.into();
306        assert!(matches!(err, CodeError::Serialization(_)));
307    }
308
309    #[test]
310    fn test_code_error_from_anyhow() {
311        let anyhow_err = anyhow::anyhow!("something went wrong");
312        let err: CodeError = anyhow_err.into();
313        assert!(matches!(err, CodeError::Internal(_)));
314        assert!(err.to_string().contains("something went wrong"));
315    }
316
317    #[test]
318    fn stable_error_codes_cover_control_flow_variants() {
319        assert_eq!(
320            CodeError::SessionBusy {
321                session_id: "session-1".to_string(),
322            }
323            .code(),
324            "SESSION_BUSY"
325        );
326        assert_eq!(
327            CodeError::SessionClosed {
328                session_id: "session-1".to_string(),
329            }
330            .code(),
331            "SESSION_CLOSED"
332        );
333        assert_eq!(
334            CodeError::RunIdentityConflict {
335                run_id: "run-1".to_string(),
336            }
337            .code(),
338            "RUN_IDENTITY_CONFLICT"
339        );
340        assert_eq!(
341            CodeError::BudgetExhausted {
342                resource: "tokens".to_string(),
343                reason: "limit".to_string(),
344            }
345            .code(),
346            "BUDGET_EXHAUSTED"
347        );
348        assert_eq!(
349            CodeError::TaskAdmissionCancelled {
350                session_id: "session-1".to_string(),
351            }
352            .code(),
353            "TASK_ADMISSION_CANCELLED"
354        );
355        assert_eq!(
356            CodeError::TaskSchedulerClosed.code(),
357            "TASK_SCHEDULER_CLOSED"
358        );
359    }
360
361    #[test]
362    fn test_code_error_question_mark_from_anyhow() {
363        fn inner() -> anyhow::Result<()> {
364            anyhow::bail!("inner error")
365        }
366
367        fn outer() -> Result<()> {
368            inner()?; // anyhow::Error -> CodeError::Internal via #[from]
369            Ok(())
370        }
371
372        let result = outer();
373        assert!(result.is_err());
374        let err = result.unwrap_err();
375        assert!(matches!(err, CodeError::Internal(_)));
376    }
377
378    #[test]
379    fn test_read_or_recover_normal() {
380        let lock = std::sync::RwLock::new(42);
381        let guard = read_or_recover(&lock);
382        assert_eq!(*guard, 42);
383    }
384
385    #[test]
386    fn test_write_or_recover_normal() {
387        let lock = std::sync::RwLock::new(42);
388        let mut guard = write_or_recover(&lock);
389        *guard = 99;
390        drop(guard);
391        assert_eq!(*read_or_recover(&lock), 99);
392    }
393
394    #[test]
395    fn test_read_or_recover_poisoned() {
396        let lock = std::sync::RwLock::new(42);
397        // Poison the lock by panicking while holding a write guard
398        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
399            let _guard = lock.write().unwrap();
400            panic!("intentional poison");
401        }));
402        // Should recover without panicking
403        let guard = read_or_recover(&lock);
404        assert_eq!(*guard, 42);
405    }
406
407    #[test]
408    fn test_write_or_recover_poisoned() {
409        let lock = std::sync::RwLock::new(42);
410        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
411            let _guard = lock.write().unwrap();
412            panic!("intentional poison");
413        }));
414        let mut guard = write_or_recover(&lock);
415        *guard = 100;
416        assert_eq!(*guard, 100);
417    }
418}