1use serde::{Deserialize, Serialize};
4use serde_json::{Value, json};
5use std::collections::HashMap;
6use std::fmt;
7use std::time::Duration;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
18#[serde(rename_all = "snake_case")]
19pub enum ErrorComponent {
20 Agent,
22 Model,
24 Tool,
26 Session,
28 Artifact,
30 Memory,
32 Graph,
34 Realtime,
36 Code,
38 Server,
40 Auth,
42 Guardrail,
44 Eval,
46 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92pub enum ErrorCategory {
93 InvalidInput,
95 Unauthorized,
97 Forbidden,
99 NotFound,
101 RateLimited,
103 Timeout,
105 Unavailable,
107 Cancelled,
109 Internal,
111 Unsupported,
113 ResourceExhausted,
120 Conflict,
125}
126
127impl ErrorCategory {
128 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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
178pub struct RetryHint {
179 pub should_retry: bool,
181 #[serde(default, skip_serializing_if = "Option::is_none")]
183 pub retry_after_ms: Option<u64>,
184 #[serde(default, skip_serializing_if = "Option::is_none")]
186 pub max_attempts: Option<u32>,
187}
188
189impl RetryHint {
190 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 pub fn retry_after(&self) -> Option<Duration> {
202 self.retry_after_ms.map(Duration::from_millis)
203 }
204
205 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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
214pub struct ErrorDetails {
215 #[serde(default, skip_serializing_if = "Option::is_none")]
217 pub upstream_status_code: Option<u16>,
218 #[serde(default, skip_serializing_if = "Option::is_none")]
220 pub request_id: Option<String>,
221 #[serde(default, skip_serializing_if = "Option::is_none")]
223 pub provider: Option<String>,
224 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
230 pub metadata: HashMap<String, Value>,
231}
232
233pub struct AdkError {
263 pub component: ErrorComponent,
265 pub category: ErrorCategory,
267 pub code: &'static str,
269 pub message: String,
271 pub retry: RetryHint,
273 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 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 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 pub fn with_retry(mut self, retry: RetryHint) -> Self {
342 self.retry = retry;
343 self
344 }
345
346 pub fn with_details(mut self, details: ErrorDetails) -> Self {
348 self.details = Box::new(details);
349 self
350 }
351
352 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 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 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 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 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 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 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 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 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 pub fn agent(message: impl Into<String>) -> Self {
430 Self::new(ErrorComponent::Agent, ErrorCategory::Internal, "agent.legacy", message)
431 }
432
433 pub fn model(message: impl Into<String>) -> Self {
435 Self::new(ErrorComponent::Model, ErrorCategory::Internal, "model.legacy", message)
436 }
437
438 pub fn tool(message: impl Into<String>) -> Self {
440 Self::new(ErrorComponent::Tool, ErrorCategory::Internal, "tool.legacy", message)
441 }
442
443 pub fn session(message: impl Into<String>) -> Self {
445 Self::new(ErrorComponent::Session, ErrorCategory::Internal, "session.legacy", message)
446 }
447
448 pub fn memory(message: impl Into<String>) -> Self {
450 Self::new(ErrorComponent::Memory, ErrorCategory::Internal, "memory.legacy", message)
451 }
452
453 pub fn config(message: impl Into<String>) -> Self {
455 Self::new(ErrorComponent::Server, ErrorCategory::InvalidInput, "config.legacy", message)
456 }
457
458 pub fn artifact(message: impl Into<String>) -> Self {
460 Self::new(ErrorComponent::Artifact, ErrorCategory::Internal, "artifact.legacy", message)
461 }
462}
463
464impl AdkError {
465 pub fn is_agent(&self) -> bool {
467 self.component == ErrorComponent::Agent
468 }
469 pub fn is_model(&self) -> bool {
471 self.component == ErrorComponent::Model
472 }
473 pub fn is_tool(&self) -> bool {
475 self.component == ErrorComponent::Tool
476 }
477 pub fn is_session(&self) -> bool {
479 self.component == ErrorComponent::Session
480 }
481 pub fn is_artifact(&self) -> bool {
483 self.component == ErrorComponent::Artifact
484 }
485 pub fn is_memory(&self) -> bool {
487 self.component == ErrorComponent::Memory
488 }
489 pub fn is_config(&self) -> bool {
491 self.code == "config.legacy"
492 }
493}
494
495impl AdkError {
496 pub fn is_retryable(&self) -> bool {
498 self.retry.should_retry
499 }
500 pub fn is_not_found(&self) -> bool {
502 self.category == ErrorCategory::NotFound
503 }
504 pub fn is_unauthorized(&self) -> bool {
506 self.category == ErrorCategory::Unauthorized
507 }
508 pub fn is_rate_limited(&self) -> bool {
510 self.category == ErrorCategory::RateLimited
511 }
512 pub fn is_timeout(&self) -> bool {
514 self.category == ErrorCategory::Timeout
515 }
516 pub fn is_conflict(&self) -> bool {
518 self.category == ErrorCategory::Conflict
519 }
520
521 pub fn redacted(&self) -> String {
541 format!("{}.{} ({})", self.component, self.category, self.code)
542 }
543
544 pub fn diagnostics(&self) -> ErrorDiagnostics<'_> {
570 ErrorDiagnostics(self)
571 }
572}
573
574#[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
605fn 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
612pub const UPSTREAM_EXCERPT_BYTES: usize = 512;
615
616pub fn upstream_excerpt(text: &str) -> &str {
632 let text = text.trim();
633 &text[..text.floor_char_boundary(UPSTREAM_EXCERPT_BYTES)]
634}
635
636pub 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 #[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 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
702pub 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}