1use std::collections::BTreeMap;
4use std::error::Error as StdError;
5use std::fmt;
6
7use type_bridge_contract::sdk_diagnostic::{
8 SdkDiagnosticCategory, SdkDiagnosticDetailValue, SdkDiagnosticPathSegment,
9 SdkExecutionDiagnostic, SdkProjectionEvidenceSlotPresence, SdkQueryDiagnosticCategory,
10 SdkQueryDiagnosticPathKind,
11};
12use type_bridge_orm::match_request::MatchError;
13use type_bridge_orm::{
14 ProjectedCrudCompatibilityCause, ProjectedCrudCompatibilityFailure,
15 ProjectedCrudCompatibilityStage,
16};
17
18use crate::hooks::{CrudOperation, ModelKind};
19
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
22#[non_exhaustive]
23pub enum ErrorCategory {
24 Connection,
26 Schema,
28 ModelValidation,
30 Integrity,
32 QueryAuthoring,
34 QueryExecution,
36 Transaction,
38 Remote,
40 Capability,
42 ResourceLimit,
44 Cancelled,
46 NotFound,
48 Lifecycle,
50 Database,
52 Other,
54}
55
56impl ErrorCategory {
57 #[must_use]
59 pub const fn as_str(self) -> &'static str {
60 match self {
61 Self::Connection => "connection",
62 Self::Schema => "schema",
63 Self::ModelValidation => "model_validation",
64 Self::Integrity => "integrity",
65 Self::QueryAuthoring => "query_authoring",
66 Self::QueryExecution => "query_execution",
67 Self::Transaction => "transaction",
68 Self::Remote => "remote",
69 Self::Capability => "capability",
70 Self::ResourceLimit => "resource_limit",
71 Self::Cancelled => "cancelled",
72 Self::NotFound => "not_found",
73 Self::Lifecycle => "lifecycle",
74 Self::Database => "database",
75 Self::Other => "other",
76 }
77 }
78}
79
80impl fmt::Display for ErrorCategory {
81 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
82 formatter.write_str(self.as_str())
83 }
84}
85
86#[derive(Clone, Copy, Debug, Eq, PartialEq)]
88pub enum ModelValidationPhase {
89 Input,
91 Hydration,
93}
94
95#[derive(Clone, Debug, Eq, PartialEq)]
97#[non_exhaustive]
98pub enum ErrorDetail {
99 Text(String),
101 Long(i64),
103 Boolean(bool),
105 TextList(Vec<String>),
107 QueryCategory(QueryDiagnosticCategory),
109 QueryIdentity(String),
111 QueryIdentityList(Vec<String>),
113}
114
115#[derive(Clone, Copy, Debug, Eq, PartialEq)]
117#[non_exhaustive]
118pub enum QueryDiagnosticCategory {
119 InvalidPlan,
121 Cardinality,
123 UnsupportedCapability,
125 StaleSchema,
127 ResourceLimit,
129 Cancelled,
131 Provider,
133 ResultDecode,
135}
136
137#[derive(Clone, Copy, Debug, Eq, PartialEq)]
139#[non_exhaustive]
140pub enum QueryDiagnosticPathKind {
141 Request,
143 Plan,
145 Operation,
147 Predicate,
149 Output,
151 ProviderEvidence,
153 Result,
155}
156
157#[derive(Clone, Debug, Eq, PartialEq)]
159#[non_exhaustive]
160pub enum ErrorPathSegment {
161 Argument(String),
163 Field(String),
165 Index(u64),
167 Identifier(String),
169 Query(QueryDiagnosticPathKind),
171 QueryBinding(u16),
173 QueryField {
175 owner: String,
177 name: String,
179 },
180 QueryRole {
182 owner: String,
184 name: String,
186 },
187 QueryRoleEdge(u16),
189 QueryOutputSlot(u64),
191 QueryOutputName(String),
193 ContractField(String),
195 ContractIdentity(String),
197}
198
199#[derive(Clone, Debug, Eq, PartialEq)]
202pub struct ErrorDiagnostic {
203 path: Vec<ErrorPathSegment>,
204 details: BTreeMap<String, ErrorDetail>,
205}
206
207impl ErrorDiagnostic {
208 #[must_use]
210 pub fn path(&self) -> &[ErrorPathSegment] {
211 &self.path
212 }
213
214 #[must_use]
216 pub fn details(&self) -> &BTreeMap<String, ErrorDetail> {
217 &self.details
218 }
219}
220
221#[derive(Debug, thiserror::Error)]
223#[non_exhaustive]
224pub enum Error {
225 #[error("Model validation failed during {phase:?}: {message}")]
227 ModelValidation {
228 phase: ModelValidationPhase,
230 code: String,
232 path: Vec<String>,
234 message: String,
236 #[source]
238 source: Option<Box<dyn StdError + Send + Sync + 'static>>,
239 },
240
241 #[error("{category} error [{code}]: {message}")]
244 Classified {
245 category: ErrorCategory,
247 phase: Option<ModelValidationPhase>,
249 code: String,
251 path: Vec<String>,
253 diagnostic: Option<Box<ErrorDiagnostic>>,
255 message: String,
257 #[source]
259 source: Option<Box<dyn StdError + Send + Sync + 'static>>,
260 },
261
262 #[error("Schema verification failed: {message}")]
264 SchemaVerification {
265 message: String,
267 #[source]
269 source: Option<Box<dyn StdError + Send + Sync + 'static>>,
270 },
271
272 #[error("Connection error: {message}")]
274 Connection {
275 message: String,
277 #[source]
279 source: Option<Box<dyn StdError + Send + Sync + 'static>>,
280 },
281
282 #[error("Query execution error: {message}")]
284 QueryExecution {
285 message: String,
287 #[source]
289 source: Option<Box<dyn StdError + Send + Sync + 'static>>,
290 },
291
292 #[error("Transaction error: {message}")]
294 Transaction {
295 message: String,
297 #[source]
299 source: Option<Box<dyn StdError + Send + Sync + 'static>>,
300 },
301
302 #[error("Entity not found: {message}")]
304 NotFound {
305 message: String,
307 #[source]
309 source: Option<Box<dyn StdError + Send + Sync + 'static>>,
310 },
311
312 #[error("Database error: {message}")]
314 Database {
315 message: String,
317 #[source]
319 source: Option<Box<dyn StdError + Send + Sync + 'static>>,
320 },
321
322 #[error("Client error: {message}")]
324 Other {
325 message: String,
327 #[source]
329 source: Option<Box<dyn StdError + Send + Sync + 'static>>,
330 },
331}
332
333impl Error {
334 pub(crate) fn from_contract_diagnostic(
335 error: type_bridge_contract::diagnostic::Diagnostic,
336 ) -> Self {
337 use type_bridge_contract::diagnostic::DiagnosticCategory;
338
339 let category = match error.category() {
340 DiagnosticCategory::InvalidContract => ErrorCategory::Other,
341 DiagnosticCategory::UnsupportedCapability => ErrorCategory::Capability,
342 DiagnosticCategory::ResourceLimit => ErrorCategory::ResourceLimit,
343 DiagnosticCategory::Cancelled => ErrorCategory::Cancelled,
344 DiagnosticCategory::Integrity => ErrorCategory::Integrity,
345 };
346 let code = error.code().as_str().to_owned();
347 let message = error.to_string();
348 Self::classified_with_diagnostic(
349 category,
350 None,
351 code,
352 Vec::new(),
353 None,
354 message,
355 Some(Box::new(error)),
356 )
357 }
358
359 #[allow(dead_code)]
360 pub(crate) fn model_validation(
361 phase: ModelValidationPhase,
362 code: impl Into<String>,
363 path: Vec<String>,
364 message: impl Into<String>,
365 source: Option<Box<dyn StdError + Send + Sync + 'static>>,
366 ) -> Self {
367 Self::ModelValidation {
368 phase,
369 code: code.into(),
370 path,
371 message: message.into(),
372 source,
373 }
374 }
375
376 pub(crate) fn classified(
377 category: ErrorCategory,
378 phase: Option<ModelValidationPhase>,
379 code: impl Into<String>,
380 path: Vec<String>,
381 message: impl Into<String>,
382 source: Option<Box<dyn StdError + Send + Sync + 'static>>,
383 ) -> Self {
384 Self::classified_with_diagnostic(category, phase, code, path, None, message, source)
385 }
386
387 pub(crate) fn projection_evidence_rejection(
388 presence: SdkProjectionEvidenceSlotPresence,
389 ) -> Self {
390 let error = SdkExecutionDiagnostic::classify_detached_semantic_schema_fingerprint_rejection(
391 presence,
392 );
393 let code = error.code().as_str().to_owned();
394 let message = error.message().as_str().to_owned();
395 let path = error.path().iter().map(flatten_sdk_path).collect();
396 let diagnostic = ErrorDiagnostic {
397 path: error
398 .path()
399 .iter()
400 .map(|segment| match segment {
401 SdkDiagnosticPathSegment::Argument(value) => {
402 ErrorPathSegment::Argument(value.as_str().to_owned())
403 }
404 other => typed_sdk_path(other),
405 })
406 .collect(),
407 details: error
408 .details()
409 .iter()
410 .map(|(name, value)| (name.as_str().to_owned(), flatten_sdk_detail(value)))
411 .collect(),
412 };
413 Self::classified_with_diagnostic(
414 ErrorCategory::Integrity,
415 None,
416 code,
417 path,
418 Some(diagnostic),
419 message,
420 Some(Box::new(error)),
421 )
422 }
423
424 fn classified_with_diagnostic(
425 category: ErrorCategory,
426 phase: Option<ModelValidationPhase>,
427 code: impl Into<String>,
428 path: Vec<String>,
429 diagnostic: Option<ErrorDiagnostic>,
430 message: impl Into<String>,
431 source: Option<Box<dyn StdError + Send + Sync + 'static>>,
432 ) -> Self {
433 Self::Classified {
434 category,
435 phase,
436 code: code.into(),
437 path,
438 diagnostic: diagnostic.map(Box::new),
439 message: message.into(),
440 source,
441 }
442 }
443
444 #[must_use]
446 pub fn failure(&self) -> Option<type_bridge_contract::failure::Failure> {
447 let mut source = StdError::source(self);
448 while let Some(error) = source {
449 if let Some(diagnostic) = error.downcast_ref::<SdkExecutionDiagnostic>() {
450 return diagnostic.failure().cloned();
451 }
452 if let Some(error) = error.downcast_ref::<type_bridge_orm::OrmError>() {
453 return error.failure();
454 }
455 source = error.source();
456 }
457 None
458 }
459
460 #[must_use]
465 pub fn remote(
466 code: impl Into<String>,
467 message: impl Into<String>,
468 source: Option<Box<dyn StdError + Send + Sync + 'static>>,
469 ) -> Self {
470 Self::classified(
471 ErrorCategory::Remote,
472 None,
473 code,
474 Vec::new(),
475 message,
476 source,
477 )
478 }
479
480 pub(crate) fn from_match(error: MatchError, phase: ModelValidationPhase) -> Self {
481 Self::from_sdk_execution(type_bridge_orm::lower_match_error(&error), phase)
482 }
483
484 pub(crate) fn from_sdk_execution(
485 error: SdkExecutionDiagnostic,
486 model_phase: ModelValidationPhase,
487 ) -> Self {
488 let code = error.code().as_str().to_owned();
489 let message = error.message().as_str().to_owned();
490 let path = error.path().iter().map(flatten_sdk_path).collect();
491 let diagnostic_path = error.path().iter().map(typed_sdk_path).collect();
492 let details = error
493 .details()
494 .iter()
495 .map(|(name, value)| (name.as_str().to_owned(), flatten_sdk_detail(value)))
496 .collect();
497 let diagnostic = ErrorDiagnostic {
498 path: diagnostic_path,
499 details,
500 };
501 if let Some(query_category) = sdk_query_category(&error) {
502 let (category, phase) = match query_category {
503 SdkQueryDiagnosticCategory::InvalidPlan => (ErrorCategory::QueryAuthoring, None),
504 SdkQueryDiagnosticCategory::Cardinality
505 | SdkQueryDiagnosticCategory::ResultDecode => {
506 (ErrorCategory::ModelValidation, Some(model_phase))
507 }
508 SdkQueryDiagnosticCategory::UnsupportedCapability => {
509 (ErrorCategory::Capability, None)
510 }
511 SdkQueryDiagnosticCategory::StaleSchema => (ErrorCategory::Schema, None),
512 SdkQueryDiagnosticCategory::ResourceLimit => (ErrorCategory::ResourceLimit, None),
513 SdkQueryDiagnosticCategory::Cancelled => (ErrorCategory::Cancelled, None),
514 SdkQueryDiagnosticCategory::Provider => (ErrorCategory::QueryExecution, None),
515 _ => (ErrorCategory::Other, None),
516 };
517 return Self::classified_with_diagnostic(
518 category,
519 phase,
520 code,
521 path,
522 Some(diagnostic),
523 message,
524 Some(Box::new(error)),
525 );
526 }
527 match error.category() {
528 SdkDiagnosticCategory::InvalidInput | SdkDiagnosticCategory::Integrity => {
529 Self::ModelValidation {
530 phase: model_phase,
531 code,
532 path,
533 message,
534 source: Some(Box::new(error)),
535 }
536 }
537 SdkDiagnosticCategory::Provider => Self::QueryExecution {
538 message,
539 source: Some(Box::new(error)),
540 },
541 SdkDiagnosticCategory::Transaction => Self::Transaction {
542 message,
543 source: Some(Box::new(error)),
544 },
545 SdkDiagnosticCategory::UnsupportedCapability => Self::classified_with_diagnostic(
546 ErrorCategory::Capability,
547 None,
548 code,
549 path,
550 Some(diagnostic),
551 message,
552 Some(Box::new(error)),
553 ),
554 SdkDiagnosticCategory::ResourceLimit => Self::classified_with_diagnostic(
555 ErrorCategory::ResourceLimit,
556 None,
557 code,
558 path,
559 Some(diagnostic),
560 message,
561 Some(Box::new(error)),
562 ),
563 SdkDiagnosticCategory::Cancelled => Self::classified_with_diagnostic(
564 ErrorCategory::Cancelled,
565 None,
566 code,
567 path,
568 Some(diagnostic),
569 message,
570 Some(Box::new(error)),
571 ),
572 SdkDiagnosticCategory::Internal => Self::classified_with_diagnostic(
573 ErrorCategory::Other,
574 None,
575 code,
576 path,
577 Some(diagnostic),
578 message,
579 Some(Box::new(error)),
580 ),
581 _ => Self::Other {
582 message,
583 source: Some(Box::new(error)),
584 },
585 }
586 }
587
588 #[cfg(feature = "typedb")]
589 pub(crate) fn from_direct_connection(error: SdkExecutionDiagnostic) -> Self {
590 let category = match error.category() {
591 SdkDiagnosticCategory::InvalidInput | SdkDiagnosticCategory::Provider => {
592 ErrorCategory::Connection
593 }
594 SdkDiagnosticCategory::Integrity => ErrorCategory::Integrity,
595 SdkDiagnosticCategory::UnsupportedCapability => ErrorCategory::Capability,
596 SdkDiagnosticCategory::ResourceLimit => ErrorCategory::ResourceLimit,
597 SdkDiagnosticCategory::Cancelled => ErrorCategory::Cancelled,
598 SdkDiagnosticCategory::Transaction | SdkDiagnosticCategory::Internal => {
599 ErrorCategory::Other
600 }
601 _ => ErrorCategory::Other,
602 };
603 let code = error.code().as_str().to_owned();
604 let message = error.message().as_str().to_owned();
605 let path = error.path().iter().map(flatten_sdk_path).collect();
606 let diagnostic = ErrorDiagnostic {
607 path: error.path().iter().map(typed_sdk_path).collect(),
608 details: error
609 .details()
610 .iter()
611 .map(|(name, value)| (name.as_str().to_owned(), flatten_sdk_detail(value)))
612 .collect(),
613 };
614 Self::classified_with_diagnostic(
615 category,
616 None,
617 code,
618 path,
619 Some(diagnostic),
620 message,
621 Some(Box::new(error)),
622 )
623 }
624
625 pub(crate) fn from_projected_batch(
626 error: SdkExecutionDiagnostic,
627 model_phase: ModelValidationPhase,
628 ) -> Self {
629 let (category, phase) = match error.category() {
630 SdkDiagnosticCategory::InvalidInput => {
631 (ErrorCategory::ModelValidation, Some(model_phase))
632 }
633 SdkDiagnosticCategory::Integrity => (ErrorCategory::Integrity, Some(model_phase)),
634 SdkDiagnosticCategory::Provider => (ErrorCategory::QueryExecution, None),
635 SdkDiagnosticCategory::Transaction => (ErrorCategory::Transaction, None),
636 SdkDiagnosticCategory::UnsupportedCapability => (ErrorCategory::Capability, None),
637 SdkDiagnosticCategory::ResourceLimit => (ErrorCategory::ResourceLimit, None),
638 SdkDiagnosticCategory::Cancelled => (ErrorCategory::Cancelled, None),
639 SdkDiagnosticCategory::Internal => (ErrorCategory::Other, None),
640 _ => (ErrorCategory::Other, None),
641 };
642 let code = error.code().as_str().to_owned();
643 let message = error.message().as_str().to_owned();
644 let path = error.path().iter().map(flatten_sdk_path).collect();
645 let diagnostic = ErrorDiagnostic {
646 path: error
647 .path()
648 .iter()
649 .map(typed_projected_batch_path)
650 .collect(),
651 details: error
652 .details()
653 .iter()
654 .map(|(name, value)| (name.as_str().to_owned(), flatten_sdk_detail(value)))
655 .collect(),
656 };
657 Self::classified_with_diagnostic(
658 category,
659 phase,
660 code,
661 path,
662 Some(diagnostic),
663 message,
664 Some(Box::new(error)),
665 )
666 }
667
668 pub(crate) fn with_projected_batch_row(self, ordinal: u64) -> Self {
669 let row_path = [
670 ErrorPathSegment::Argument("rows".to_owned()),
671 ErrorPathSegment::Index(ordinal),
672 ];
673 match self {
674 Self::ModelValidation {
675 phase,
676 code,
677 mut path,
678 message,
679 source,
680 } => {
681 let mut typed_path = Vec::with_capacity(path.len().saturating_add(2));
682 typed_path.extend(row_path);
683 for segment in &path {
684 append_generated_path_segment(&mut typed_path, segment);
685 }
686 path.insert(0, format!("[{ordinal}]"));
687 path.insert(0, "rows".to_owned());
688 Self::classified_with_diagnostic(
689 ErrorCategory::ModelValidation,
690 Some(phase),
691 code,
692 path,
693 Some(ErrorDiagnostic {
694 path: typed_path,
695 details: BTreeMap::new(),
696 }),
697 message,
698 source,
699 )
700 }
701 Self::Classified {
702 category,
703 phase,
704 code,
705 mut path,
706 diagnostic,
707 message,
708 source,
709 } => {
710 path.insert(0, format!("[{ordinal}]"));
711 path.insert(0, "rows".to_owned());
712 let mut diagnostic = diagnostic.map_or_else(
713 || ErrorDiagnostic {
714 path: Vec::new(),
715 details: BTreeMap::new(),
716 },
717 |diagnostic| *diagnostic,
718 );
719 diagnostic.path.splice(0..0, row_path);
720 Self::classified_with_diagnostic(
721 category,
722 phase,
723 code,
724 path,
725 Some(diagnostic),
726 message,
727 source,
728 )
729 }
730 other => other,
731 }
732 }
733
734 pub(crate) fn from_projected_crud(
735 error: ProjectedCrudCompatibilityFailure,
736 kind: ModelKind,
737 operation: Option<CrudOperation>,
738 ) -> Self {
739 let (diagnostic, stage, cause) = error.into_parts();
740 let code = diagnostic.code().as_str();
741
742 if code == "mutation_rehydration_missing" {
743 let message = match (kind, operation) {
744 (ModelKind::Entity, Some(CrudOperation::Update)) => {
745 "updated entity was not returned"
746 }
747 (ModelKind::Entity, _) => "written entity was not returned",
748 (ModelKind::Relation, _) => "written relation was not returned",
749 };
750 return Self::model_validation(
751 ModelValidationPhase::Hydration,
752 "missing_post_write_row",
753 vec!["iid".into()],
754 message,
755 None,
756 );
757 }
758 if code == "relation_hydration_ambiguous" {
759 return Self::model_validation(
760 ModelValidationPhase::Hydration,
761 "ambiguous_provider_row",
762 vec!["iid".into()],
763 "provider returned multiple coalesced rows for one exact IID",
764 None,
765 );
766 }
767 if code == "hydrated_type_mismatch" {
768 let message = match kind {
769 ModelKind::Entity => "provider entity row has the wrong exact concrete type",
770 ModelKind::Relation => "provider relation row has the wrong exact concrete type",
771 };
772 return Self::model_validation(
773 ModelValidationPhase::Hydration,
774 "wrong_concrete_type",
775 vec!["type".into()],
776 message,
777 None,
778 );
779 }
780 if code == "hydrated_iid_missing" {
781 let message = match kind {
782 ModelKind::Entity => "provider entity row omitted its IID",
783 ModelKind::Relation => "provider relation row omitted its IID",
784 };
785 return Self::model_validation(
786 ModelValidationPhase::Hydration,
787 "missing_iid",
788 vec!["iid".into()],
789 message,
790 None,
791 );
792 }
793 if code == "hydrated_iid_mismatch" {
794 let message = match kind {
795 ModelKind::Entity => "provider entity row contains a noncanonical IID",
796 ModelKind::Relation => "provider relation row contains a noncanonical IID",
797 };
798 return Self::model_validation(
799 ModelValidationPhase::Hydration,
800 "noncanonical_iid",
801 vec!["iid".into()],
802 message,
803 None,
804 );
805 }
806 if kind == ModelKind::Relation
807 && code == "noncanonical_iid"
808 && diagnostic
809 .path()
810 .iter()
811 .any(|segment| matches!(segment, SdkDiagnosticPathSegment::Role(_)))
812 {
813 return Self::model_validation(
814 ModelValidationPhase::Input,
815 "noncanonical_player_iid",
816 projected_role_path(&diagnostic, "iid"),
817 "relation reference IID must be canonical",
818 None,
819 );
820 }
821 if kind == ModelKind::Relation
822 && diagnostic
823 .path()
824 .iter()
825 .any(|segment| matches!(segment, SdkDiagnosticPathSegment::Role(_)))
826 && matches!(
827 cause.as_ref(),
828 Some(ProjectedCrudCompatibilityCause::Orm(
829 type_bridge_orm::OrmError::Hydration { .. }
830 ))
831 )
832 {
833 return Self::model_validation(
834 ModelValidationPhase::Hydration,
835 "invalid_player_attributes",
836 projected_role_path(&diagnostic, "attributes"),
837 "provider role player attributes are outside the projected descriptor",
838 cause.and_then(projected_cause_source),
839 );
840 }
841 if kind == ModelKind::Relation
842 && code == "runtime_projection_mismatch"
843 && diagnostic
844 .path()
845 .iter()
846 .any(|segment| matches!(segment, SdkDiagnosticPathSegment::Role(_)))
847 {
848 return Self::model_validation(
849 ModelValidationPhase::Hydration,
850 "invalid_player_attributes",
851 projected_role_path(&diagnostic, "attributes"),
852 "provider role player attributes are outside the projected descriptor",
853 cause.and_then(projected_cause_source),
854 );
855 }
856 if kind == ModelKind::Relation {
857 let mapped = match code {
858 "hydrated_player_iid_missing" => Some((
859 "missing_player_iid",
860 "iid",
861 "provider role player omitted its IID",
862 )),
863 "hydrated_player_iid_invalid" => Some((
864 "noncanonical_player_iid",
865 "iid",
866 "provider role player contains a noncanonical IID",
867 )),
868 "hydrated_player_type_missing" => Some((
869 "missing_player_type",
870 "type",
871 "provider role player omitted its concrete type",
872 )),
873 "hydrated_role_player_not_accepted" => Some((
874 "player_not_allowed",
875 "type",
876 "provider role player type is outside the role",
877 )),
878 "projected_player_type_ambiguous" => Some((
879 "invalid_installed_projection",
880 "type",
881 "projected player authority is ambiguous",
882 )),
883 _ => None,
884 };
885 if let Some((legacy_code, suffix, message)) = mapped {
886 return Self::model_validation(
887 ModelValidationPhase::Hydration,
888 legacy_code,
889 projected_role_path(&diagnostic, suffix),
890 message,
891 None,
892 );
893 }
894 }
895
896 if let Some(cause) = cause {
897 return match cause {
898 ProjectedCrudCompatibilityCause::Orm(error) => {
899 if stage == ProjectedCrudCompatibilityStage::Hydration {
900 Self::from_orm_hydration(error)
901 } else {
902 Self::from_orm(error)
903 }
904 }
905 ProjectedCrudCompatibilityCause::Commit(error) => {
906 Self::from_orm(error.into_orm_error())
907 }
908 };
909 }
910 Self::from_sdk_execution(
911 diagnostic,
912 if stage == ProjectedCrudCompatibilityStage::Hydration {
913 ModelValidationPhase::Hydration
914 } else {
915 ModelValidationPhase::Input
916 },
917 )
918 }
919
920 pub(crate) fn from_hook(error: crate::hooks::HookError) -> Self {
921 let code = match error {
922 crate::hooks::HookError::Rejected { .. } => "lifecycle_hook_rejected",
923 crate::hooks::HookError::Internal { .. } => "lifecycle_hook_failed",
924 };
925 Self::classified(
926 ErrorCategory::Lifecycle,
927 None,
928 code,
929 Vec::new(),
930 error.to_string(),
931 Some(Box::new(error)),
932 )
933 }
934
935 #[allow(dead_code)]
936 pub(crate) fn from_orm(err: type_bridge_orm::OrmError) -> Self {
937 match err {
940 type_bridge_orm::OrmError::Match(error) => {
941 Self::from_match(error, ModelValidationPhase::Input)
942 }
943 error @ type_bridge_orm::OrmError::Connection(_) => Self::Connection {
944 message: error.to_string(),
945 source: Some(Box::new(error)),
946 },
947 error @ type_bridge_orm::OrmError::QueryExecution(_) => Self::QueryExecution {
948 message: error.to_string(),
949 source: Some(Box::new(error)),
950 },
951 error @ type_bridge_orm::OrmError::Transaction(_) => Self::Transaction {
952 message: error.to_string(),
953 source: Some(Box::new(error)),
954 },
955 error @ type_bridge_orm::OrmError::NotFound(_) => Self::NotFound {
956 message: error.to_string(),
957 source: Some(Box::new(error)),
958 },
959 error @ type_bridge_orm::OrmError::Hydration { .. } => Self::ModelValidation {
960 phase: ModelValidationPhase::Hydration,
961 code: "invalid_provider_evidence".into(),
962 path: vec![],
963 message: error.to_string(),
964 source: Some(Box::new(error)),
965 },
966 error => Self::Database {
967 message: error.to_string(),
968 source: Some(Box::new(error)),
969 },
970 }
971 }
972
973 pub(crate) fn from_orm_hydration(err: type_bridge_orm::OrmError) -> Self {
974 match err {
975 type_bridge_orm::OrmError::Match(error) => {
976 Self::from_match(error, ModelValidationPhase::Hydration)
977 }
978 error => Self::from_orm(error),
979 }
980 }
981
982 #[must_use]
984 pub const fn category(&self) -> ErrorCategory {
985 match self {
986 Self::ModelValidation { .. } => ErrorCategory::ModelValidation,
987 Self::Classified { category, .. } => *category,
988 Self::SchemaVerification { .. } => ErrorCategory::Schema,
989 Self::Connection { .. } => ErrorCategory::Connection,
990 Self::QueryExecution { .. } => ErrorCategory::QueryExecution,
991 Self::Transaction { .. } => ErrorCategory::Transaction,
992 Self::NotFound { .. } => ErrorCategory::NotFound,
993 Self::Database { .. } => ErrorCategory::Database,
994 Self::Other { .. } => ErrorCategory::Other,
995 }
996 }
997
998 #[must_use]
1006 pub fn sdk_category(&self) -> Option<&'static str> {
1007 StdError::source(self)
1008 .and_then(|source| source.downcast_ref::<SdkExecutionDiagnostic>())
1009 .map(|diagnostic| diagnostic.category().as_str())
1010 }
1011
1012 #[must_use]
1014 pub fn message(&self) -> &str {
1015 match self {
1016 Self::ModelValidation { message, .. }
1017 | Self::Classified { message, .. }
1018 | Self::SchemaVerification { message, .. }
1019 | Self::Connection { message, .. }
1020 | Self::QueryExecution { message, .. }
1021 | Self::Transaction { message, .. }
1022 | Self::NotFound { message, .. }
1023 | Self::Database { message, .. }
1024 | Self::Other { message, .. } => message,
1025 }
1026 }
1027
1028 #[must_use]
1030 pub fn code(&self) -> Option<&str> {
1031 match self {
1032 Self::ModelValidation { code, .. } | Self::Classified { code, .. } => Some(code),
1033 _ => None,
1034 }
1035 }
1036
1037 #[must_use]
1039 pub fn path(&self) -> Option<&[String]> {
1040 match self {
1041 Self::ModelValidation { path, .. } | Self::Classified { path, .. } => Some(path),
1042 _ => None,
1043 }
1044 }
1045
1046 #[must_use]
1051 pub fn diagnostic_path(&self) -> Option<&[ErrorPathSegment]> {
1052 match self {
1053 Self::Classified { diagnostic, .. } => diagnostic.as_deref().map(ErrorDiagnostic::path),
1054 _ => None,
1055 }
1056 }
1057
1058 #[must_use]
1060 pub fn details(&self) -> Option<&BTreeMap<String, ErrorDetail>> {
1061 match self {
1062 Self::Classified { diagnostic, .. } => {
1063 diagnostic.as_deref().map(ErrorDiagnostic::details)
1064 }
1065 _ => None,
1066 }
1067 }
1068
1069 #[must_use]
1071 pub const fn model_validation_phase(&self) -> Option<ModelValidationPhase> {
1072 match self {
1073 Self::ModelValidation { phase, .. } => Some(*phase),
1074 Self::Classified { phase, .. } => *phase,
1075 _ => None,
1076 }
1077 }
1078}
1079
1080fn flatten_sdk_path(segment: &SdkDiagnosticPathSegment) -> String {
1081 match segment {
1082 SdkDiagnosticPathSegment::Argument(value) => value.as_str().to_owned(),
1083 SdkDiagnosticPathSegment::Index(value) => format!("[{value}]"),
1084 SdkDiagnosticPathSegment::Type(_) => "type".into(),
1085 SdkDiagnosticPathSegment::Field(value) => value.attribute().label().as_str().to_owned(),
1086 SdkDiagnosticPathSegment::Role(value) => value.label().as_str().to_owned(),
1087 SdkDiagnosticPathSegment::Query(value) => value.as_str().to_owned(),
1088 SdkDiagnosticPathSegment::QueryBinding(value) => format!("binding[{value}]"),
1089 SdkDiagnosticPathSegment::QueryField { owner, name } => {
1090 format!("{}.{}", owner.as_str(), name.as_str())
1091 }
1092 SdkDiagnosticPathSegment::QueryRole { owner, name } => {
1093 format!("{}.{}", owner.as_str(), name.as_str())
1094 }
1095 SdkDiagnosticPathSegment::QueryRoleEdge(value) => format!("role_edge[{value}]"),
1096 SdkDiagnosticPathSegment::QueryOutputSlot(value) => format!("output[{value}]"),
1097 SdkDiagnosticPathSegment::QueryOutputName(value)
1098 | SdkDiagnosticPathSegment::ContractField(value)
1099 | SdkDiagnosticPathSegment::ContractIdentity(value) => value.as_str().to_owned(),
1100 _ => "diagnostic".into(),
1101 }
1102}
1103
1104fn projected_role_path(diagnostic: &SdkExecutionDiagnostic, suffix: &'static str) -> Vec<String> {
1105 let role = diagnostic.path().iter().find_map(|segment| {
1106 let SdkDiagnosticPathSegment::Role(role) = segment else {
1107 return None;
1108 };
1109 Some(role.label().as_str())
1110 });
1111 let index = diagnostic.path().iter().find_map(|segment| {
1112 let SdkDiagnosticPathSegment::Index(index) = segment else {
1113 return None;
1114 };
1115 Some(*index)
1116 });
1117 let head = match (role, index) {
1118 (Some(role), Some(index)) => format!("{role}[{index}]"),
1119 (Some(role), None) => role.to_owned(),
1120 _ => "roles".to_owned(),
1121 };
1122 vec![head, suffix.to_owned()]
1123}
1124
1125fn projected_cause_source(
1126 cause: ProjectedCrudCompatibilityCause,
1127) -> Option<Box<dyn StdError + Send + Sync + 'static>> {
1128 match cause {
1129 ProjectedCrudCompatibilityCause::Orm(error) => Some(Box::new(error)),
1130 ProjectedCrudCompatibilityCause::Commit(error) => Some(Box::new(error)),
1131 }
1132}
1133
1134fn typed_sdk_path(segment: &SdkDiagnosticPathSegment) -> ErrorPathSegment {
1135 match segment {
1136 SdkDiagnosticPathSegment::Argument(value) => {
1137 ErrorPathSegment::Field(value.as_str().to_owned())
1138 }
1139 SdkDiagnosticPathSegment::Index(value) => ErrorPathSegment::Index(*value),
1140 SdkDiagnosticPathSegment::Type(value) => ErrorPathSegment::Identifier(format!(
1141 "{}:{}",
1142 match value.kind() {
1143 type_bridge_contract::id::TypeKind::Entity => "entity",
1144 type_bridge_contract::id::TypeKind::Relation => "relation",
1145 type_bridge_contract::id::TypeKind::Attribute => "attribute",
1146 type_bridge_contract::id::TypeKind::Struct => "struct",
1147 },
1148 value.label().as_str()
1149 )),
1150 SdkDiagnosticPathSegment::Field(value) => ErrorPathSegment::Identifier(format!(
1151 "{}:{}",
1152 value.owner().label().as_str(),
1153 value.attribute().label().as_str()
1154 )),
1155 SdkDiagnosticPathSegment::Role(value) => ErrorPathSegment::Identifier(format!(
1156 "{}:{}",
1157 value.declaring_relation().as_str(),
1158 value.label().as_str()
1159 )),
1160 SdkDiagnosticPathSegment::Query(value) => {
1161 ErrorPathSegment::Query(acceptance_path_kind(*value))
1162 }
1163 SdkDiagnosticPathSegment::QueryBinding(value) => ErrorPathSegment::QueryBinding(*value),
1164 SdkDiagnosticPathSegment::QueryField { owner, name } => ErrorPathSegment::QueryField {
1165 owner: owner.as_str().to_owned(),
1166 name: name.as_str().to_owned(),
1167 },
1168 SdkDiagnosticPathSegment::QueryRole { owner, name } => ErrorPathSegment::QueryRole {
1169 owner: owner.as_str().to_owned(),
1170 name: name.as_str().to_owned(),
1171 },
1172 SdkDiagnosticPathSegment::QueryRoleEdge(value) => ErrorPathSegment::QueryRoleEdge(*value),
1173 SdkDiagnosticPathSegment::QueryOutputSlot(value) => {
1174 ErrorPathSegment::QueryOutputSlot(*value)
1175 }
1176 SdkDiagnosticPathSegment::QueryOutputName(value) => {
1177 ErrorPathSegment::QueryOutputName(value.as_str().to_owned())
1178 }
1179 SdkDiagnosticPathSegment::ContractField(value) => {
1180 ErrorPathSegment::ContractField(value.as_str().to_owned())
1181 }
1182 SdkDiagnosticPathSegment::ContractIdentity(value) => {
1183 ErrorPathSegment::ContractIdentity(value.as_str().to_owned())
1184 }
1185 _ => ErrorPathSegment::Identifier("diagnostic".into()),
1186 }
1187}
1188
1189fn typed_projected_batch_path(segment: &SdkDiagnosticPathSegment) -> ErrorPathSegment {
1190 match segment {
1191 SdkDiagnosticPathSegment::Argument(value) => {
1192 ErrorPathSegment::Argument(value.as_str().to_owned())
1193 }
1194 other => typed_sdk_path(other),
1195 }
1196}
1197
1198fn append_generated_path_segment(path: &mut Vec<ErrorPathSegment>, segment: &str) {
1199 let Some(first_index) = segment.find('[') else {
1200 path.push(ErrorPathSegment::Field(segment.to_owned()));
1201 return;
1202 };
1203 let mut parsed = Vec::new();
1204 if first_index > 0 {
1205 parsed.push(ErrorPathSegment::Field(segment[..first_index].to_owned()));
1206 }
1207 let mut remainder = &segment[first_index..];
1208 while remainder.starts_with('[') {
1209 let Some(end) = remainder.find(']') else {
1210 path.push(ErrorPathSegment::Field(segment.to_owned()));
1211 return;
1212 };
1213 let Ok(index) = remainder[1..end].parse::<u64>() else {
1214 path.push(ErrorPathSegment::Field(segment.to_owned()));
1215 return;
1216 };
1217 parsed.push(ErrorPathSegment::Index(index));
1218 remainder = &remainder[end + 1..];
1219 }
1220 if !remainder.is_empty() || parsed.is_empty() {
1221 path.push(ErrorPathSegment::Field(segment.to_owned()));
1222 } else {
1223 path.extend(parsed);
1224 }
1225}
1226
1227fn flatten_sdk_detail(value: &SdkDiagnosticDetailValue) -> ErrorDetail {
1228 match value {
1229 SdkDiagnosticDetailValue::Boolean(value) => ErrorDetail::Boolean(*value),
1230 SdkDiagnosticDetailValue::Count(value) | SdkDiagnosticDetailValue::ByteCount(value) => {
1231 i64::try_from(*value)
1232 .map_or_else(|_| ErrorDetail::Text(value.to_string()), ErrorDetail::Long)
1233 }
1234 SdkDiagnosticDetailValue::Capability(value) => ErrorDetail::Text(value.as_str().to_owned()),
1235 SdkDiagnosticDetailValue::ValueType(value) => ErrorDetail::Text(value.as_str().to_owned()),
1236 SdkDiagnosticDetailValue::Type(value) => {
1237 ErrorDetail::Text(value.label().as_str().to_owned())
1238 }
1239 SdkDiagnosticDetailValue::Field(value) => {
1240 ErrorDetail::Text(value.attribute().label().as_str().to_owned())
1241 }
1242 SdkDiagnosticDetailValue::Role(value) => {
1243 ErrorDetail::Text(value.label().as_str().to_owned())
1244 }
1245 SdkDiagnosticDetailValue::Fingerprint(value) => ErrorDetail::Text(value.digest().to_hex()),
1246 SdkDiagnosticDetailValue::ProviderOperation(value) => {
1247 ErrorDetail::Text(value.as_str().to_owned())
1248 }
1249 SdkDiagnosticDetailValue::CommitOutcome(value) => {
1250 ErrorDetail::Text(value.as_str().to_owned())
1251 }
1252 SdkDiagnosticDetailValue::Signed(value) => ErrorDetail::Long(*value),
1253 SdkDiagnosticDetailValue::QueryCategory(value) => {
1254 ErrorDetail::QueryCategory(query_category(*value))
1255 }
1256 SdkDiagnosticDetailValue::QueryIdentity(value) => {
1257 ErrorDetail::QueryIdentity(value.as_str().to_owned())
1258 }
1259 SdkDiagnosticDetailValue::QueryIdentityList(values) => ErrorDetail::QueryIdentityList(
1260 values
1261 .iter()
1262 .map(|value| value.as_str().to_owned())
1263 .collect(),
1264 ),
1265 _ => ErrorDetail::Text("diagnostic".into()),
1266 }
1267}
1268
1269fn sdk_query_category(error: &SdkExecutionDiagnostic) -> Option<SdkQueryDiagnosticCategory> {
1270 error.details().iter().find_map(|(name, value)| {
1271 (name.as_str() == "query_category").then(|| {
1272 let SdkDiagnosticDetailValue::QueryCategory(category) = value else {
1273 return None;
1274 };
1275 Some(*category)
1276 })?
1277 })
1278}
1279
1280const fn query_category(value: SdkQueryDiagnosticCategory) -> QueryDiagnosticCategory {
1281 match value {
1282 SdkQueryDiagnosticCategory::InvalidPlan => QueryDiagnosticCategory::InvalidPlan,
1283 SdkQueryDiagnosticCategory::Cardinality => QueryDiagnosticCategory::Cardinality,
1284 SdkQueryDiagnosticCategory::UnsupportedCapability => {
1285 QueryDiagnosticCategory::UnsupportedCapability
1286 }
1287 SdkQueryDiagnosticCategory::StaleSchema => QueryDiagnosticCategory::StaleSchema,
1288 SdkQueryDiagnosticCategory::ResourceLimit => QueryDiagnosticCategory::ResourceLimit,
1289 SdkQueryDiagnosticCategory::Cancelled => QueryDiagnosticCategory::Cancelled,
1290 SdkQueryDiagnosticCategory::Provider => QueryDiagnosticCategory::Provider,
1291 SdkQueryDiagnosticCategory::ResultDecode => QueryDiagnosticCategory::ResultDecode,
1292 _ => QueryDiagnosticCategory::ResultDecode,
1293 }
1294}
1295
1296const fn acceptance_path_kind(value: SdkQueryDiagnosticPathKind) -> QueryDiagnosticPathKind {
1297 match value {
1298 SdkQueryDiagnosticPathKind::Request => QueryDiagnosticPathKind::Request,
1299 SdkQueryDiagnosticPathKind::Plan => QueryDiagnosticPathKind::Plan,
1300 SdkQueryDiagnosticPathKind::Operation => QueryDiagnosticPathKind::Operation,
1301 SdkQueryDiagnosticPathKind::Predicate => QueryDiagnosticPathKind::Predicate,
1302 SdkQueryDiagnosticPathKind::Output => QueryDiagnosticPathKind::Output,
1303 SdkQueryDiagnosticPathKind::ProviderEvidence => QueryDiagnosticPathKind::ProviderEvidence,
1304 SdkQueryDiagnosticPathKind::Result => QueryDiagnosticPathKind::Result,
1305 _ => QueryDiagnosticPathKind::Result,
1306 }
1307}
1308
1309pub type Result<T, E = Error> = std::result::Result<T, E>;
1311
1312#[cfg(test)]
1313mod tests {
1314 use super::*;
1315
1316 #[test]
1317 fn typed_failure_keeps_the_released_variant_and_structural_outcome() {
1318 use type_bridge_contract::failure::{Failure, LockKind, Phase, Reason};
1319 let failure = Failure::Rejected {
1320 phase: Phase::Commit,
1321 reason: Reason::Conflict {
1322 lock: LockKind::Exclusive,
1323 },
1324 op_index: Some(3),
1325 };
1326 let diagnostic = SdkExecutionDiagnostic::from_failure(&failure, Default::default());
1327 let error = Error::from_sdk_execution(diagnostic, ModelValidationPhase::Input);
1328 assert_eq!(error.failure(), Some(failure));
1329 assert!(matches!(error, Error::Transaction { .. }));
1330 assert_eq!(error.category(), ErrorCategory::Transaction);
1331 assert!(StdError::source(&error).is_some());
1332 }
1333
1334 #[cfg(feature = "typedb")]
1335 #[test]
1336 fn orm_typed_failure_keeps_the_released_variant() {
1337 let orm = type_bridge_orm::OrmError::QueryExecution(
1338 "[CNT9] TypeDB query rejected: unique constraint".to_owned(),
1339 );
1340 let failure = orm.failure().expect("runtime rendering is typed");
1341 let error = Error::from_orm(orm);
1342 assert!(matches!(error, Error::QueryExecution { .. }));
1343 assert_eq!(error.failure(), Some(failure));
1344 }
1345 #[test]
1346 fn public_error_categories_and_remote_constructor_are_stable() {
1347 let categories = [
1348 (ErrorCategory::Connection, "connection"),
1349 (ErrorCategory::Schema, "schema"),
1350 (ErrorCategory::ModelValidation, "model_validation"),
1351 (ErrorCategory::Integrity, "integrity"),
1352 (ErrorCategory::QueryAuthoring, "query_authoring"),
1353 (ErrorCategory::QueryExecution, "query_execution"),
1354 (ErrorCategory::Transaction, "transaction"),
1355 (ErrorCategory::Remote, "remote"),
1356 (ErrorCategory::Capability, "capability"),
1357 (ErrorCategory::ResourceLimit, "resource_limit"),
1358 (ErrorCategory::NotFound, "not_found"),
1359 (ErrorCategory::Lifecycle, "lifecycle"),
1360 (ErrorCategory::Database, "database"),
1361 (ErrorCategory::Other, "other"),
1362 ];
1363 for (category, spelling) in categories {
1364 assert_eq!(category.as_str(), spelling);
1365 assert_eq!(category.to_string(), spelling);
1366 }
1367
1368 let error = Error::remote("remote_transport", "connection reset", None);
1369 assert_eq!(error.category(), ErrorCategory::Remote);
1370 assert_eq!(error.code(), Some("remote_transport"));
1371 assert_eq!(error.path(), Some(&[][..]));
1372 assert_eq!(error.message(), "connection reset");
1373 }
1374}
1375
1376#[cfg(all(test, feature = "typedb"))]
1377#[path = "../../../../tests/support/typed_failure_live.rs"]
1378mod typed_failure_live;
1379#[cfg(all(test, feature = "typedb"))]
1380#[tokio::test]
1381#[ignore = "requires an owned TypeDB 3.13.6 container and failure-smoke environment"]
1382async fn live_provider_failures_reach_rust_error() {
1383 for (case, error) in typed_failure_live::observations("tb_failure_rust").await {
1384 let error = Error::from_sdk_execution(
1385 typed_failure_live::diagnostic(error),
1386 ModelValidationPhase::Input,
1387 );
1388 let failure = error.failure().expect("typed failure retained by SDK");
1389 assert!(matches!(
1390 error,
1391 Error::Transaction { .. } | Error::QueryExecution { .. }
1392 ));
1393 assert_eq!(failure.retry_safe(), case != "paused");
1394 assert!(!format!("{error} {error:?}").contains("SECRET_SENTINEL"));
1395 println!("{case}: {}", failure.host_json());
1396 }
1397}