Skip to main content

adk_core/
error.rs

1// Unified structured error envelope for all ADK-Rust operations.
2
3use serde::{Deserialize, Serialize};
4use serde_json::{Value, json};
5use std::collections::HashMap;
6use std::fmt;
7use std::time::Duration;
8
9/// The subsystem that produced the error — the origin, not the boundary it surfaces through.
10///
11/// Choose the variant matching where the failure actually happened, not which trait
12/// boundary returned it. For example:
13/// - A code-execution timeout inside `python_code_tool.rs` → [`Code`](Self::Code)
14/// - An auth denial inside middleware → [`Auth`](Self::Auth)
15/// - A missing API key detected in model config → [`Model`](Self::Model) with `InvalidInput`
16/// - A database write failure in session persistence → [`Session`](Self::Session)
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
18#[serde(rename_all = "snake_case")]
19pub enum ErrorComponent {
20    /// Error originated in agent logic.
21    Agent,
22    /// Error originated in model/LLM interaction.
23    Model,
24    /// Error originated in tool execution.
25    Tool,
26    /// Error originated in session management.
27    Session,
28    /// Error originated in artifact storage.
29    Artifact,
30    /// Error originated in memory/RAG operations.
31    Memory,
32    /// Error originated in graph workflow execution.
33    Graph,
34    /// Error originated in realtime audio/video streaming.
35    Realtime,
36    /// Error originated in code execution.
37    Code,
38    /// Error originated in the HTTP server.
39    Server,
40    /// Error originated in authentication/authorization.
41    Auth,
42    /// Error originated in guardrail validation.
43    Guardrail,
44    /// Error originated in evaluation framework.
45    Eval,
46    /// Error originated in deployment operations.
47    Deploy,
48}
49
50impl fmt::Display for ErrorComponent {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        let s = match self {
53            Self::Agent => "agent",
54            Self::Model => "model",
55            Self::Tool => "tool",
56            Self::Session => "session",
57            Self::Artifact => "artifact",
58            Self::Memory => "memory",
59            Self::Graph => "graph",
60            Self::Realtime => "realtime",
61            Self::Code => "code",
62            Self::Server => "server",
63            Self::Auth => "auth",
64            Self::Guardrail => "guardrail",
65            Self::Eval => "eval",
66            Self::Deploy => "deploy",
67        };
68        f.write_str(s)
69    }
70}
71
72/// The kind of failure independent of subsystem.
73///
74/// Choose the variant that best describes what went wrong:
75/// - [`InvalidInput`](Self::InvalidInput) — caller provided bad data (config, request body, parameters)
76/// - [`Unauthorized`](Self::Unauthorized) — missing or invalid credentials
77/// - [`Forbidden`](Self::Forbidden) — valid credentials but insufficient permissions
78/// - [`NotFound`](Self::NotFound) — requested resource does not exist
79/// - [`RateLimited`](Self::RateLimited) — upstream rate limit hit (retryable by default)
80/// - [`Timeout`](Self::Timeout) — operation exceeded time limit (retryable by default)
81/// - [`Unavailable`](Self::Unavailable) — upstream service temporarily down (retryable by default)
82/// - [`Cancelled`](Self::Cancelled) — operation was cancelled by caller or system
83/// - [`Internal`](Self::Internal) — unexpected internal error (bugs, invariant violations)
84/// - [`Unsupported`](Self::Unsupported) — requested feature or operation is not supported
85/// - [`ResourceExhausted`](Self::ResourceExhausted) — a configured budget (model calls, tokens,
86///   cost, wall time, tool calls) or a provider account's quota, credit balance or spend limit
87///   is used up; not retryable within the same run
88/// - [`Conflict`](Self::Conflict) — the write lost a race or used a stale version; reload and
89///   retry, or stop
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92pub enum ErrorCategory {
93    /// Caller provided bad data (config, request body, parameters).
94    InvalidInput,
95    /// Missing or invalid credentials.
96    Unauthorized,
97    /// Valid credentials but insufficient permissions.
98    Forbidden,
99    /// Requested resource does not exist.
100    NotFound,
101    /// Upstream rate limit hit (retryable by default).
102    RateLimited,
103    /// Operation exceeded time limit (retryable by default).
104    Timeout,
105    /// Upstream service temporarily down (retryable by default).
106    Unavailable,
107    /// Operation was cancelled by caller or system.
108    Cancelled,
109    /// Unexpected internal error (bugs, invariant violations).
110    Internal,
111    /// Requested feature or operation is not supported.
112    Unsupported,
113    /// A configured resource budget, or a provider account's quota, credit balance or
114    /// spend limit, is used up.
115    ///
116    /// Not retryable within the same run: retrying spends against the same
117    /// exhausted budget, or fails until the account has credit again. See
118    /// [`RunBudget`](crate::RunBudget).
119    ResourceExhausted,
120    /// The write lost a race or used a stale version; reload and retry, or stop.
121    ///
122    /// Not retryable as is: repeating the same write with the same stale version or
123    /// epoch fails again. Maps to HTTP 409.
124    Conflict,
125}
126
127impl ErrorCategory {
128    /// Whether the category describes the call rather than what happened upstream.
129    ///
130    /// `InvalidInput`, `Forbidden`, `NotFound`, `Unsupported`, `Conflict` and
131    /// `ResourceExhausted` say what the call asked for and why it was not done, so their
132    /// messages are the guidance the caller needs. The others report an upstream or
133    /// internal failure, whose message can quote credentials, hosts or response bodies.
134    ///
135    /// # Example
136    ///
137    /// ```
138    /// use adk_core::ErrorCategory;
139    ///
140    /// assert!(ErrorCategory::Forbidden.is_rejection());
141    /// assert!(!ErrorCategory::Unavailable.is_rejection());
142    /// ```
143    pub fn is_rejection(self) -> bool {
144        matches!(
145            self,
146            Self::InvalidInput
147                | Self::Forbidden
148                | Self::NotFound
149                | Self::Unsupported
150                | Self::Conflict
151                | Self::ResourceExhausted
152        )
153    }
154}
155
156impl fmt::Display for ErrorCategory {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        let s = match self {
159            Self::InvalidInput => "invalid_input",
160            Self::Unauthorized => "unauthorized",
161            Self::Forbidden => "forbidden",
162            Self::NotFound => "not_found",
163            Self::RateLimited => "rate_limited",
164            Self::Timeout => "timeout",
165            Self::Unavailable => "unavailable",
166            Self::Cancelled => "cancelled",
167            Self::Internal => "internal",
168            Self::Unsupported => "unsupported",
169            Self::ResourceExhausted => "resource_exhausted",
170            Self::Conflict => "conflict",
171        };
172        f.write_str(s)
173    }
174}
175
176/// Structured retry guidance attached to every [`AdkError`].
177#[derive(Debug, Clone, Default, Serialize, Deserialize)]
178pub struct RetryHint {
179    /// Whether the operation should be retried.
180    pub should_retry: bool,
181    /// Suggested delay before retrying, in milliseconds.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub retry_after_ms: Option<u64>,
184    /// Maximum number of retry attempts suggested.
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub max_attempts: Option<u32>,
187}
188
189impl RetryHint {
190    /// Derive a default retry hint from the error category.
191    pub fn for_category(category: ErrorCategory) -> Self {
192        match category {
193            ErrorCategory::RateLimited | ErrorCategory::Unavailable | ErrorCategory::Timeout => {
194                Self { should_retry: true, ..Default::default() }
195            }
196            _ => Self::default(),
197        }
198    }
199
200    /// Convert `retry_after_ms` to a [`Duration`].
201    pub fn retry_after(&self) -> Option<Duration> {
202        self.retry_after_ms.map(Duration::from_millis)
203    }
204
205    /// Set the retry-after delay from a [`Duration`].
206    pub fn with_retry_after(mut self, duration: Duration) -> Self {
207        self.retry_after_ms = Some(duration.as_millis() as u64);
208        self
209    }
210}
211
212/// Optional structured metadata carried by an [`AdkError`].
213#[derive(Debug, Clone, Default, Serialize, Deserialize)]
214pub struct ErrorDetails {
215    /// HTTP status code from the upstream service, if applicable.
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub upstream_status_code: Option<u16>,
218    /// Request ID from the upstream service for correlation.
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub request_id: Option<String>,
221    /// Name of the provider that produced the error (e.g., "openai", "gemini").
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub provider: Option<String>,
224    /// Additional key-value metadata for debugging.
225    ///
226    /// Model providers in `adk-model` store the provider's own error code, such as
227    /// `RATE_LIMIT_EXCEEDED` or `context_length_exceeded`, as a string under
228    /// `"provider_error_code"`.
229    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
230    pub metadata: HashMap<String, Value>,
231}
232
233/// Unified structured error type for all ADK-Rust operations.
234///
235/// # Migration from enum syntax
236///
237/// Before (0.4.x enum):
238/// ```rust,ignore
239/// // Construction
240/// Err(AdkError::Model("rate limited".into()))
241/// // Matching
242/// matches!(err, AdkError::Model(_))
243/// ```
244///
245/// After (0.5.x struct):
246/// ```rust
247/// use adk_core::{AdkError, ErrorComponent, ErrorCategory};
248///
249/// // Structured construction
250/// let err = AdkError::new(
251///     ErrorComponent::Model,
252///     ErrorCategory::RateLimited,
253///     "model.openai.rate_limited",
254///     "rate limited",
255/// );
256/// assert!(err.is_retryable()); // RateLimited → should_retry = true
257///
258/// // Backward-compat construction (for migration)
259/// let err = AdkError::model("rate limited");
260/// assert!(err.is_model());
261/// ```
262pub struct AdkError {
263    /// The subsystem that produced the error.
264    pub component: ErrorComponent,
265    /// The kind of failure.
266    pub category: ErrorCategory,
267    /// Machine-readable error code (e.g., "model.openai.rate_limited").
268    pub code: &'static str,
269    /// Human-readable error message.
270    pub message: String,
271    /// Retry guidance for this error.
272    pub retry: RetryHint,
273    /// Additional structured metadata.
274    pub details: Box<ErrorDetails>,
275    source: Option<Box<dyn std::error::Error + Send + Sync>>,
276}
277
278impl fmt::Debug for AdkError {
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        let mut d = f.debug_struct("AdkError");
281        d.field("component", &self.component)
282            .field("category", &self.category)
283            .field("code", &self.code)
284            .field("message", &self.message)
285            .field("retry", &self.retry)
286            .field("details", &self.details);
287        if let Some(src) = &self.source {
288            d.field("source", &format_args!("{src}"));
289        }
290        d.finish()
291    }
292}
293
294impl fmt::Display for AdkError {
295    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296        write!(f, "{}.{}: {}", self.component, self.category, self.message)
297    }
298}
299
300impl std::error::Error for AdkError {
301    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
302        self.source.as_ref().map(|e| e.as_ref() as &(dyn std::error::Error + 'static))
303    }
304}
305
306const _: () = {
307    fn _assert_send<T: Send>() {}
308    fn _assert_sync<T: Sync>() {}
309    fn _assertions() {
310        _assert_send::<AdkError>();
311        _assert_sync::<AdkError>();
312    }
313};
314
315impl AdkError {
316    /// Creates a new `AdkError` with the given component, category, code, and message.
317    pub fn new(
318        component: ErrorComponent,
319        category: ErrorCategory,
320        code: &'static str,
321        message: impl Into<String>,
322    ) -> Self {
323        Self {
324            component,
325            category,
326            code,
327            message: message.into(),
328            retry: RetryHint::for_category(category),
329            details: Box::new(ErrorDetails::default()),
330            source: None,
331        }
332    }
333
334    /// Attaches a source error for error chaining.
335    pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Self {
336        self.source = Some(Box::new(source));
337        self
338    }
339
340    /// Overrides the default retry hint.
341    pub fn with_retry(mut self, retry: RetryHint) -> Self {
342        self.retry = retry;
343        self
344    }
345
346    /// Replaces the error details.
347    pub fn with_details(mut self, details: ErrorDetails) -> Self {
348        self.details = Box::new(details);
349        self
350    }
351
352    /// Sets the upstream HTTP status code in details.
353    pub fn with_upstream_status(mut self, status_code: u16) -> Self {
354        self.details.upstream_status_code = Some(status_code);
355        self
356    }
357
358    /// Sets the upstream request ID in details.
359    pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
360        self.details.request_id = Some(request_id.into());
361        self
362    }
363
364    /// Sets the provider name in details.
365    pub fn with_provider(mut self, provider: impl Into<String>) -> Self {
366        self.details.provider = Some(provider.into());
367        self
368    }
369}
370
371impl AdkError {
372    /// Creates a `NotFound` error for the given component.
373    pub fn not_found(
374        component: ErrorComponent,
375        code: &'static str,
376        message: impl Into<String>,
377    ) -> Self {
378        Self::new(component, ErrorCategory::NotFound, code, message)
379    }
380
381    /// Creates a `RateLimited` error for the given component.
382    pub fn rate_limited(
383        component: ErrorComponent,
384        code: &'static str,
385        message: impl Into<String>,
386    ) -> Self {
387        Self::new(component, ErrorCategory::RateLimited, code, message)
388    }
389
390    /// Creates an `Unauthorized` error for the given component.
391    pub fn unauthorized(
392        component: ErrorComponent,
393        code: &'static str,
394        message: impl Into<String>,
395    ) -> Self {
396        Self::new(component, ErrorCategory::Unauthorized, code, message)
397    }
398
399    /// Creates an `Internal` error for the given component.
400    pub fn internal(
401        component: ErrorComponent,
402        code: &'static str,
403        message: impl Into<String>,
404    ) -> Self {
405        Self::new(component, ErrorCategory::Internal, code, message)
406    }
407
408    /// Creates a `Timeout` error for the given component.
409    pub fn timeout(
410        component: ErrorComponent,
411        code: &'static str,
412        message: impl Into<String>,
413    ) -> Self {
414        Self::new(component, ErrorCategory::Timeout, code, message)
415    }
416
417    /// Creates an `Unavailable` error for the given component.
418    pub fn unavailable(
419        component: ErrorComponent,
420        code: &'static str,
421        message: impl Into<String>,
422    ) -> Self {
423        Self::new(component, ErrorCategory::Unavailable, code, message)
424    }
425}
426
427impl AdkError {
428    /// Legacy convenience constructor for agent errors.
429    pub fn agent(message: impl Into<String>) -> Self {
430        Self::new(ErrorComponent::Agent, ErrorCategory::Internal, "agent.legacy", message)
431    }
432
433    /// Legacy convenience constructor for model errors.
434    pub fn model(message: impl Into<String>) -> Self {
435        Self::new(ErrorComponent::Model, ErrorCategory::Internal, "model.legacy", message)
436    }
437
438    /// Legacy convenience constructor for tool errors.
439    pub fn tool(message: impl Into<String>) -> Self {
440        Self::new(ErrorComponent::Tool, ErrorCategory::Internal, "tool.legacy", message)
441    }
442
443    /// Legacy convenience constructor for session errors.
444    pub fn session(message: impl Into<String>) -> Self {
445        Self::new(ErrorComponent::Session, ErrorCategory::Internal, "session.legacy", message)
446    }
447
448    /// Legacy convenience constructor for memory errors.
449    pub fn memory(message: impl Into<String>) -> Self {
450        Self::new(ErrorComponent::Memory, ErrorCategory::Internal, "memory.legacy", message)
451    }
452
453    /// Legacy convenience constructor for configuration errors.
454    pub fn config(message: impl Into<String>) -> Self {
455        Self::new(ErrorComponent::Server, ErrorCategory::InvalidInput, "config.legacy", message)
456    }
457
458    /// Legacy convenience constructor for artifact errors.
459    pub fn artifact(message: impl Into<String>) -> Self {
460        Self::new(ErrorComponent::Artifact, ErrorCategory::Internal, "artifact.legacy", message)
461    }
462}
463
464impl AdkError {
465    /// Returns `true` if this error originated in agent logic.
466    pub fn is_agent(&self) -> bool {
467        self.component == ErrorComponent::Agent
468    }
469    /// Returns `true` if this error originated in model interaction.
470    pub fn is_model(&self) -> bool {
471        self.component == ErrorComponent::Model
472    }
473    /// Returns `true` if this error originated in tool execution.
474    pub fn is_tool(&self) -> bool {
475        self.component == ErrorComponent::Tool
476    }
477    /// Returns `true` if this error originated in session management.
478    pub fn is_session(&self) -> bool {
479        self.component == ErrorComponent::Session
480    }
481    /// Returns `true` if this error originated in artifact storage.
482    pub fn is_artifact(&self) -> bool {
483        self.component == ErrorComponent::Artifact
484    }
485    /// Returns `true` if this error originated in memory operations.
486    pub fn is_memory(&self) -> bool {
487        self.component == ErrorComponent::Memory
488    }
489    /// Returns `true` if this is a configuration error (legacy code path).
490    pub fn is_config(&self) -> bool {
491        self.code == "config.legacy"
492    }
493}
494
495impl AdkError {
496    /// Returns `true` if this error should be retried.
497    pub fn is_retryable(&self) -> bool {
498        self.retry.should_retry
499    }
500    /// Returns `true` if this is a not-found error.
501    pub fn is_not_found(&self) -> bool {
502        self.category == ErrorCategory::NotFound
503    }
504    /// Returns `true` if this is an unauthorized error.
505    pub fn is_unauthorized(&self) -> bool {
506        self.category == ErrorCategory::Unauthorized
507    }
508    /// Returns `true` if this is a rate-limited error.
509    pub fn is_rate_limited(&self) -> bool {
510        self.category == ErrorCategory::RateLimited
511    }
512    /// Returns `true` if this is a timeout error.
513    pub fn is_timeout(&self) -> bool {
514        self.category == ErrorCategory::Timeout
515    }
516    /// Returns `true` if the write lost a race or used a stale version.
517    pub fn is_conflict(&self) -> bool {
518        self.category == ErrorCategory::Conflict
519    }
520
521    /// Describes the error by its component, category, and code, without its message.
522    ///
523    /// A message can carry credentials, internal hosts, or upstream response bodies, so this
524    /// form is what an agent shows a model for a failure whose message stays local. The code is
525    /// a compile-time constant, never caller data.
526    ///
527    /// # Example
528    ///
529    /// ```rust
530    /// use adk_core::{AdkError, ErrorCategory, ErrorComponent};
531    ///
532    /// let err = AdkError::new(
533    ///     ErrorComponent::Tool,
534    ///     ErrorCategory::Unavailable,
535    ///     "tool.orders_db.unavailable",
536    ///     "connect postgres://admin:secret@db.internal/prod failed",
537    /// );
538    /// assert_eq!(err.redacted(), "tool.unavailable (tool.orders_db.unavailable)");
539    /// ```
540    pub fn redacted(&self) -> String {
541        format!("{}.{} ({})", self.component, self.category, self.code)
542    }
543
544    /// Describes the error for a log line or span field without its message.
545    ///
546    /// The form is [`redacted`](Self::redacted) followed by the upstream status, provider,
547    /// provider error code, and request ID when they are set. A provider error code or
548    /// request ID is shown only when it is a short identifier, since both come from the
549    /// upstream response.
550    ///
551    /// # Example
552    ///
553    /// ```rust
554    /// use adk_core::{AdkError, ErrorCategory, ErrorComponent};
555    ///
556    /// let err = AdkError::new(
557    ///     ErrorComponent::Model,
558    ///     ErrorCategory::InvalidInput,
559    ///     "model.gemini.bad_request",
560    ///     "Invalid value at 'contents[0]' (acct-7731)",
561    /// )
562    /// .with_upstream_status(400)
563    /// .with_provider("gemini");
564    /// assert_eq!(
565    ///     err.diagnostics().to_string(),
566    ///     "model.invalid_input (model.gemini.bad_request); status 400; provider gemini"
567    /// );
568    /// ```
569    pub fn diagnostics(&self) -> ErrorDiagnostics<'_> {
570        ErrorDiagnostics(self)
571    }
572}
573
574/// An [`AdkError`] described by everything but its message, from [`AdkError::diagnostics`].
575#[derive(Debug, Clone, Copy)]
576pub struct ErrorDiagnostics<'a>(&'a AdkError);
577
578impl fmt::Display for ErrorDiagnostics<'_> {
579    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
580        let error = self.0;
581        write!(f, "{}.{} ({})", error.component, error.category, error.code)?;
582        let details = &error.details;
583        if let Some(status) = details.upstream_status_code {
584            write!(f, "; status {status}")?;
585        }
586        if let Some(provider) = details.provider.as_deref().filter(|value| is_identifier(value)) {
587            write!(f, "; provider {provider}")?;
588        }
589        if let Some(code) = details
590            .metadata
591            .get("provider_error_code")
592            .and_then(Value::as_str)
593            .filter(|value| is_identifier(value))
594        {
595            write!(f, "; provider code {code}")?;
596        }
597        if let Some(request_id) = details.request_id.as_deref().filter(|value| is_identifier(value))
598        {
599            write!(f, "; request id {request_id}")?;
600        }
601        Ok(())
602    }
603}
604
605/// Whether `value` is short and limited to ASCII alphanumerics, `_`, `.`, `-`, and `:`.
606fn is_identifier(value: &str) -> bool {
607    !value.is_empty()
608        && value.len() <= 128
609        && value.bytes().all(|byte| byte.is_ascii_alphanumeric() || b"_.-:".contains(&byte))
610}
611
612/// Longest excerpt of upstream text, such as a provider's HTTP error body, that an error
613/// message quotes.
614pub const UPSTREAM_EXCERPT_BYTES: usize = 512;
615
616/// Returns `text` trimmed and cut to at most [`UPSTREAM_EXCERPT_BYTES`] at a character
617/// boundary.
618///
619/// Provider error bodies can echo the request — prompts, tool arguments, file contents — and
620/// can be arbitrarily long, so an error message quotes at most this much of one.
621///
622/// # Example
623///
624/// ```rust
625/// use adk_core::{UPSTREAM_EXCERPT_BYTES, upstream_excerpt};
626///
627/// let body = "x".repeat(4 * UPSTREAM_EXCERPT_BYTES);
628/// assert_eq!(upstream_excerpt(&body).len(), UPSTREAM_EXCERPT_BYTES);
629/// assert_eq!(upstream_excerpt("  bad request \n"), "bad request");
630/// ```
631pub fn upstream_excerpt(text: &str) -> &str {
632    let text = text.trim();
633    &text[..text.floor_char_boundary(UPSTREAM_EXCERPT_BYTES)]
634}
635
636/// Describes a JSON decoding error by its class and position, without the text it quotes.
637///
638/// A `serde_json` data error quotes the offending value, such as `invalid type: string
639/// "..."`, and a provider response carries generated text and tool arguments, so an error
640/// message about an undecodable response uses this description instead.
641///
642/// # Example
643///
644/// ```rust
645/// use adk_core::json_error_summary;
646///
647/// let error = serde_json::from_str::<u32>(r#""acct-7731""#).unwrap_err();
648/// assert_eq!(json_error_summary(&error), "schema error at line 1 column 11");
649/// ```
650pub fn json_error_summary(error: &serde_json::Error) -> String {
651    let class = match error.classify() {
652        serde_json::error::Category::Io => "io",
653        serde_json::error::Category::Syntax => "syntax",
654        serde_json::error::Category::Data => "schema",
655        serde_json::error::Category::Eof => "truncated input",
656    };
657    match error.line() {
658        0 => format!("{class} error"),
659        line => format!("{class} error at line {line} column {}", error.column()),
660    }
661}
662
663impl AdkError {
664    /// Maps the error category to an appropriate HTTP status code.
665    #[allow(unreachable_patterns)]
666    pub fn http_status_code(&self) -> u16 {
667        match self.category {
668            ErrorCategory::InvalidInput => 400,
669            ErrorCategory::Unauthorized => 401,
670            ErrorCategory::Forbidden => 403,
671            ErrorCategory::NotFound => 404,
672            ErrorCategory::RateLimited => 429,
673            ErrorCategory::Timeout => 408,
674            ErrorCategory::Unavailable => 503,
675            ErrorCategory::Cancelled => 499,
676            ErrorCategory::Internal => 500,
677            ErrorCategory::Unsupported => 501,
678            ErrorCategory::ResourceExhausted => 429,
679            ErrorCategory::Conflict => 409,
680            _ => 500,
681        }
682    }
683}
684
685impl AdkError {
686    /// Serializes the error as a JSON Problem Details object.
687    pub fn to_problem_json(&self) -> Value {
688        json!({
689            "error": {
690                "code": self.code,
691                "message": self.message,
692                "component": self.component,
693                "category": self.category,
694                "requestId": self.details.request_id,
695                "retryAfter": self.retry.retry_after_ms,
696                "upstreamStatusCode": self.details.upstream_status_code,
697            }
698        })
699    }
700}
701
702/// Convenience alias used throughout ADK crates.
703pub type Result<T> = std::result::Result<T, AdkError>;
704
705#[cfg(test)]
706mod tests {
707    use super::*;
708
709    #[test]
710    fn test_new_sets_fields() {
711        let err = AdkError::new(
712            ErrorComponent::Model,
713            ErrorCategory::RateLimited,
714            "model.rate_limited",
715            "too many requests",
716        );
717        assert_eq!(err.component, ErrorComponent::Model);
718        assert_eq!(err.category, ErrorCategory::RateLimited);
719        assert_eq!(err.code, "model.rate_limited");
720        assert_eq!(err.message, "too many requests");
721        assert!(err.retry.should_retry);
722    }
723
724    #[test]
725    fn test_display_format() {
726        let err = AdkError::new(
727            ErrorComponent::Session,
728            ErrorCategory::NotFound,
729            "session.not_found",
730            "session xyz not found",
731        );
732        assert_eq!(err.to_string(), "session.not_found: session xyz not found");
733    }
734
735    #[test]
736    fn diagnostics_name_every_detail_but_the_message() {
737        let mut err = AdkError::new(
738            ErrorComponent::Model,
739            ErrorCategory::InvalidInput,
740            "model.openai.bad_request",
741            "Invalid value: 'acct-7731-secret'",
742        )
743        .with_upstream_status(400)
744        .with_provider("openai")
745        .with_request_id("req_123");
746        err.details.metadata.insert("provider_error_code".into(), json!("invalid_value"));
747
748        assert_eq!(
749            err.diagnostics().to_string(),
750            "model.invalid_input (model.openai.bad_request); status 400; provider openai; \
751             provider code invalid_value; request id req_123"
752        );
753    }
754
755    #[test]
756    fn diagnostics_omit_upstream_values_that_are_not_identifiers() {
757        let mut err =
758            AdkError::new(ErrorComponent::Model, ErrorCategory::Internal, "model.x", "boom")
759                .with_request_id("req 1 acct-7731-secret")
760                .with_provider("open\u{1b}]ai");
761        err.details.metadata.insert("provider_error_code".into(), json!("a b"));
762
763        assert_eq!(err.diagnostics().to_string(), "model.internal (model.x)");
764    }
765
766    #[test]
767    fn upstream_excerpt_trims_and_cuts_at_a_character_boundary() {
768        let long = format!("  {}🙂tail", "x".repeat(UPSTREAM_EXCERPT_BYTES - 2));
769        assert_eq!(upstream_excerpt(&long), "x".repeat(UPSTREAM_EXCERPT_BYTES - 2));
770        assert_eq!(upstream_excerpt(" short \n"), "short");
771        assert_eq!(upstream_excerpt(""), "");
772    }
773
774    #[test]
775    fn json_error_summary_never_quotes_the_input() {
776        let data = serde_json::from_str::<u32>(r#""acct-7731-secret""#).unwrap_err();
777        assert_eq!(json_error_summary(&data), "schema error at line 1 column 18");
778        let syntax = serde_json::from_str::<Value>("{acct-7731-secret").unwrap_err();
779        assert_eq!(json_error_summary(&syntax), "syntax error at line 1 column 2");
780        let eof = serde_json::from_str::<Value>(r#"{"a": "acct"#).unwrap_err();
781        assert_eq!(json_error_summary(&eof), "truncated input error at line 1 column 11");
782        let from_value = serde_json::from_value::<u32>(json!("acct-7731-secret")).unwrap_err();
783        assert_eq!(json_error_summary(&from_value), "schema error");
784    }
785
786    #[test]
787    fn test_convenience_not_found() {
788        let err = AdkError::not_found(ErrorComponent::Session, "session.not_found", "gone");
789        assert_eq!(err.category, ErrorCategory::NotFound);
790        assert!(!err.is_retryable());
791    }
792
793    #[test]
794    fn test_convenience_rate_limited() {
795        let err = AdkError::rate_limited(ErrorComponent::Model, "model.rate_limited", "slow down");
796        assert!(err.is_retryable());
797        assert!(err.is_rate_limited());
798    }
799
800    #[test]
801    fn test_convenience_unauthorized() {
802        let err = AdkError::unauthorized(ErrorComponent::Auth, "auth.unauthorized", "bad token");
803        assert!(err.is_unauthorized());
804        assert!(!err.is_retryable());
805    }
806
807    #[test]
808    fn test_convenience_internal() {
809        let err = AdkError::internal(ErrorComponent::Agent, "agent.internal", "oops");
810        assert_eq!(err.category, ErrorCategory::Internal);
811    }
812
813    #[test]
814    fn test_convenience_timeout() {
815        let err = AdkError::timeout(ErrorComponent::Model, "model.timeout", "timed out");
816        assert!(err.is_timeout());
817        assert!(err.is_retryable());
818    }
819
820    #[test]
821    fn test_convenience_unavailable() {
822        let err = AdkError::unavailable(ErrorComponent::Model, "model.unavailable", "503");
823        assert!(err.is_retryable());
824    }
825
826    #[test]
827    fn test_backward_compat_agent() {
828        let err = AdkError::agent("test error");
829        assert!(err.is_agent());
830        assert_eq!(err.code, "agent.legacy");
831        assert_eq!(err.category, ErrorCategory::Internal);
832        assert_eq!(err.to_string(), "agent.internal: test error");
833    }
834
835    #[test]
836    fn test_backward_compat_model() {
837        let err = AdkError::model("model fail");
838        assert!(err.is_model());
839        assert_eq!(err.code, "model.legacy");
840    }
841
842    #[test]
843    fn test_backward_compat_tool() {
844        let err = AdkError::tool("tool fail");
845        assert!(err.is_tool());
846        assert_eq!(err.code, "tool.legacy");
847    }
848
849    #[test]
850    fn test_backward_compat_session() {
851        let err = AdkError::session("session fail");
852        assert!(err.is_session());
853        assert_eq!(err.code, "session.legacy");
854    }
855
856    #[test]
857    fn test_backward_compat_memory() {
858        let err = AdkError::memory("memory fail");
859        assert!(err.is_memory());
860        assert_eq!(err.code, "memory.legacy");
861    }
862
863    #[test]
864    fn test_backward_compat_artifact() {
865        let err = AdkError::artifact("artifact fail");
866        assert!(err.is_artifact());
867        assert_eq!(err.code, "artifact.legacy");
868    }
869
870    #[test]
871    fn test_backward_compat_config() {
872        let err = AdkError::config("bad config");
873        assert!(err.is_config());
874        assert_eq!(err.code, "config.legacy");
875        assert_eq!(err.component, ErrorComponent::Server);
876        assert_eq!(err.category, ErrorCategory::InvalidInput);
877    }
878
879    #[test]
880    fn test_backward_compat_codes_end_with_legacy() {
881        let errors = [
882            AdkError::agent("a"),
883            AdkError::model("m"),
884            AdkError::tool("t"),
885            AdkError::session("s"),
886            AdkError::memory("mem"),
887            AdkError::config("c"),
888            AdkError::artifact("art"),
889        ];
890        for err in &errors {
891            assert!(err.code.ends_with(".legacy"), "code '{}' should end with .legacy", err.code);
892        }
893    }
894
895    #[test]
896    fn test_is_config_false_for_non_config() {
897        assert!(!AdkError::agent("not config").is_config());
898    }
899
900    #[test]
901    fn test_retryable_categories_default_true() {
902        for cat in [ErrorCategory::RateLimited, ErrorCategory::Unavailable, ErrorCategory::Timeout]
903        {
904            let err = AdkError::new(ErrorComponent::Model, cat, "test", "msg");
905            assert!(err.is_retryable(), "expected is_retryable() == true for {cat}");
906        }
907    }
908
909    #[test]
910    fn test_retryable_override_to_false() {
911        let err =
912            AdkError::new(ErrorComponent::Model, ErrorCategory::RateLimited, "m.rl", "overridden")
913                .with_retry(RetryHint { should_retry: false, ..Default::default() });
914        assert!(!err.is_retryable());
915    }
916
917    #[test]
918    fn test_non_retryable_categories_default_false() {
919        for cat in [
920            ErrorCategory::InvalidInput,
921            ErrorCategory::Unauthorized,
922            ErrorCategory::Forbidden,
923            ErrorCategory::NotFound,
924            ErrorCategory::Cancelled,
925            ErrorCategory::Internal,
926            ErrorCategory::Unsupported,
927            ErrorCategory::ResourceExhausted,
928            ErrorCategory::Conflict,
929        ] {
930            let err = AdkError::new(ErrorComponent::Model, cat, "test", "msg");
931            assert!(!err.is_retryable(), "expected is_retryable() == false for {cat}");
932        }
933    }
934
935    #[test]
936    fn test_http_status_code_mapping() {
937        let cases = [
938            (ErrorCategory::InvalidInput, 400),
939            (ErrorCategory::Unauthorized, 401),
940            (ErrorCategory::Forbidden, 403),
941            (ErrorCategory::NotFound, 404),
942            (ErrorCategory::RateLimited, 429),
943            (ErrorCategory::Timeout, 408),
944            (ErrorCategory::Unavailable, 503),
945            (ErrorCategory::Cancelled, 499),
946            (ErrorCategory::Internal, 500),
947            (ErrorCategory::Unsupported, 501),
948            (ErrorCategory::ResourceExhausted, 429),
949            (ErrorCategory::Conflict, 409),
950        ];
951        for (cat, expected) in &cases {
952            let err = AdkError::new(ErrorComponent::Server, *cat, "test", "msg");
953            assert_eq!(err.http_status_code(), *expected, "wrong status for {cat}");
954        }
955    }
956
957    #[test]
958    fn test_source_returns_some_when_set() {
959        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
960        let err = AdkError::new(ErrorComponent::Session, ErrorCategory::NotFound, "s.f", "missing")
961            .with_source(io_err);
962        assert!(std::error::Error::source(&err).is_some());
963    }
964
965    #[test]
966    fn test_source_returns_none_when_not_set() {
967        assert!(std::error::Error::source(&AdkError::agent("no source")).is_none());
968    }
969
970    #[test]
971    fn test_retry_hint_for_category() {
972        assert!(RetryHint::for_category(ErrorCategory::RateLimited).should_retry);
973        assert!(RetryHint::for_category(ErrorCategory::Unavailable).should_retry);
974        assert!(RetryHint::for_category(ErrorCategory::Timeout).should_retry);
975        assert!(!RetryHint::for_category(ErrorCategory::Internal).should_retry);
976        assert!(!RetryHint::for_category(ErrorCategory::NotFound).should_retry);
977    }
978
979    #[test]
980    fn test_retry_hint_with_retry_after() {
981        let hint = RetryHint::default().with_retry_after(Duration::from_secs(5));
982        assert_eq!(hint.retry_after_ms, Some(5000));
983        assert_eq!(hint.retry_after(), Some(Duration::from_secs(5)));
984    }
985
986    #[test]
987    fn test_to_problem_json() {
988        let err = AdkError::new(
989            ErrorComponent::Model,
990            ErrorCategory::RateLimited,
991            "model.rate_limited",
992            "slow down",
993        )
994        .with_request_id("req-123")
995        .with_upstream_status(429);
996        let j = err.to_problem_json();
997        let o = &j["error"];
998        assert_eq!(o["code"], "model.rate_limited");
999        assert_eq!(o["message"], "slow down");
1000        assert_eq!(o["component"], "model");
1001        assert_eq!(o["category"], "rate_limited");
1002        assert_eq!(o["requestId"], "req-123");
1003        assert_eq!(o["upstreamStatusCode"], 429);
1004    }
1005
1006    #[test]
1007    fn test_conflict_category() {
1008        let err = AdkError::new(
1009            ErrorComponent::Agent,
1010            ErrorCategory::Conflict,
1011            "run_store.stale_epoch",
1012            "stale",
1013        );
1014        assert!(err.is_conflict());
1015        assert!(!err.is_retryable());
1016        assert_eq!(err.http_status_code(), 409);
1017        assert_eq!(ErrorCategory::Conflict.to_string(), "conflict");
1018        assert_eq!(err.to_problem_json()["error"]["category"], "conflict");
1019    }
1020
1021    #[test]
1022    fn test_to_problem_json_null_optionals() {
1023        let j = AdkError::agent("simple").to_problem_json();
1024        let o = &j["error"];
1025        assert!(o["requestId"].is_null());
1026        assert!(o["retryAfter"].is_null());
1027        assert!(o["upstreamStatusCode"].is_null());
1028    }
1029
1030    #[test]
1031    fn test_builder_chaining() {
1032        let err = AdkError::new(ErrorComponent::Model, ErrorCategory::Unavailable, "m.u", "down")
1033            .with_provider("openai")
1034            .with_request_id("req-456")
1035            .with_upstream_status(503)
1036            .with_retry(RetryHint {
1037                should_retry: true,
1038                retry_after_ms: Some(1000),
1039                max_attempts: Some(3),
1040            });
1041        assert_eq!(err.details.provider.as_deref(), Some("openai"));
1042        assert_eq!(err.details.request_id.as_deref(), Some("req-456"));
1043        assert_eq!(err.details.upstream_status_code, Some(503));
1044        assert!(err.is_retryable());
1045        assert_eq!(err.retry.retry_after_ms, Some(1000));
1046        assert_eq!(err.retry.max_attempts, Some(3));
1047    }
1048
1049    #[test]
1050    fn test_error_component_display() {
1051        assert_eq!(ErrorComponent::Agent.to_string(), "agent");
1052        assert_eq!(ErrorComponent::Model.to_string(), "model");
1053        assert_eq!(ErrorComponent::Graph.to_string(), "graph");
1054        assert_eq!(ErrorComponent::Realtime.to_string(), "realtime");
1055        assert_eq!(ErrorComponent::Deploy.to_string(), "deploy");
1056    }
1057
1058    #[test]
1059    fn test_error_category_display() {
1060        assert_eq!(ErrorCategory::InvalidInput.to_string(), "invalid_input");
1061        assert_eq!(ErrorCategory::RateLimited.to_string(), "rate_limited");
1062        assert_eq!(ErrorCategory::NotFound.to_string(), "not_found");
1063        assert_eq!(ErrorCategory::Internal.to_string(), "internal");
1064    }
1065
1066    #[test]
1067    #[allow(clippy::unnecessary_literal_unwrap)]
1068    fn test_result_type() {
1069        let ok: Result<i32> = Ok(42);
1070        assert_eq!(ok.unwrap(), 42);
1071        let err: Result<i32> = Err(AdkError::config("invalid"));
1072        assert!(err.is_err());
1073    }
1074
1075    #[test]
1076    fn test_with_details() {
1077        let d = ErrorDetails {
1078            upstream_status_code: Some(502),
1079            request_id: Some("abc".into()),
1080            provider: Some("gemini".into()),
1081            metadata: HashMap::new(),
1082        };
1083        let err = AdkError::agent("test").with_details(d);
1084        assert_eq!(err.details.upstream_status_code, Some(502));
1085        assert_eq!(err.details.request_id.as_deref(), Some("abc"));
1086        assert_eq!(err.details.provider.as_deref(), Some("gemini"));
1087    }
1088
1089    #[test]
1090    fn test_debug_impl() {
1091        let s = format!("{:?}", AdkError::agent("debug test"));
1092        assert!(s.contains("AdkError"));
1093        assert!(s.contains("agent.legacy"));
1094    }
1095
1096    #[test]
1097    fn test_send_sync() {
1098        fn assert_send<T: Send>() {}
1099        fn assert_sync<T: Sync>() {}
1100        assert_send::<AdkError>();
1101        assert_sync::<AdkError>();
1102    }
1103}