1#[cfg(test)]
9mod tests;
10
11use std::fmt;
12use thiserror::Error as ThisError;
13
14#[derive(Debug, ThisError)]
115#[error("{message}")]
116pub struct InternalError {
117 pub(crate) class: ErrorClass,
118 pub(crate) origin: ErrorOrigin,
119 pub(crate) message: String,
120
121 pub(crate) detail: Option<ErrorDetail>,
124}
125
126impl InternalError {
127 #[cold]
131 #[inline(never)]
132 pub fn new(class: ErrorClass, origin: ErrorOrigin, message: impl Into<String>) -> Self {
133 let message = message.into();
134
135 let detail = match (class, origin) {
136 (ErrorClass::Corruption, ErrorOrigin::Store) => {
137 Some(ErrorDetail::Store(StoreError::Corrupt {
138 message: message.clone(),
139 }))
140 }
141 (ErrorClass::InvariantViolation, ErrorOrigin::Store) => {
142 Some(ErrorDetail::Store(StoreError::InvariantViolation {
143 message: message.clone(),
144 }))
145 }
146 _ => None,
147 };
148
149 Self {
150 class,
151 origin,
152 message,
153 detail,
154 }
155 }
156
157 #[must_use]
159 pub const fn class(&self) -> ErrorClass {
160 self.class
161 }
162
163 #[must_use]
165 pub const fn origin(&self) -> ErrorOrigin {
166 self.origin
167 }
168
169 #[must_use]
171 pub fn message(&self) -> &str {
172 &self.message
173 }
174
175 #[must_use]
177 pub const fn detail(&self) -> Option<&ErrorDetail> {
178 self.detail.as_ref()
179 }
180
181 #[must_use]
183 pub fn into_message(self) -> String {
184 self.message
185 }
186
187 #[cold]
189 #[inline(never)]
190 pub(crate) fn classified(
191 class: ErrorClass,
192 origin: ErrorOrigin,
193 message: impl Into<String>,
194 ) -> Self {
195 Self::new(class, origin, message)
196 }
197
198 #[cold]
200 #[inline(never)]
201 pub(crate) fn with_message(self, message: impl Into<String>) -> Self {
202 Self::classified(self.class, self.origin, message)
203 }
204
205 #[cold]
209 #[inline(never)]
210 pub(crate) fn with_origin(self, origin: ErrorOrigin) -> Self {
211 Self::classified(self.class, origin, self.message)
212 }
213
214 #[cold]
216 #[inline(never)]
217 pub(crate) fn index_invariant(message: impl Into<String>) -> Self {
218 Self::new(
219 ErrorClass::InvariantViolation,
220 ErrorOrigin::Index,
221 message.into(),
222 )
223 }
224
225 pub(crate) fn index_key_field_count_exceeds_max(
227 index_name: &str,
228 field_count: usize,
229 max_fields: usize,
230 ) -> Self {
231 Self::index_invariant(format!(
232 "index '{index_name}' has {field_count} fields (max {max_fields})",
233 ))
234 }
235
236 pub(crate) fn index_key_item_field_missing_on_entity_model(field: &str) -> Self {
238 Self::index_invariant(format!(
239 "index key item field missing on entity model: {field}",
240 ))
241 }
242
243 pub(crate) fn index_key_item_field_missing_on_lookup_row(field: &str) -> Self {
245 Self::index_invariant(format!(
246 "index key item field missing on lookup row: {field}",
247 ))
248 }
249
250 pub(crate) fn index_expression_source_type_mismatch(
252 index_name: &str,
253 expression: impl fmt::Display,
254 expected: &str,
255 source_label: &str,
256 ) -> Self {
257 Self::index_invariant(format!(
258 "index '{index_name}' expression '{expression}' expected {expected} source value, got {source_label}",
259 ))
260 }
261
262 #[cold]
265 #[inline(never)]
266 pub(crate) fn planner_executor_invariant(reason: impl Into<String>) -> Self {
267 Self::new(
268 ErrorClass::InvariantViolation,
269 ErrorOrigin::Planner,
270 Self::executor_invariant_message(reason),
271 )
272 }
273
274 #[cold]
277 #[inline(never)]
278 pub(crate) fn query_executor_invariant(reason: impl Into<String>) -> Self {
279 Self::new(
280 ErrorClass::InvariantViolation,
281 ErrorOrigin::Query,
282 Self::executor_invariant_message(reason),
283 )
284 }
285
286 #[cold]
289 #[inline(never)]
290 pub(crate) fn cursor_executor_invariant(reason: impl Into<String>) -> Self {
291 Self::new(
292 ErrorClass::InvariantViolation,
293 ErrorOrigin::Cursor,
294 Self::executor_invariant_message(reason),
295 )
296 }
297
298 #[cold]
300 #[inline(never)]
301 pub(crate) fn executor_invariant(message: impl Into<String>) -> Self {
302 Self::new(
303 ErrorClass::InvariantViolation,
304 ErrorOrigin::Executor,
305 message.into(),
306 )
307 }
308
309 #[cold]
311 #[inline(never)]
312 pub(crate) fn executor_internal(message: impl Into<String>) -> Self {
313 Self::new(ErrorClass::Internal, ErrorOrigin::Executor, message.into())
314 }
315
316 #[cold]
318 #[inline(never)]
319 pub(crate) fn executor_unsupported(message: impl Into<String>) -> Self {
320 Self::new(
321 ErrorClass::Unsupported,
322 ErrorOrigin::Executor,
323 message.into(),
324 )
325 }
326
327 pub(crate) fn mutation_entity_primary_key_missing(entity_path: &str, field_name: &str) -> Self {
329 Self::executor_invariant(format!(
330 "entity primary key field missing: {entity_path} field={field_name}",
331 ))
332 }
333
334 pub(crate) fn mutation_entity_primary_key_invalid_value(
336 entity_path: &str,
337 field_name: &str,
338 value: &crate::value::Value,
339 ) -> Self {
340 Self::executor_invariant(format!(
341 "entity primary key field has invalid value: {entity_path} field={field_name} value={value:?}",
342 ))
343 }
344
345 pub(crate) fn mutation_entity_primary_key_type_mismatch(
347 entity_path: &str,
348 field_name: &str,
349 value: &crate::value::Value,
350 ) -> Self {
351 Self::executor_invariant(format!(
352 "entity primary key field type mismatch: {entity_path} field={field_name} value={value:?}",
353 ))
354 }
355
356 pub(crate) fn mutation_entity_primary_key_mismatch(
358 entity_path: &str,
359 field_name: &str,
360 field_value: &crate::value::Value,
361 identity_key: &crate::value::Value,
362 ) -> Self {
363 Self::executor_invariant(format!(
364 "entity primary key mismatch: {entity_path} field={field_name} field_value={field_value:?} id_key={identity_key:?}",
365 ))
366 }
367
368 pub(crate) fn mutation_entity_field_missing(
370 entity_path: &str,
371 field_name: &str,
372 indexed: bool,
373 ) -> Self {
374 let indexed_note = if indexed { " (indexed)" } else { "" };
375
376 Self::executor_invariant(format!(
377 "entity field missing: {entity_path} field={field_name}{indexed_note}",
378 ))
379 }
380
381 pub(crate) fn mutation_structural_patch_required_field_missing(
383 entity_path: &str,
384 field_name: &str,
385 ) -> Self {
386 Self::executor_invariant(format!(
387 "structural patch missing required field: {entity_path} field={field_name}",
388 ))
389 }
390
391 pub(crate) fn mutation_entity_field_type_mismatch(
393 entity_path: &str,
394 field_name: &str,
395 value: &crate::value::Value,
396 ) -> Self {
397 Self::executor_invariant(format!(
398 "entity field type mismatch: {entity_path} field={field_name} value={value:?}",
399 ))
400 }
401
402 pub(crate) fn mutation_generated_field_explicit(entity_path: &str, field_name: &str) -> Self {
404 Self::executor_unsupported(format!(
405 "generated field may not be explicitly written: {entity_path} field={field_name}",
406 ))
407 }
408
409 pub(crate) fn mutation_create_missing_authored_fields(
411 entity_path: &str,
412 field_names: &str,
413 ) -> Self {
414 Self::executor_unsupported(format!(
415 "create requires explicit values for authorable fields {field_names}: {entity_path}",
416 ))
417 }
418
419 pub(crate) fn mutation_structural_after_image_invalid(
424 entity_path: &str,
425 data_key: impl fmt::Display,
426 detail: impl AsRef<str>,
427 ) -> Self {
428 Self::executor_invariant(format!(
429 "mutation result is invalid: {entity_path} key={data_key} ({})",
430 detail.as_ref(),
431 ))
432 }
433
434 pub(crate) fn mutation_structural_field_unknown(entity_path: &str, field_name: &str) -> Self {
436 Self::executor_invariant(format!(
437 "mutation field not found: {entity_path} field={field_name}",
438 ))
439 }
440
441 pub(crate) fn mutation_decimal_scale_mismatch(
443 entity_path: &str,
444 field_name: &str,
445 expected_scale: impl fmt::Display,
446 actual_scale: impl fmt::Display,
447 ) -> Self {
448 Self::executor_unsupported(format!(
449 "decimal field scale mismatch: {entity_path} field={field_name} expected_scale={expected_scale} actual_scale={actual_scale}",
450 ))
451 }
452
453 pub(crate) fn mutation_text_max_len_exceeded(
455 entity_path: &str,
456 field_name: &str,
457 max_len: impl fmt::Display,
458 actual_len: impl fmt::Display,
459 ) -> Self {
460 Self::executor_unsupported(format!(
461 "text length exceeds max_len: {entity_path} field={field_name} max_len={max_len} actual_len={actual_len}",
462 ))
463 }
464
465 pub(crate) fn mutation_set_field_list_required(entity_path: &str, field_name: &str) -> Self {
467 Self::executor_invariant(format!(
468 "set field must encode as Value::List: {entity_path} field={field_name}",
469 ))
470 }
471
472 pub(crate) fn mutation_set_field_not_canonical(entity_path: &str, field_name: &str) -> Self {
474 Self::executor_invariant(format!(
475 "set field must be strictly ordered and deduplicated: {entity_path} field={field_name}",
476 ))
477 }
478
479 pub(crate) fn mutation_map_field_map_required(entity_path: &str, field_name: &str) -> Self {
481 Self::executor_invariant(format!(
482 "map field must encode as Value::Map: {entity_path} field={field_name}",
483 ))
484 }
485
486 pub(crate) fn mutation_map_field_entries_invalid(
488 entity_path: &str,
489 field_name: &str,
490 detail: impl fmt::Display,
491 ) -> Self {
492 Self::executor_invariant(format!(
493 "map field entries violate map invariants: {entity_path} field={field_name} ({detail})",
494 ))
495 }
496
497 pub(crate) fn mutation_map_field_entries_not_canonical(
499 entity_path: &str,
500 field_name: &str,
501 ) -> Self {
502 Self::executor_invariant(format!(
503 "map field entries are not in canonical deterministic order: {entity_path} field={field_name}",
504 ))
505 }
506
507 pub(crate) fn scalar_page_ordering_after_filtering_required() -> Self {
509 Self::query_executor_invariant("ordering must run after filtering")
510 }
511
512 pub(crate) fn scalar_page_cursor_boundary_order_required() -> Self {
514 Self::query_executor_invariant("cursor boundary requires ordering")
515 }
516
517 pub(crate) fn scalar_page_cursor_boundary_after_ordering_required() -> Self {
519 Self::query_executor_invariant("cursor boundary must run after ordering")
520 }
521
522 pub(crate) fn scalar_page_pagination_after_ordering_required() -> Self {
524 Self::query_executor_invariant("pagination must run after ordering")
525 }
526
527 pub(crate) fn scalar_page_delete_limit_after_ordering_required() -> Self {
529 Self::query_executor_invariant("delete limit must run after ordering")
530 }
531
532 pub(crate) fn load_runtime_scalar_payload_required() -> Self {
534 Self::query_executor_invariant("scalar load mode must carry scalar runtime payload")
535 }
536
537 pub(crate) fn load_runtime_grouped_payload_required() -> Self {
539 Self::query_executor_invariant("grouped load mode must carry grouped runtime payload")
540 }
541
542 pub(crate) fn load_runtime_scalar_surface_payload_required() -> Self {
544 Self::query_executor_invariant("scalar page load mode must carry scalar runtime payload")
545 }
546
547 pub(crate) fn load_runtime_grouped_surface_payload_required() -> Self {
549 Self::query_executor_invariant("grouped page load mode must carry grouped runtime payload")
550 }
551
552 pub(crate) fn load_executor_load_plan_required() -> Self {
554 Self::query_executor_invariant("load executor requires load plans")
555 }
556
557 pub(crate) fn delete_executor_grouped_unsupported() -> Self {
559 Self::executor_unsupported("grouped query execution is not yet enabled in this release")
560 }
561
562 pub(crate) fn delete_executor_delete_plan_required() -> Self {
564 Self::query_executor_invariant("delete executor requires delete plans")
565 }
566
567 pub(crate) fn aggregate_fold_mode_terminal_contract_required() -> Self {
569 Self::query_executor_invariant(
570 "aggregate fold mode must match route fold-mode contract for aggregate terminal",
571 )
572 }
573
574 pub(crate) fn fast_stream_route_kind_request_match_required() -> Self {
576 Self::query_executor_invariant("fast-stream route kind/request mismatch")
577 }
578
579 pub(crate) fn secondary_index_prefix_spec_required() -> Self {
581 Self::query_executor_invariant(
582 "index-prefix executable spec must be materialized for index-prefix plans",
583 )
584 }
585
586 pub(crate) fn index_range_limit_spec_required() -> Self {
588 Self::query_executor_invariant(
589 "index-range executable spec must be materialized for index-range plans",
590 )
591 }
592
593 pub(crate) fn mutation_atomic_save_duplicate_key(
595 entity_path: &str,
596 key: impl fmt::Display,
597 ) -> Self {
598 Self::executor_unsupported(format!(
599 "atomic save batch rejected duplicate key: entity={entity_path} key={key}",
600 ))
601 }
602
603 pub(crate) fn mutation_index_store_generation_changed(
605 expected_generation: u64,
606 observed_generation: u64,
607 ) -> Self {
608 Self::executor_invariant(format!(
609 "index store generation changed between preflight and apply: expected {expected_generation}, found {observed_generation}",
610 ))
611 }
612
613 #[must_use]
615 #[cold]
616 #[inline(never)]
617 pub(crate) fn executor_invariant_message(reason: impl Into<String>) -> String {
618 format!("executor invariant violated: {}", reason.into())
619 }
620
621 #[cold]
623 #[inline(never)]
624 pub(crate) fn planner_invariant(message: impl Into<String>) -> Self {
625 Self::new(
626 ErrorClass::InvariantViolation,
627 ErrorOrigin::Planner,
628 message.into(),
629 )
630 }
631
632 #[must_use]
634 pub(crate) fn invalid_logical_plan_message(reason: impl Into<String>) -> String {
635 format!("invalid logical plan: {}", reason.into())
636 }
637
638 pub(crate) fn query_invalid_logical_plan(reason: impl Into<String>) -> Self {
640 Self::planner_invariant(Self::invalid_logical_plan_message(reason))
641 }
642
643 pub(crate) fn store_invariant(message: impl Into<String>) -> Self {
645 Self::new(
646 ErrorClass::InvariantViolation,
647 ErrorOrigin::Store,
648 message.into(),
649 )
650 }
651
652 pub(crate) fn duplicate_runtime_hooks_for_entity_tag(
654 entity_tag: crate::types::EntityTag,
655 ) -> Self {
656 Self::store_invariant(format!(
657 "duplicate runtime hooks for entity tag '{}'",
658 entity_tag.value()
659 ))
660 }
661
662 pub(crate) fn duplicate_runtime_hooks_for_entity_path(entity_path: &str) -> Self {
664 Self::store_invariant(format!(
665 "duplicate runtime hooks for entity path '{entity_path}'"
666 ))
667 }
668
669 #[cold]
671 #[inline(never)]
672 pub(crate) fn store_internal(message: impl Into<String>) -> Self {
673 Self::new(ErrorClass::Internal, ErrorOrigin::Store, message.into())
674 }
675
676 pub(crate) fn commit_memory_id_unconfigured() -> Self {
678 Self::store_internal(
679 "commit memory id is not configured; initialize recovery before commit store access",
680 )
681 }
682
683 pub(crate) fn commit_memory_id_mismatch(cached_id: u8, configured_id: u8) -> Self {
685 Self::store_internal(format!(
686 "commit memory id mismatch: cached={cached_id}, configured={configured_id}",
687 ))
688 }
689
690 pub(crate) fn delete_rollback_row_required() -> Self {
692 Self::store_internal("missing raw row for delete rollback")
693 }
694
695 pub(crate) fn commit_memory_registry_init_failed(err: impl fmt::Display) -> Self {
697 Self::store_internal(format!("memory registry init failed: {err}"))
698 }
699
700 pub(crate) fn recovery_integrity_validation_failed(
702 missing_index_entries: u64,
703 divergent_index_entries: u64,
704 orphan_index_references: u64,
705 ) -> Self {
706 Self::store_corruption(format!(
707 "recovery integrity validation failed: missing_index_entries={missing_index_entries} divergent_index_entries={divergent_index_entries} orphan_index_references={orphan_index_references}",
708 ))
709 }
710
711 #[cold]
713 #[inline(never)]
714 pub(crate) fn index_internal(message: impl Into<String>) -> Self {
715 Self::new(ErrorClass::Internal, ErrorOrigin::Index, message.into())
716 }
717
718 pub(crate) fn structural_index_removal_entity_key_required() -> Self {
720 Self::index_internal("missing old entity key for structural index removal")
721 }
722
723 pub(crate) fn structural_index_insertion_entity_key_required() -> Self {
725 Self::index_internal("missing new entity key for structural index insertion")
726 }
727
728 pub(crate) fn index_commit_op_old_entity_key_required() -> Self {
730 Self::index_internal("missing old entity key for index removal")
731 }
732
733 pub(crate) fn index_commit_op_new_entity_key_required() -> Self {
735 Self::index_internal("missing new entity key for index insertion")
736 }
737
738 #[cfg(test)]
740 pub(crate) fn query_internal(message: impl Into<String>) -> Self {
741 Self::new(ErrorClass::Internal, ErrorOrigin::Query, message.into())
742 }
743
744 #[cold]
746 #[inline(never)]
747 pub(crate) fn query_unsupported(message: impl Into<String>) -> Self {
748 Self::new(ErrorClass::Unsupported, ErrorOrigin::Query, message.into())
749 }
750
751 #[cold]
753 #[inline(never)]
754 pub(crate) fn query_numeric_overflow() -> Self {
755 Self {
756 class: ErrorClass::Unsupported,
757 origin: ErrorOrigin::Query,
758 message: "numeric overflow".to_string(),
759 detail: Some(ErrorDetail::Query(QueryErrorDetail::NumericOverflow)),
760 }
761 }
762
763 #[cold]
766 #[inline(never)]
767 pub(crate) fn query_numeric_not_representable() -> Self {
768 Self {
769 class: ErrorClass::Unsupported,
770 origin: ErrorOrigin::Query,
771 message: "numeric result is not representable".to_string(),
772 detail: Some(ErrorDetail::Query(
773 QueryErrorDetail::NumericNotRepresentable,
774 )),
775 }
776 }
777
778 #[cold]
780 #[inline(never)]
781 pub(crate) fn serialize_internal(message: impl Into<String>) -> Self {
782 Self::new(ErrorClass::Internal, ErrorOrigin::Serialize, message.into())
783 }
784
785 pub(crate) fn persisted_row_encode_failed(detail: impl fmt::Display) -> Self {
787 Self::serialize_internal(format!("row encode failed: {detail}"))
788 }
789
790 pub(crate) fn persisted_row_field_encode_failed(
792 field_name: &str,
793 detail: impl fmt::Display,
794 ) -> Self {
795 Self::serialize_internal(format!(
796 "row encode failed for field '{field_name}': {detail}",
797 ))
798 }
799
800 pub(crate) fn bytes_field_value_encode_failed(detail: impl fmt::Display) -> Self {
802 Self::serialize_internal(format!("bytes(field) value encode failed: {detail}"))
803 }
804
805 #[cold]
807 #[inline(never)]
808 pub(crate) fn store_corruption(message: impl Into<String>) -> Self {
809 Self::new(ErrorClass::Corruption, ErrorOrigin::Store, message.into())
810 }
811
812 pub(crate) fn multiple_commit_memory_ids_registered(ids: impl fmt::Debug) -> Self {
814 Self::store_corruption(format!(
815 "multiple commit marker memory ids registered: {ids:?}"
816 ))
817 }
818
819 pub(crate) fn commit_corruption(detail: impl fmt::Display) -> Self {
821 Self::store_corruption(format!("commit marker corrupted: {detail}"))
822 }
823
824 pub(crate) fn commit_component_corruption(component: &str, detail: impl fmt::Display) -> Self {
826 Self::store_corruption(format!("commit marker {component} corrupted: {detail}"))
827 }
828
829 pub(crate) fn commit_id_generation_failed(detail: impl fmt::Display) -> Self {
831 Self::store_internal(format!("commit id generation failed: {detail}"))
832 }
833
834 pub(crate) fn commit_marker_payload_exceeds_u32_length_limit(label: &str, len: usize) -> Self {
836 Self::store_unsupported(format!("{label} exceeds u32 length limit: {len} bytes"))
837 }
838
839 pub(crate) fn commit_component_length_invalid(
841 component: &str,
842 len: usize,
843 expected: impl fmt::Display,
844 ) -> Self {
845 Self::commit_component_corruption(
846 component,
847 format!("invalid length {len}, expected {expected}"),
848 )
849 }
850
851 pub(crate) fn commit_marker_exceeds_max_size(size: usize, max_size: u32) -> Self {
853 Self::commit_corruption(format!(
854 "commit marker exceeds max size: {size} bytes (limit {max_size})",
855 ))
856 }
857
858 #[cfg(test)]
860 pub(crate) fn commit_marker_exceeds_max_size_before_persist(
861 size: usize,
862 max_size: u32,
863 ) -> Self {
864 Self::store_unsupported(format!(
865 "commit marker exceeds max size: {size} bytes (limit {max_size})",
866 ))
867 }
868
869 pub(crate) fn commit_control_slot_exceeds_max_size(size: usize, max_size: u32) -> Self {
871 Self::store_unsupported(format!(
872 "commit control slot exceeds max size: {size} bytes (limit {max_size})",
873 ))
874 }
875
876 pub(crate) fn commit_control_slot_marker_bytes_exceed_u32_length_limit(size: usize) -> Self {
878 Self::store_unsupported(format!(
879 "commit marker bytes exceed u32 length limit: {size} bytes",
880 ))
881 }
882
883 pub(crate) fn startup_index_rebuild_invalid_data_key(
885 store_path: &str,
886 detail: impl fmt::Display,
887 ) -> Self {
888 Self::store_corruption(format!(
889 "startup index rebuild failed: invalid data key in store '{store_path}' ({detail})",
890 ))
891 }
892
893 #[cold]
895 #[inline(never)]
896 pub(crate) fn index_corruption(message: impl Into<String>) -> Self {
897 Self::new(ErrorClass::Corruption, ErrorOrigin::Index, message.into())
898 }
899
900 pub(crate) fn index_unique_validation_corruption(
902 entity_path: &str,
903 fields: &str,
904 detail: impl fmt::Display,
905 ) -> Self {
906 Self::index_plan_index_corruption(format!(
907 "index corrupted: {entity_path} ({fields}) -> {detail}",
908 ))
909 }
910
911 pub(crate) fn structural_index_entry_corruption(
913 entity_path: &str,
914 fields: &str,
915 detail: impl fmt::Display,
916 ) -> Self {
917 Self::index_plan_index_corruption(format!(
918 "index corrupted: {entity_path} ({fields}) -> {detail}",
919 ))
920 }
921
922 pub(crate) fn index_unique_validation_entity_key_required() -> Self {
924 Self::index_invariant("missing entity key during unique validation")
925 }
926
927 pub(crate) fn index_unique_validation_row_deserialize_failed(
929 data_key: impl fmt::Display,
930 source: impl fmt::Display,
931 ) -> Self {
932 Self::index_plan_serialize_corruption(format!(
933 "failed to structurally deserialize row: {data_key} ({source})"
934 ))
935 }
936
937 pub(crate) fn index_unique_validation_primary_key_decode_failed(
939 data_key: impl fmt::Display,
940 source: impl fmt::Display,
941 ) -> Self {
942 Self::index_plan_serialize_corruption(format!(
943 "failed to decode structural primary-key slot: {data_key} ({source})"
944 ))
945 }
946
947 pub(crate) fn index_unique_validation_key_rebuild_failed(
949 data_key: impl fmt::Display,
950 entity_path: &str,
951 source: impl fmt::Display,
952 ) -> Self {
953 Self::index_plan_serialize_corruption(format!(
954 "failed to structurally decode unique key row {data_key} for {entity_path}: {source}",
955 ))
956 }
957
958 pub(crate) fn index_unique_validation_row_required(data_key: impl fmt::Display) -> Self {
960 Self::index_plan_store_corruption(format!("missing row: {data_key}"))
961 }
962
963 pub(crate) fn index_only_predicate_component_required() -> Self {
965 Self::index_invariant("index-only predicate program referenced missing index component")
966 }
967
968 pub(crate) fn index_scan_continuation_anchor_within_envelope_required() -> Self {
970 Self::index_invariant(
971 "index-range continuation anchor is outside the requested range envelope",
972 )
973 }
974
975 pub(crate) fn index_scan_continuation_advancement_required() -> Self {
977 Self::index_invariant("index-range continuation scan did not advance beyond the anchor")
978 }
979
980 pub(crate) fn index_scan_key_corrupted_during(
982 context: &'static str,
983 err: impl fmt::Display,
984 ) -> Self {
985 Self::index_corruption(format!("index key corrupted during {context}: {err}"))
986 }
987
988 pub(crate) fn index_projection_component_required(
990 index_name: &str,
991 component_index: usize,
992 ) -> Self {
993 Self::index_invariant(format!(
994 "index projection referenced missing component: index='{index_name}' component_index={component_index}",
995 ))
996 }
997
998 pub(crate) fn unique_index_entry_single_key_required() -> Self {
1000 Self::index_corruption("unique index entry contains an unexpected number of keys")
1001 }
1002
1003 pub(crate) fn index_entry_decode_failed(err: impl fmt::Display) -> Self {
1005 Self::index_corruption(err.to_string())
1006 }
1007
1008 pub(crate) fn serialize_corruption(message: impl Into<String>) -> Self {
1010 Self::new(
1011 ErrorClass::Corruption,
1012 ErrorOrigin::Serialize,
1013 message.into(),
1014 )
1015 }
1016
1017 pub(crate) fn persisted_row_decode_failed(detail: impl fmt::Display) -> Self {
1019 Self::serialize_corruption(format!("row decode: {detail}"))
1020 }
1021
1022 pub(crate) fn persisted_row_field_decode_failed(
1024 field_name: &str,
1025 detail: impl fmt::Display,
1026 ) -> Self {
1027 Self::serialize_corruption(format!(
1028 "row decode failed for field '{field_name}': {detail}",
1029 ))
1030 }
1031
1032 pub(crate) fn persisted_row_field_kind_decode_failed(
1034 field_name: &str,
1035 field_kind: impl fmt::Debug,
1036 detail: impl fmt::Display,
1037 ) -> Self {
1038 Self::persisted_row_field_decode_failed(
1039 field_name,
1040 format!("kind={field_kind:?}: {detail}"),
1041 )
1042 }
1043
1044 pub(crate) fn persisted_row_field_payload_exact_len_required(
1046 field_name: &str,
1047 payload_kind: &str,
1048 expected_len: usize,
1049 ) -> Self {
1050 let unit = if expected_len == 1 { "byte" } else { "bytes" };
1051
1052 Self::persisted_row_field_decode_failed(
1053 field_name,
1054 format!("{payload_kind} payload must be exactly {expected_len} {unit}"),
1055 )
1056 }
1057
1058 pub(crate) fn persisted_row_field_payload_must_be_empty(
1060 field_name: &str,
1061 payload_kind: &str,
1062 ) -> Self {
1063 Self::persisted_row_field_decode_failed(
1064 field_name,
1065 format!("{payload_kind} payload must be empty"),
1066 )
1067 }
1068
1069 pub(crate) fn persisted_row_field_payload_invalid_byte(
1071 field_name: &str,
1072 payload_kind: &str,
1073 value: u8,
1074 ) -> Self {
1075 Self::persisted_row_field_decode_failed(
1076 field_name,
1077 format!("invalid {payload_kind} payload byte {value}"),
1078 )
1079 }
1080
1081 pub(crate) fn persisted_row_field_payload_non_finite(
1083 field_name: &str,
1084 payload_kind: &str,
1085 ) -> Self {
1086 Self::persisted_row_field_decode_failed(
1087 field_name,
1088 format!("{payload_kind} payload is non-finite"),
1089 )
1090 }
1091
1092 pub(crate) fn persisted_row_field_payload_out_of_range(
1094 field_name: &str,
1095 payload_kind: &str,
1096 ) -> Self {
1097 Self::persisted_row_field_decode_failed(
1098 field_name,
1099 format!("{payload_kind} payload out of range for target type"),
1100 )
1101 }
1102
1103 pub(crate) fn persisted_row_field_text_payload_invalid_utf8(
1105 field_name: &str,
1106 detail: impl fmt::Display,
1107 ) -> Self {
1108 Self::persisted_row_field_decode_failed(
1109 field_name,
1110 format!("invalid UTF-8 text payload ({detail})"),
1111 )
1112 }
1113
1114 pub(crate) fn persisted_row_slot_lookup_out_of_bounds(model_path: &str, slot: usize) -> Self {
1116 Self::index_invariant(format!(
1117 "slot lookup outside model bounds during structural row access: model='{model_path}' slot={slot}",
1118 ))
1119 }
1120
1121 pub(crate) fn persisted_row_slot_cache_lookup_out_of_bounds(
1123 model_path: &str,
1124 slot: usize,
1125 ) -> Self {
1126 Self::index_invariant(format!(
1127 "slot cache lookup outside model bounds during structural row access: model='{model_path}' slot={slot}",
1128 ))
1129 }
1130
1131 pub(crate) fn persisted_row_primary_key_not_storage_encodable(
1133 data_key: impl fmt::Debug,
1134 detail: impl fmt::Display,
1135 ) -> Self {
1136 Self::persisted_row_decode_failed(format!(
1137 "primary-key value is not storage-key encodable: {data_key:?} ({detail})",
1138 ))
1139 }
1140
1141 pub(crate) fn persisted_row_primary_key_slot_missing(data_key: impl fmt::Debug) -> Self {
1143 Self::persisted_row_decode_failed(format!(
1144 "missing primary-key slot while validating {data_key:?}",
1145 ))
1146 }
1147
1148 pub(crate) fn persisted_row_key_mismatch(
1150 expected_key: impl fmt::Debug,
1151 found_key: impl fmt::Debug,
1152 ) -> Self {
1153 Self::store_corruption(format!(
1154 "row key mismatch: expected {expected_key:?}, found {found_key:?}",
1155 ))
1156 }
1157
1158 pub(crate) fn persisted_row_declared_field_missing(field_name: &str) -> Self {
1160 Self::persisted_row_decode_failed(format!("missing declared field `{field_name}`"))
1161 }
1162
1163 pub(crate) fn data_key_entity_mismatch(
1165 expected: impl fmt::Display,
1166 found: impl fmt::Display,
1167 ) -> Self {
1168 Self::store_corruption(format!(
1169 "data key entity mismatch: expected {expected}, found {found}",
1170 ))
1171 }
1172
1173 pub(crate) fn reverse_index_ordinal_overflow(
1175 source_path: &str,
1176 field_name: &str,
1177 target_path: &str,
1178 detail: impl fmt::Display,
1179 ) -> Self {
1180 Self::index_internal(format!(
1181 "reverse index ordinal overflow: source={source_path} field={field_name} target={target_path} ({detail})",
1182 ))
1183 }
1184
1185 pub(crate) fn reverse_index_entry_corrupted(
1187 source_path: &str,
1188 field_name: &str,
1189 target_path: &str,
1190 index_key: impl fmt::Debug,
1191 detail: impl fmt::Display,
1192 ) -> Self {
1193 Self::index_corruption(format!(
1194 "reverse index entry corrupted: source={source_path} field={field_name} target={target_path} key={index_key:?} ({detail})",
1195 ))
1196 }
1197
1198 pub(crate) fn reverse_index_entry_encode_failed(
1200 source_path: &str,
1201 field_name: &str,
1202 target_path: &str,
1203 detail: impl fmt::Display,
1204 ) -> Self {
1205 Self::index_unsupported(format!(
1206 "reverse index entry encoding failed: source={source_path} field={field_name} target={target_path} ({detail})",
1207 ))
1208 }
1209
1210 pub(crate) fn relation_target_store_missing(
1212 source_path: &str,
1213 field_name: &str,
1214 target_path: &str,
1215 store_path: &str,
1216 detail: impl fmt::Display,
1217 ) -> Self {
1218 Self::executor_internal(format!(
1219 "relation target store missing: source={source_path} field={field_name} target={target_path} store={store_path} ({detail})",
1220 ))
1221 }
1222
1223 pub(crate) fn relation_target_key_decode_failed(
1225 context_label: &str,
1226 source_path: &str,
1227 field_name: &str,
1228 target_path: &str,
1229 detail: impl fmt::Display,
1230 ) -> Self {
1231 Self::identity_corruption(format!(
1232 "{context_label}: source={source_path} field={field_name} target={target_path} ({detail})",
1233 ))
1234 }
1235
1236 pub(crate) fn relation_target_entity_mismatch(
1238 context_label: &str,
1239 source_path: &str,
1240 field_name: &str,
1241 target_path: &str,
1242 target_entity_name: &str,
1243 expected_tag: impl fmt::Display,
1244 actual_tag: impl fmt::Display,
1245 ) -> Self {
1246 Self::store_corruption(format!(
1247 "{context_label}: source={source_path} field={field_name} target={target_path} expected={target_entity_name} (tag={expected_tag}) actual_tag={actual_tag}",
1248 ))
1249 }
1250
1251 pub(crate) fn relation_source_row_decode_failed(
1253 source_path: &str,
1254 field_name: &str,
1255 target_path: &str,
1256 detail: impl fmt::Display,
1257 ) -> Self {
1258 Self::serialize_corruption(format!(
1259 "relation source row decode: source={source_path} field={field_name} target={target_path} ({detail})",
1260 ))
1261 }
1262
1263 pub(crate) fn relation_source_row_unsupported_scalar_relation_key(
1265 source_path: &str,
1266 field_name: &str,
1267 target_path: &str,
1268 ) -> Self {
1269 Self::serialize_corruption(format!(
1270 "relation source row decode: unsupported scalar relation key: source={source_path} field={field_name} target={target_path}",
1271 ))
1272 }
1273
1274 pub(crate) fn relation_source_row_invalid_field_kind(field_kind: impl fmt::Debug) -> Self {
1276 Self::serialize_corruption(format!(
1277 "invalid strong relation field kind during structural decode: {field_kind:?}"
1278 ))
1279 }
1280
1281 pub(crate) fn relation_source_row_unsupported_key_kind(field_kind: impl fmt::Debug) -> Self {
1283 Self::serialize_corruption(format!(
1284 "unsupported strong relation key kind during structural decode: {field_kind:?}"
1285 ))
1286 }
1287
1288 pub(crate) fn reverse_index_relation_target_decode_invariant_violated(
1290 source_path: &str,
1291 field_name: &str,
1292 target_path: &str,
1293 ) -> Self {
1294 Self::executor_internal(format!(
1295 "relation target decode invariant violated while preparing reverse index: source={source_path} field={field_name} target={target_path}",
1296 ))
1297 }
1298
1299 pub(crate) fn bytes_covering_component_payload_empty() -> Self {
1301 Self::index_corruption("index component payload is empty during covering projection decode")
1302 }
1303
1304 pub(crate) fn bytes_covering_bool_payload_truncated() -> Self {
1306 Self::index_corruption("bool covering component payload is truncated")
1307 }
1308
1309 pub(crate) fn bytes_covering_component_payload_invalid_length(payload_kind: &str) -> Self {
1311 Self::index_corruption(format!(
1312 "{payload_kind} covering component payload has invalid length"
1313 ))
1314 }
1315
1316 pub(crate) fn bytes_covering_bool_payload_invalid_value() -> Self {
1318 Self::index_corruption("bool covering component payload has invalid value")
1319 }
1320
1321 pub(crate) fn bytes_covering_text_payload_invalid_terminator() -> Self {
1323 Self::index_corruption("text covering component payload has invalid terminator")
1324 }
1325
1326 pub(crate) fn bytes_covering_text_payload_trailing_bytes() -> Self {
1328 Self::index_corruption("text covering component payload contains trailing bytes")
1329 }
1330
1331 pub(crate) fn bytes_covering_text_payload_invalid_utf8() -> Self {
1333 Self::index_corruption("text covering component payload is not valid UTF-8")
1334 }
1335
1336 pub(crate) fn bytes_covering_text_payload_invalid_escape_byte() -> Self {
1338 Self::index_corruption("text covering component payload has invalid escape byte")
1339 }
1340
1341 pub(crate) fn bytes_covering_text_payload_missing_terminator() -> Self {
1343 Self::index_corruption("text covering component payload is missing terminator")
1344 }
1345
1346 #[must_use]
1348 pub fn missing_persisted_slot(field_name: &'static str) -> Self {
1349 Self::serialize_corruption(format!("row decode: missing required field '{field_name}'"))
1350 }
1351
1352 pub(crate) fn identity_corruption(message: impl Into<String>) -> Self {
1354 Self::new(
1355 ErrorClass::Corruption,
1356 ErrorOrigin::Identity,
1357 message.into(),
1358 )
1359 }
1360
1361 #[cold]
1363 #[inline(never)]
1364 pub(crate) fn store_unsupported(message: impl Into<String>) -> Self {
1365 Self::new(ErrorClass::Unsupported, ErrorOrigin::Store, message.into())
1366 }
1367
1368 pub(crate) fn unsupported_entity_tag_in_data_store(
1370 entity_tag: crate::types::EntityTag,
1371 ) -> Self {
1372 Self::store_unsupported(format!(
1373 "unsupported entity tag in data store: '{}'",
1374 entity_tag.value()
1375 ))
1376 }
1377
1378 pub(crate) fn configured_commit_memory_id_mismatch(
1380 configured_id: u8,
1381 registered_id: u8,
1382 ) -> Self {
1383 Self::store_unsupported(format!(
1384 "configured commit memory id {configured_id} does not match existing commit marker id {registered_id}",
1385 ))
1386 }
1387
1388 pub(crate) fn commit_memory_id_already_registered(memory_id: u8, label: &str) -> Self {
1390 Self::store_unsupported(format!(
1391 "configured commit memory id {memory_id} is already registered as '{label}'",
1392 ))
1393 }
1394
1395 pub(crate) fn commit_memory_id_outside_reserved_ranges(memory_id: u8) -> Self {
1397 Self::store_unsupported(format!(
1398 "configured commit memory id {memory_id} is outside reserved ranges",
1399 ))
1400 }
1401
1402 pub(crate) fn commit_memory_id_registration_failed(err: impl fmt::Display) -> Self {
1404 Self::store_internal(format!("commit memory id registration failed: {err}"))
1405 }
1406
1407 pub(crate) fn index_unsupported(message: impl Into<String>) -> Self {
1409 Self::new(ErrorClass::Unsupported, ErrorOrigin::Index, message.into())
1410 }
1411
1412 pub(crate) fn index_component_exceeds_max_size(
1414 key_item: impl fmt::Display,
1415 len: usize,
1416 max_component_size: usize,
1417 ) -> Self {
1418 Self::index_unsupported(format!(
1419 "index component exceeds max size: key item '{key_item}' -> {len} bytes (limit {max_component_size})",
1420 ))
1421 }
1422
1423 pub(crate) fn index_entry_exceeds_max_keys(
1425 entity_path: &str,
1426 fields: &str,
1427 keys: usize,
1428 ) -> Self {
1429 Self::index_unsupported(format!(
1430 "index entry exceeds max keys: {entity_path} ({fields}) -> {keys} keys",
1431 ))
1432 }
1433
1434 #[cfg(test)]
1436 pub(crate) fn index_entry_duplicate_keys_unexpected(entity_path: &str, fields: &str) -> Self {
1437 Self::index_invariant(format!(
1438 "index entry unexpectedly contains duplicate keys: {entity_path} ({fields})",
1439 ))
1440 }
1441
1442 pub(crate) fn index_entry_key_encoding_failed(
1444 entity_path: &str,
1445 fields: &str,
1446 err: impl fmt::Display,
1447 ) -> Self {
1448 Self::index_unsupported(format!(
1449 "index entry key encoding failed: {entity_path} ({fields}) -> {err}",
1450 ))
1451 }
1452
1453 pub(crate) fn serialize_unsupported(message: impl Into<String>) -> Self {
1455 Self::new(
1456 ErrorClass::Unsupported,
1457 ErrorOrigin::Serialize,
1458 message.into(),
1459 )
1460 }
1461
1462 pub(crate) fn cursor_unsupported(message: impl Into<String>) -> Self {
1464 Self::new(ErrorClass::Unsupported, ErrorOrigin::Cursor, message.into())
1465 }
1466
1467 pub(crate) fn serialize_incompatible_persisted_format(message: impl Into<String>) -> Self {
1469 Self::new(
1470 ErrorClass::IncompatiblePersistedFormat,
1471 ErrorOrigin::Serialize,
1472 message.into(),
1473 )
1474 }
1475
1476 #[cfg(feature = "sql")]
1479 pub(crate) fn query_unsupported_sql_feature(feature: &'static str) -> Self {
1480 let message = format!(
1481 "SQL query is not executable in this release: unsupported SQL feature: {feature}"
1482 );
1483
1484 Self {
1485 class: ErrorClass::Unsupported,
1486 origin: ErrorOrigin::Query,
1487 message,
1488 detail: Some(ErrorDetail::Query(
1489 QueryErrorDetail::UnsupportedSqlFeature { feature },
1490 )),
1491 }
1492 }
1493
1494 pub fn store_not_found(key: impl Into<String>) -> Self {
1495 let key = key.into();
1496
1497 Self {
1498 class: ErrorClass::NotFound,
1499 origin: ErrorOrigin::Store,
1500 message: format!("data key not found: {key}"),
1501 detail: Some(ErrorDetail::Store(StoreError::NotFound { key })),
1502 }
1503 }
1504
1505 pub fn unsupported_entity_path(path: impl Into<String>) -> Self {
1507 let path = path.into();
1508
1509 Self::new(
1510 ErrorClass::Unsupported,
1511 ErrorOrigin::Store,
1512 format!("unsupported entity path: '{path}'"),
1513 )
1514 }
1515
1516 #[must_use]
1517 pub const fn is_not_found(&self) -> bool {
1518 matches!(
1519 self.detail,
1520 Some(ErrorDetail::Store(StoreError::NotFound { .. }))
1521 )
1522 }
1523
1524 #[must_use]
1525 pub fn display_with_class(&self) -> String {
1526 format!("{}:{}: {}", self.origin, self.class, self.message)
1527 }
1528
1529 #[cold]
1531 #[inline(never)]
1532 pub(crate) fn index_plan_corruption(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1533 let message = message.into();
1534 Self::new(
1535 ErrorClass::Corruption,
1536 origin,
1537 format!("corruption detected ({origin}): {message}"),
1538 )
1539 }
1540
1541 #[cold]
1543 #[inline(never)]
1544 pub(crate) fn index_plan_index_corruption(message: impl Into<String>) -> Self {
1545 Self::index_plan_corruption(ErrorOrigin::Index, message)
1546 }
1547
1548 #[cold]
1550 #[inline(never)]
1551 pub(crate) fn index_plan_store_corruption(message: impl Into<String>) -> Self {
1552 Self::index_plan_corruption(ErrorOrigin::Store, message)
1553 }
1554
1555 #[cold]
1557 #[inline(never)]
1558 pub(crate) fn index_plan_serialize_corruption(message: impl Into<String>) -> Self {
1559 Self::index_plan_corruption(ErrorOrigin::Serialize, message)
1560 }
1561
1562 #[cfg(test)]
1564 pub(crate) fn index_plan_invariant(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1565 let message = message.into();
1566 Self::new(
1567 ErrorClass::InvariantViolation,
1568 origin,
1569 format!("invariant violation detected ({origin}): {message}"),
1570 )
1571 }
1572
1573 #[cfg(test)]
1575 pub(crate) fn index_plan_store_invariant(message: impl Into<String>) -> Self {
1576 Self::index_plan_invariant(ErrorOrigin::Store, message)
1577 }
1578
1579 pub(crate) fn index_violation(path: &str, index_fields: &[&str]) -> Self {
1581 Self::new(
1582 ErrorClass::Conflict,
1583 ErrorOrigin::Index,
1584 format!(
1585 "index constraint violation: {path} ({})",
1586 index_fields.join(", ")
1587 ),
1588 )
1589 }
1590}
1591
1592#[derive(Debug, ThisError)]
1600pub enum ErrorDetail {
1601 #[error("{0}")]
1602 Store(StoreError),
1603 #[error("{0}")]
1604 Query(QueryErrorDetail),
1605 }
1612
1613#[derive(Debug, ThisError)]
1621pub enum StoreError {
1622 #[error("key not found: {key}")]
1623 NotFound { key: String },
1624
1625 #[error("store corruption: {message}")]
1626 Corrupt { message: String },
1627
1628 #[error("store invariant violation: {message}")]
1629 InvariantViolation { message: String },
1630}
1631
1632#[derive(Debug, ThisError)]
1639pub enum QueryErrorDetail {
1640 #[error("numeric overflow")]
1641 NumericOverflow,
1642
1643 #[error("numeric result is not representable")]
1644 NumericNotRepresentable,
1645
1646 #[error("unsupported SQL feature: {feature}")]
1647 UnsupportedSqlFeature { feature: &'static str },
1648}
1649
1650#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1657pub enum ErrorClass {
1658 Corruption,
1659 IncompatiblePersistedFormat,
1660 NotFound,
1661 Internal,
1662 Conflict,
1663 Unsupported,
1664 InvariantViolation,
1665}
1666
1667impl fmt::Display for ErrorClass {
1668 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1669 let label = match self {
1670 Self::Corruption => "corruption",
1671 Self::IncompatiblePersistedFormat => "incompatible_persisted_format",
1672 Self::NotFound => "not_found",
1673 Self::Internal => "internal",
1674 Self::Conflict => "conflict",
1675 Self::Unsupported => "unsupported",
1676 Self::InvariantViolation => "invariant_violation",
1677 };
1678 write!(f, "{label}")
1679 }
1680}
1681
1682#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1689pub enum ErrorOrigin {
1690 Serialize,
1691 Store,
1692 Index,
1693 Identity,
1694 Query,
1695 Planner,
1696 Cursor,
1697 Recovery,
1698 Response,
1699 Executor,
1700 Interface,
1701}
1702
1703impl fmt::Display for ErrorOrigin {
1704 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1705 let label = match self {
1706 Self::Serialize => "serialize",
1707 Self::Store => "store",
1708 Self::Index => "index",
1709 Self::Identity => "identity",
1710 Self::Query => "query",
1711 Self::Planner => "planner",
1712 Self::Cursor => "cursor",
1713 Self::Recovery => "recovery",
1714 Self::Response => "response",
1715 Self::Executor => "executor",
1716 Self::Interface => "interface",
1717 };
1718 write!(f, "{label}")
1719 }
1720}