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 typed steer/interrupt request could not be accepted by the active
119    /// run-control inbox.
120    #[error("Run control error: {0}")]
121    RunControl(#[from] crate::run_control::RunControlError),
122
123    /// A host-supplied [`BudgetGuard`](crate::budget::BudgetGuard) denied
124    /// the operation. The session is not closed — callers can re-try
125    /// after the host has re-allocated budget.
126    #[error("Budget exhausted on '{resource}': {reason}")]
127    BudgetExhausted { resource: String, reason: String },
128
129    /// Security subsystem error
130    #[error("Security error: {0}")]
131    Security(String),
132
133    /// Context provider or context store error
134    #[error("Context error: {0}")]
135    Context(String),
136
137    /// MCP (Model Context Protocol) error
138    #[error("MCP error: {0}")]
139    Mcp(String),
140
141    /// Queue or lane error
142    #[error("Queue error: {0}")]
143    Queue(String),
144
145    /// Atomic Session capability publication or Run admission failure.
146    #[error("Capability runtime error: {0}")]
147    Capability(#[from] crate::capability::CapabilityRuntimeError),
148
149    /// A3S Flow definition, replay, store, or runtime failure.
150    #[error("Flow error: {0}")]
151    Flow(#[from] a3s_flow::FlowError),
152
153    /// I/O error
154    #[error("IO error: {0}")]
155    Io(#[from] std::io::Error),
156
157    /// JSON serialization/deserialization error
158    #[error("Serialization error: {0}")]
159    Serialization(#[from] serde_json::Error),
160
161    /// Catch-all for errors not yet migrated to a specific variant.
162    ///
163    /// The `#[from] anyhow::Error` conversion enables gradual migration:
164    /// any function returning `anyhow::Result` can be called with `?` from
165    /// a function returning `crate::error::Result` without changes.
166    #[error("{0:#}")]
167    Internal(#[from] anyhow::Error),
168}
169
170impl CodeError {
171    /// Stable machine-readable code for SDK and service boundaries.
172    pub const fn code(&self) -> &'static str {
173        match self {
174            Self::Config(_) => "CONFIG_ERROR",
175            Self::Llm(_) => "LLM_ERROR",
176            Self::Tool { .. } => "TOOL_ERROR",
177            Self::Session(_) => "SESSION_ERROR",
178            Self::SessionConfiguration { .. } => "SESSION_CONFIGURATION_ERROR",
179            Self::SessionInitialization { .. } => "SESSION_INITIALIZATION_ERROR",
180            Self::AsyncSessionBuildRequired { .. } => "ASYNC_SESSION_BUILD_REQUIRED",
181            Self::SessionClosed { .. } => "SESSION_CLOSED",
182            Self::SessionBusy { .. } => "SESSION_BUSY",
183            Self::TaskAdmissionCancelled { .. } => "TASK_ADMISSION_CANCELLED",
184            Self::TaskSchedulerClosed => "TASK_SCHEDULER_CLOSED",
185            Self::RunIdentityConflict { .. } => "RUN_IDENTITY_CONFLICT",
186            Self::RunControl(error) => error.code(),
187            Self::BudgetExhausted { .. } => "BUDGET_EXHAUSTED",
188            Self::Security(_) => "SECURITY_ERROR",
189            Self::Context(_) => "CONTEXT_ERROR",
190            Self::Mcp(_) => "MCP_ERROR",
191            Self::Queue(_) => "QUEUE_ERROR",
192            Self::Capability(_) => "CAPABILITY_RUNTIME_ERROR",
193            Self::Flow(_) => "FLOW_ERROR",
194            Self::Io(_) => "IO_ERROR",
195            Self::Serialization(_) => "SERIALIZATION_ERROR",
196            Self::Internal(_) => "INTERNAL_ERROR",
197        }
198    }
199}
200
201// ============================================================================
202// Lock Poisoning Helpers (Phase 3b)
203// ============================================================================
204
205/// Acquire a read guard, recovering from poison if the lock was poisoned.
206///
207/// Non-security code should never panic on a poisoned lock. The data may
208/// be in an inconsistent state, but crashing the entire process is worse
209/// than serving stale data in a coding agent context.
210pub(crate) fn read_or_recover<T>(lock: &std::sync::RwLock<T>) -> std::sync::RwLockReadGuard<'_, T> {
211    lock.read().unwrap_or_else(|p| p.into_inner())
212}
213
214/// Acquire a write guard, recovering from poison if the lock was poisoned.
215///
216/// See [`read_or_recover`] for rationale.
217pub(crate) fn write_or_recover<T>(
218    lock: &std::sync::RwLock<T>,
219) -> std::sync::RwLockWriteGuard<'_, T> {
220    lock.write().unwrap_or_else(|p| p.into_inner())
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    #[test]
228    fn test_code_error_config() {
229        let err = CodeError::Config("missing API key".to_string());
230        assert!(err.to_string().contains("Config error"));
231        assert!(err.to_string().contains("missing API key"));
232    }
233
234    #[test]
235    fn test_code_error_llm() {
236        let err = CodeError::Llm("rate limited".to_string());
237        assert!(err.to_string().contains("LLM error"));
238    }
239
240    #[test]
241    fn test_code_error_tool() {
242        let err = CodeError::Tool {
243            tool: "bash".to_string(),
244            message: "command not found".to_string(),
245        };
246        let msg = err.to_string();
247        assert!(msg.contains("bash"));
248        assert!(msg.contains("command not found"));
249    }
250
251    #[test]
252    fn test_code_error_session() {
253        let err = CodeError::Session("not found".to_string());
254        assert!(err.to_string().contains("Session error"));
255    }
256
257    #[test]
258    fn test_code_error_session_configuration_keeps_field_identity() {
259        let err = CodeError::SessionConfiguration {
260            field: "session_id",
261            message: "must not be empty".to_string(),
262        };
263        assert!(err.to_string().contains("session_id"));
264        assert!(err.to_string().contains("must not be empty"));
265    }
266
267    #[test]
268    fn test_code_error_session_busy() {
269        let err = CodeError::SessionBusy {
270            session_id: "session-1".to_string(),
271        };
272        assert!(err.to_string().contains("session-1"));
273        assert!(err.to_string().contains("active operation"));
274    }
275
276    #[test]
277    fn test_code_error_security() {
278        let err = CodeError::Security("taint detected".to_string());
279        assert!(err.to_string().contains("Security error"));
280    }
281
282    #[test]
283    fn test_code_error_context() {
284        let err = CodeError::Context("provider failed".to_string());
285        assert!(err.to_string().contains("Context error"));
286    }
287
288    #[test]
289    fn test_code_error_mcp() {
290        let err = CodeError::Mcp("connection refused".to_string());
291        assert!(err.to_string().contains("MCP error"));
292    }
293
294    #[test]
295    fn test_code_error_queue() {
296        let err = CodeError::Queue("lane full".to_string());
297        assert!(err.to_string().contains("Queue error"));
298    }
299
300    #[test]
301    fn test_code_error_from_io() {
302        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
303        let err: CodeError = io_err.into();
304        assert!(matches!(err, CodeError::Io(_)));
305        assert!(err.to_string().contains("file missing"));
306    }
307
308    #[test]
309    fn test_code_error_from_serde_json() {
310        let json_err = serde_json::from_str::<serde_json::Value>("invalid").unwrap_err();
311        let err: CodeError = json_err.into();
312        assert!(matches!(err, CodeError::Serialization(_)));
313    }
314
315    #[test]
316    fn test_code_error_from_anyhow() {
317        let anyhow_err = anyhow::anyhow!("something went wrong");
318        let err: CodeError = anyhow_err.into();
319        assert!(matches!(err, CodeError::Internal(_)));
320        assert!(err.to_string().contains("something went wrong"));
321    }
322
323    #[test]
324    fn stable_error_codes_cover_control_flow_variants() {
325        assert_eq!(
326            CodeError::SessionBusy {
327                session_id: "session-1".to_string(),
328            }
329            .code(),
330            "SESSION_BUSY"
331        );
332        assert_eq!(
333            CodeError::SessionClosed {
334                session_id: "session-1".to_string(),
335            }
336            .code(),
337            "SESSION_CLOSED"
338        );
339        assert_eq!(
340            CodeError::RunIdentityConflict {
341                run_id: "run-1".to_string(),
342            }
343            .code(),
344            "RUN_IDENTITY_CONFLICT"
345        );
346        assert_eq!(
347            CodeError::BudgetExhausted {
348                resource: "tokens".to_string(),
349                reason: "limit".to_string(),
350            }
351            .code(),
352            "BUDGET_EXHAUSTED"
353        );
354        assert_eq!(
355            CodeError::TaskAdmissionCancelled {
356                session_id: "session-1".to_string(),
357            }
358            .code(),
359            "TASK_ADMISSION_CANCELLED"
360        );
361        assert_eq!(
362            CodeError::TaskSchedulerClosed.code(),
363            "TASK_SCHEDULER_CLOSED"
364        );
365    }
366
367    #[test]
368    fn test_code_error_question_mark_from_anyhow() {
369        fn inner() -> anyhow::Result<()> {
370            anyhow::bail!("inner error")
371        }
372
373        fn outer() -> Result<()> {
374            inner()?; // anyhow::Error -> CodeError::Internal via #[from]
375            Ok(())
376        }
377
378        let result = outer();
379        assert!(result.is_err());
380        let err = result.unwrap_err();
381        assert!(matches!(err, CodeError::Internal(_)));
382    }
383
384    #[test]
385    fn test_read_or_recover_normal() {
386        let lock = std::sync::RwLock::new(42);
387        let guard = read_or_recover(&lock);
388        assert_eq!(*guard, 42);
389    }
390
391    #[test]
392    fn test_write_or_recover_normal() {
393        let lock = std::sync::RwLock::new(42);
394        let mut guard = write_or_recover(&lock);
395        *guard = 99;
396        drop(guard);
397        assert_eq!(*read_or_recover(&lock), 99);
398    }
399
400    #[test]
401    fn test_read_or_recover_poisoned() {
402        let lock = std::sync::RwLock::new(42);
403        // Poison the lock by panicking while holding a write guard
404        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
405            let _guard = lock.write().unwrap();
406            panic!("intentional poison");
407        }));
408        // Should recover without panicking
409        let guard = read_or_recover(&lock);
410        assert_eq!(*guard, 42);
411    }
412
413    #[test]
414    fn test_write_or_recover_poisoned() {
415        let lock = std::sync::RwLock::new(42);
416        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
417            let _guard = lock.write().unwrap();
418            panic!("intentional poison");
419        }));
420        let mut guard = write_or_recover(&lock);
421        *guard = 100;
422        assert_eq!(*guard, 100);
423    }
424}