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 commit_memory_stable_key_mismatch(
692 cached_key: &str,
693 configured_key: &str,
694 ) -> Self {
695 Self::store_internal(format!(
696 "commit memory stable key mismatch: cached={cached_key}, configured={configured_key}",
697 ))
698 }
699
700 pub(crate) fn delete_rollback_row_required() -> Self {
702 Self::store_internal("missing raw row for delete rollback")
703 }
704
705 #[cfg_attr(test, allow(dead_code))]
707 pub(crate) fn commit_memory_registry_init_failed(err: impl fmt::Display) -> Self {
708 Self::store_internal(format!("memory registry init failed: {err}"))
709 }
710
711 pub(crate) fn recovery_integrity_validation_failed(
713 missing_index_entries: u64,
714 divergent_index_entries: u64,
715 orphan_index_references: u64,
716 ) -> Self {
717 Self::store_corruption(format!(
718 "recovery integrity validation failed: missing_index_entries={missing_index_entries} divergent_index_entries={divergent_index_entries} orphan_index_references={orphan_index_references}",
719 ))
720 }
721
722 #[cold]
724 #[inline(never)]
725 pub(crate) fn index_internal(message: impl Into<String>) -> Self {
726 Self::new(ErrorClass::Internal, ErrorOrigin::Index, message.into())
727 }
728
729 pub(crate) fn structural_index_removal_entity_key_required() -> Self {
731 Self::index_internal("missing old entity key for structural index removal")
732 }
733
734 pub(crate) fn structural_index_insertion_entity_key_required() -> Self {
736 Self::index_internal("missing new entity key for structural index insertion")
737 }
738
739 pub(crate) fn index_commit_op_old_entity_key_required() -> Self {
741 Self::index_internal("missing old entity key for index removal")
742 }
743
744 pub(crate) fn index_commit_op_new_entity_key_required() -> Self {
746 Self::index_internal("missing new entity key for index insertion")
747 }
748
749 #[cfg(test)]
751 pub(crate) fn query_internal(message: impl Into<String>) -> Self {
752 Self::new(ErrorClass::Internal, ErrorOrigin::Query, message.into())
753 }
754
755 #[cold]
757 #[inline(never)]
758 pub(crate) fn query_unsupported(message: impl Into<String>) -> Self {
759 Self::new(ErrorClass::Unsupported, ErrorOrigin::Query, message.into())
760 }
761
762 #[cold]
764 #[inline(never)]
765 pub(crate) fn query_numeric_overflow() -> Self {
766 Self {
767 class: ErrorClass::Unsupported,
768 origin: ErrorOrigin::Query,
769 message: "numeric overflow".to_string(),
770 detail: Some(ErrorDetail::Query(QueryErrorDetail::NumericOverflow)),
771 }
772 }
773
774 #[cold]
777 #[inline(never)]
778 pub(crate) fn query_numeric_not_representable() -> Self {
779 Self {
780 class: ErrorClass::Unsupported,
781 origin: ErrorOrigin::Query,
782 message: "numeric result is not representable".to_string(),
783 detail: Some(ErrorDetail::Query(
784 QueryErrorDetail::NumericNotRepresentable,
785 )),
786 }
787 }
788
789 #[cold]
791 #[inline(never)]
792 pub(crate) fn serialize_internal(message: impl Into<String>) -> Self {
793 Self::new(ErrorClass::Internal, ErrorOrigin::Serialize, message.into())
794 }
795
796 pub(crate) fn persisted_row_encode_failed(detail: impl fmt::Display) -> Self {
798 Self::serialize_internal(format!("row encode failed: {detail}"))
799 }
800
801 pub(crate) fn persisted_row_field_encode_failed(
803 field_name: &str,
804 detail: impl fmt::Display,
805 ) -> Self {
806 Self::serialize_internal(format!(
807 "row encode failed for field '{field_name}': {detail}",
808 ))
809 }
810
811 pub(crate) fn bytes_field_value_encode_failed(detail: impl fmt::Display) -> Self {
813 Self::serialize_internal(format!("bytes(field) value encode failed: {detail}"))
814 }
815
816 #[cold]
818 #[inline(never)]
819 pub(crate) fn store_corruption(message: impl Into<String>) -> Self {
820 Self::new(ErrorClass::Corruption, ErrorOrigin::Store, message.into())
821 }
822
823 #[cfg_attr(test, allow(dead_code))]
825 pub(crate) fn multiple_commit_memory_ids_registered(ids: impl fmt::Debug) -> Self {
826 Self::store_corruption(format!(
827 "multiple commit marker memory ids registered: {ids:?}"
828 ))
829 }
830
831 pub(crate) fn commit_corruption(detail: impl fmt::Display) -> Self {
833 Self::store_corruption(format!("commit marker corrupted: {detail}"))
834 }
835
836 pub(crate) fn commit_component_corruption(component: &str, detail: impl fmt::Display) -> Self {
838 Self::store_corruption(format!("commit marker {component} corrupted: {detail}"))
839 }
840
841 pub(crate) fn commit_id_generation_failed(detail: impl fmt::Display) -> Self {
843 Self::store_internal(format!("commit id generation failed: {detail}"))
844 }
845
846 pub(crate) fn commit_marker_payload_exceeds_u32_length_limit(label: &str, len: usize) -> Self {
848 Self::store_unsupported(format!("{label} exceeds u32 length limit: {len} bytes"))
849 }
850
851 pub(crate) fn commit_component_length_invalid(
853 component: &str,
854 len: usize,
855 expected: impl fmt::Display,
856 ) -> Self {
857 Self::commit_component_corruption(
858 component,
859 format!("invalid length {len}, expected {expected}"),
860 )
861 }
862
863 pub(crate) fn commit_marker_exceeds_max_size(size: usize, max_size: u32) -> Self {
865 Self::commit_corruption(format!(
866 "commit marker exceeds max size: {size} bytes (limit {max_size})",
867 ))
868 }
869
870 #[cfg(test)]
872 pub(crate) fn commit_marker_exceeds_max_size_before_persist(
873 size: usize,
874 max_size: u32,
875 ) -> Self {
876 Self::store_unsupported(format!(
877 "commit marker exceeds max size: {size} bytes (limit {max_size})",
878 ))
879 }
880
881 pub(crate) fn commit_control_slot_exceeds_max_size(size: usize, max_size: u32) -> Self {
883 Self::store_unsupported(format!(
884 "commit control slot exceeds max size: {size} bytes (limit {max_size})",
885 ))
886 }
887
888 pub(crate) fn commit_control_slot_marker_bytes_exceed_u32_length_limit(size: usize) -> Self {
890 Self::store_unsupported(format!(
891 "commit marker bytes exceed u32 length limit: {size} bytes",
892 ))
893 }
894
895 pub(crate) fn startup_index_rebuild_invalid_data_key(
897 store_path: &str,
898 detail: impl fmt::Display,
899 ) -> Self {
900 Self::store_corruption(format!(
901 "startup index rebuild failed: invalid data key in store '{store_path}' ({detail})",
902 ))
903 }
904
905 #[cold]
907 #[inline(never)]
908 pub(crate) fn index_corruption(message: impl Into<String>) -> Self {
909 Self::new(ErrorClass::Corruption, ErrorOrigin::Index, message.into())
910 }
911
912 pub(crate) fn index_unique_validation_corruption(
914 entity_path: &str,
915 fields: &str,
916 detail: impl fmt::Display,
917 ) -> Self {
918 Self::index_plan_index_corruption(format!(
919 "index corrupted: {entity_path} ({fields}) -> {detail}",
920 ))
921 }
922
923 pub(crate) fn structural_index_entry_corruption(
925 entity_path: &str,
926 fields: &str,
927 detail: impl fmt::Display,
928 ) -> Self {
929 Self::index_plan_index_corruption(format!(
930 "index corrupted: {entity_path} ({fields}) -> {detail}",
931 ))
932 }
933
934 pub(crate) fn index_unique_validation_entity_key_required() -> Self {
936 Self::index_invariant("missing entity key during unique validation")
937 }
938
939 pub(crate) fn index_unique_validation_row_deserialize_failed(
941 data_key: impl fmt::Display,
942 source: impl fmt::Display,
943 ) -> Self {
944 Self::index_plan_serialize_corruption(format!(
945 "failed to structurally deserialize row: {data_key} ({source})"
946 ))
947 }
948
949 pub(crate) fn index_unique_validation_primary_key_decode_failed(
951 data_key: impl fmt::Display,
952 source: impl fmt::Display,
953 ) -> Self {
954 Self::index_plan_serialize_corruption(format!(
955 "failed to decode structural primary-key slot: {data_key} ({source})"
956 ))
957 }
958
959 pub(crate) fn index_unique_validation_key_rebuild_failed(
961 data_key: impl fmt::Display,
962 entity_path: &str,
963 source: impl fmt::Display,
964 ) -> Self {
965 Self::index_plan_serialize_corruption(format!(
966 "failed to structurally decode unique key row {data_key} for {entity_path}: {source}",
967 ))
968 }
969
970 pub(crate) fn index_unique_validation_row_required(data_key: impl fmt::Display) -> Self {
972 Self::index_plan_store_corruption(format!("missing row: {data_key}"))
973 }
974
975 pub(crate) fn index_only_predicate_component_required() -> Self {
977 Self::index_invariant("index-only predicate program referenced missing index component")
978 }
979
980 pub(crate) fn index_scan_continuation_anchor_within_envelope_required() -> Self {
982 Self::index_invariant(
983 "index-range continuation anchor is outside the requested range envelope",
984 )
985 }
986
987 pub(crate) fn index_scan_continuation_advancement_required() -> Self {
989 Self::index_invariant("index-range continuation scan did not advance beyond the anchor")
990 }
991
992 pub(crate) fn index_scan_key_corrupted_during(
994 context: &'static str,
995 err: impl fmt::Display,
996 ) -> Self {
997 Self::index_corruption(format!("index key corrupted during {context}: {err}"))
998 }
999
1000 pub(crate) fn index_projection_component_required(
1002 index_name: &str,
1003 component_index: usize,
1004 ) -> Self {
1005 Self::index_invariant(format!(
1006 "index projection referenced missing component: index='{index_name}' component_index={component_index}",
1007 ))
1008 }
1009
1010 pub(crate) fn unique_index_entry_single_key_required() -> Self {
1012 Self::index_corruption("unique index entry contains an unexpected number of keys")
1013 }
1014
1015 pub(crate) fn index_entry_decode_failed(err: impl fmt::Display) -> Self {
1017 Self::index_corruption(err.to_string())
1018 }
1019
1020 pub(crate) fn serialize_corruption(message: impl Into<String>) -> Self {
1022 Self::new(
1023 ErrorClass::Corruption,
1024 ErrorOrigin::Serialize,
1025 message.into(),
1026 )
1027 }
1028
1029 pub(crate) fn persisted_row_decode_failed(detail: impl fmt::Display) -> Self {
1031 Self::serialize_corruption(format!("row decode: {detail}"))
1032 }
1033
1034 pub(crate) fn persisted_row_field_decode_failed(
1036 field_name: &str,
1037 detail: impl fmt::Display,
1038 ) -> Self {
1039 Self::serialize_corruption(format!(
1040 "row decode failed for field '{field_name}': {detail}",
1041 ))
1042 }
1043
1044 pub(crate) fn persisted_row_field_kind_decode_failed(
1046 field_name: &str,
1047 field_kind: impl fmt::Debug,
1048 detail: impl fmt::Display,
1049 ) -> Self {
1050 Self::persisted_row_field_decode_failed(
1051 field_name,
1052 format!("kind={field_kind:?}: {detail}"),
1053 )
1054 }
1055
1056 pub(crate) fn persisted_row_field_payload_exact_len_required(
1058 field_name: &str,
1059 payload_kind: &str,
1060 expected_len: usize,
1061 ) -> Self {
1062 let unit = if expected_len == 1 { "byte" } else { "bytes" };
1063
1064 Self::persisted_row_field_decode_failed(
1065 field_name,
1066 format!("{payload_kind} payload must be exactly {expected_len} {unit}"),
1067 )
1068 }
1069
1070 pub(crate) fn persisted_row_field_payload_must_be_empty(
1072 field_name: &str,
1073 payload_kind: &str,
1074 ) -> Self {
1075 Self::persisted_row_field_decode_failed(
1076 field_name,
1077 format!("{payload_kind} payload must be empty"),
1078 )
1079 }
1080
1081 pub(crate) fn persisted_row_field_payload_invalid_byte(
1083 field_name: &str,
1084 payload_kind: &str,
1085 value: u8,
1086 ) -> Self {
1087 Self::persisted_row_field_decode_failed(
1088 field_name,
1089 format!("invalid {payload_kind} payload byte {value}"),
1090 )
1091 }
1092
1093 pub(crate) fn persisted_row_field_payload_non_finite(
1095 field_name: &str,
1096 payload_kind: &str,
1097 ) -> Self {
1098 Self::persisted_row_field_decode_failed(
1099 field_name,
1100 format!("{payload_kind} payload is non-finite"),
1101 )
1102 }
1103
1104 pub(crate) fn persisted_row_field_payload_out_of_range(
1106 field_name: &str,
1107 payload_kind: &str,
1108 ) -> Self {
1109 Self::persisted_row_field_decode_failed(
1110 field_name,
1111 format!("{payload_kind} payload out of range for target type"),
1112 )
1113 }
1114
1115 pub(crate) fn persisted_row_field_text_payload_invalid_utf8(
1117 field_name: &str,
1118 detail: impl fmt::Display,
1119 ) -> Self {
1120 Self::persisted_row_field_decode_failed(
1121 field_name,
1122 format!("invalid UTF-8 text payload ({detail})"),
1123 )
1124 }
1125
1126 pub(crate) fn persisted_row_slot_lookup_out_of_bounds(model_path: &str, slot: usize) -> Self {
1128 Self::index_invariant(format!(
1129 "slot lookup outside model bounds during structural row access: model='{model_path}' slot={slot}",
1130 ))
1131 }
1132
1133 pub(crate) fn persisted_row_slot_cache_lookup_out_of_bounds(
1135 model_path: &str,
1136 slot: usize,
1137 ) -> Self {
1138 Self::index_invariant(format!(
1139 "slot cache lookup outside model bounds during structural row access: model='{model_path}' slot={slot}",
1140 ))
1141 }
1142
1143 pub(crate) fn persisted_row_primary_key_not_storage_encodable(
1145 data_key: impl fmt::Debug,
1146 detail: impl fmt::Display,
1147 ) -> Self {
1148 Self::persisted_row_decode_failed(format!(
1149 "primary-key value is not storage-key encodable: {data_key:?} ({detail})",
1150 ))
1151 }
1152
1153 pub(crate) fn persisted_row_primary_key_slot_missing(data_key: impl fmt::Debug) -> Self {
1155 Self::persisted_row_decode_failed(format!(
1156 "missing primary-key slot while validating {data_key:?}",
1157 ))
1158 }
1159
1160 pub(crate) fn persisted_row_key_mismatch(
1162 expected_key: impl fmt::Debug,
1163 found_key: impl fmt::Debug,
1164 ) -> Self {
1165 Self::store_corruption(format!(
1166 "row key mismatch: expected {expected_key:?}, found {found_key:?}",
1167 ))
1168 }
1169
1170 pub(crate) fn persisted_row_declared_field_missing(field_name: &str) -> Self {
1172 Self::persisted_row_decode_failed(format!("missing declared field `{field_name}`"))
1173 }
1174
1175 pub(crate) fn data_key_entity_mismatch(
1177 expected: impl fmt::Display,
1178 found: impl fmt::Display,
1179 ) -> Self {
1180 Self::store_corruption(format!(
1181 "data key entity mismatch: expected {expected}, found {found}",
1182 ))
1183 }
1184
1185 pub(crate) fn reverse_index_ordinal_overflow(
1187 source_path: &str,
1188 field_name: &str,
1189 target_path: &str,
1190 detail: impl fmt::Display,
1191 ) -> Self {
1192 Self::index_internal(format!(
1193 "reverse index ordinal overflow: source={source_path} field={field_name} target={target_path} ({detail})",
1194 ))
1195 }
1196
1197 pub(crate) fn reverse_index_entry_corrupted(
1199 source_path: &str,
1200 field_name: &str,
1201 target_path: &str,
1202 index_key: impl fmt::Debug,
1203 detail: impl fmt::Display,
1204 ) -> Self {
1205 Self::index_corruption(format!(
1206 "reverse index entry corrupted: source={source_path} field={field_name} target={target_path} key={index_key:?} ({detail})",
1207 ))
1208 }
1209
1210 pub(crate) fn reverse_index_entry_encode_failed(
1212 source_path: &str,
1213 field_name: &str,
1214 target_path: &str,
1215 detail: impl fmt::Display,
1216 ) -> Self {
1217 Self::index_unsupported(format!(
1218 "reverse index entry encoding failed: source={source_path} field={field_name} target={target_path} ({detail})",
1219 ))
1220 }
1221
1222 pub(crate) fn relation_target_store_missing(
1224 source_path: &str,
1225 field_name: &str,
1226 target_path: &str,
1227 store_path: &str,
1228 detail: impl fmt::Display,
1229 ) -> Self {
1230 Self::executor_internal(format!(
1231 "relation target store missing: source={source_path} field={field_name} target={target_path} store={store_path} ({detail})",
1232 ))
1233 }
1234
1235 pub(crate) fn relation_target_key_decode_failed(
1237 context_label: &str,
1238 source_path: &str,
1239 field_name: &str,
1240 target_path: &str,
1241 detail: impl fmt::Display,
1242 ) -> Self {
1243 Self::identity_corruption(format!(
1244 "{context_label}: source={source_path} field={field_name} target={target_path} ({detail})",
1245 ))
1246 }
1247
1248 pub(crate) fn relation_target_entity_mismatch(
1250 context_label: &str,
1251 source_path: &str,
1252 field_name: &str,
1253 target_path: &str,
1254 target_entity_name: &str,
1255 expected_tag: impl fmt::Display,
1256 actual_tag: impl fmt::Display,
1257 ) -> Self {
1258 Self::store_corruption(format!(
1259 "{context_label}: source={source_path} field={field_name} target={target_path} expected={target_entity_name} (tag={expected_tag}) actual_tag={actual_tag}",
1260 ))
1261 }
1262
1263 pub(crate) fn relation_source_row_decode_failed(
1265 source_path: &str,
1266 field_name: &str,
1267 target_path: &str,
1268 detail: impl fmt::Display,
1269 ) -> Self {
1270 Self::serialize_corruption(format!(
1271 "relation source row decode: source={source_path} field={field_name} target={target_path} ({detail})",
1272 ))
1273 }
1274
1275 pub(crate) fn relation_source_row_unsupported_scalar_relation_key(
1277 source_path: &str,
1278 field_name: &str,
1279 target_path: &str,
1280 ) -> Self {
1281 Self::serialize_corruption(format!(
1282 "relation source row decode: unsupported scalar relation key: source={source_path} field={field_name} target={target_path}",
1283 ))
1284 }
1285
1286 pub(crate) fn relation_source_row_invalid_field_kind(field_kind: impl fmt::Debug) -> Self {
1288 Self::serialize_corruption(format!(
1289 "invalid strong relation field kind during structural decode: {field_kind:?}"
1290 ))
1291 }
1292
1293 pub(crate) fn relation_source_row_unsupported_key_kind(field_kind: impl fmt::Debug) -> Self {
1295 Self::serialize_corruption(format!(
1296 "unsupported strong relation key kind during structural decode: {field_kind:?}"
1297 ))
1298 }
1299
1300 pub(crate) fn reverse_index_relation_target_decode_invariant_violated(
1302 source_path: &str,
1303 field_name: &str,
1304 target_path: &str,
1305 ) -> Self {
1306 Self::executor_internal(format!(
1307 "relation target decode invariant violated while preparing reverse index: source={source_path} field={field_name} target={target_path}",
1308 ))
1309 }
1310
1311 pub(crate) fn bytes_covering_component_payload_empty() -> Self {
1313 Self::index_corruption("index component payload is empty during covering projection decode")
1314 }
1315
1316 pub(crate) fn bytes_covering_bool_payload_truncated() -> Self {
1318 Self::index_corruption("bool covering component payload is truncated")
1319 }
1320
1321 pub(crate) fn bytes_covering_component_payload_invalid_length(payload_kind: &str) -> Self {
1323 Self::index_corruption(format!(
1324 "{payload_kind} covering component payload has invalid length"
1325 ))
1326 }
1327
1328 pub(crate) fn bytes_covering_bool_payload_invalid_value() -> Self {
1330 Self::index_corruption("bool covering component payload has invalid value")
1331 }
1332
1333 pub(crate) fn bytes_covering_text_payload_invalid_terminator() -> Self {
1335 Self::index_corruption("text covering component payload has invalid terminator")
1336 }
1337
1338 pub(crate) fn bytes_covering_text_payload_trailing_bytes() -> Self {
1340 Self::index_corruption("text covering component payload contains trailing bytes")
1341 }
1342
1343 pub(crate) fn bytes_covering_text_payload_invalid_utf8() -> Self {
1345 Self::index_corruption("text covering component payload is not valid UTF-8")
1346 }
1347
1348 pub(crate) fn bytes_covering_text_payload_invalid_escape_byte() -> Self {
1350 Self::index_corruption("text covering component payload has invalid escape byte")
1351 }
1352
1353 pub(crate) fn bytes_covering_text_payload_missing_terminator() -> Self {
1355 Self::index_corruption("text covering component payload is missing terminator")
1356 }
1357
1358 #[must_use]
1360 pub fn missing_persisted_slot(field_name: &'static str) -> Self {
1361 Self::serialize_corruption(format!("row decode: missing required field '{field_name}'"))
1362 }
1363
1364 pub(crate) fn identity_corruption(message: impl Into<String>) -> Self {
1366 Self::new(
1367 ErrorClass::Corruption,
1368 ErrorOrigin::Identity,
1369 message.into(),
1370 )
1371 }
1372
1373 #[cold]
1375 #[inline(never)]
1376 pub(crate) fn store_unsupported(message: impl Into<String>) -> Self {
1377 Self::new(ErrorClass::Unsupported, ErrorOrigin::Store, message.into())
1378 }
1379
1380 pub(crate) fn unsupported_entity_tag_in_data_store(
1382 entity_tag: crate::types::EntityTag,
1383 ) -> Self {
1384 Self::store_unsupported(format!(
1385 "unsupported entity tag in data store: '{}'",
1386 entity_tag.value()
1387 ))
1388 }
1389
1390 #[cfg_attr(test, allow(dead_code))]
1392 pub(crate) fn configured_commit_memory_id_mismatch(
1393 configured_id: u8,
1394 registered_id: u8,
1395 ) -> Self {
1396 Self::store_unsupported(format!(
1397 "configured commit memory id {configured_id} does not match existing commit marker id {registered_id}",
1398 ))
1399 }
1400
1401 #[cfg_attr(test, allow(dead_code))]
1403 pub(crate) fn commit_memory_stable_key_unregistered(memory_id: u8, stable_key: &str) -> Self {
1404 Self::store_unsupported(format!(
1405 "configured commit memory id {memory_id} is not declared with stable key '{stable_key}'",
1406 ))
1407 }
1408
1409 pub(crate) fn commit_memory_id_outside_reserved_ranges(memory_id: u8) -> Self {
1411 Self::store_unsupported(format!(
1412 "configured commit memory id {memory_id} is outside reserved ranges",
1413 ))
1414 }
1415
1416 #[cfg_attr(test, allow(dead_code))]
1418 pub(crate) fn commit_memory_id_registration_failed(err: impl fmt::Display) -> Self {
1419 Self::store_internal(format!("commit memory id registration failed: {err}"))
1420 }
1421
1422 pub(crate) fn index_unsupported(message: impl Into<String>) -> Self {
1424 Self::new(ErrorClass::Unsupported, ErrorOrigin::Index, message.into())
1425 }
1426
1427 pub(crate) fn index_component_exceeds_max_size(
1429 key_item: impl fmt::Display,
1430 len: usize,
1431 max_component_size: usize,
1432 ) -> Self {
1433 Self::index_unsupported(format!(
1434 "index component exceeds max size: key item '{key_item}' -> {len} bytes (limit {max_component_size})",
1435 ))
1436 }
1437
1438 pub(crate) fn index_entry_exceeds_max_keys(
1440 entity_path: &str,
1441 fields: &str,
1442 keys: usize,
1443 ) -> Self {
1444 Self::index_unsupported(format!(
1445 "index entry exceeds max keys: {entity_path} ({fields}) -> {keys} keys",
1446 ))
1447 }
1448
1449 #[cfg(test)]
1451 pub(crate) fn index_entry_duplicate_keys_unexpected(entity_path: &str, fields: &str) -> Self {
1452 Self::index_invariant(format!(
1453 "index entry unexpectedly contains duplicate keys: {entity_path} ({fields})",
1454 ))
1455 }
1456
1457 pub(crate) fn index_entry_key_encoding_failed(
1459 entity_path: &str,
1460 fields: &str,
1461 err: impl fmt::Display,
1462 ) -> Self {
1463 Self::index_unsupported(format!(
1464 "index entry key encoding failed: {entity_path} ({fields}) -> {err}",
1465 ))
1466 }
1467
1468 pub(crate) fn serialize_unsupported(message: impl Into<String>) -> Self {
1470 Self::new(
1471 ErrorClass::Unsupported,
1472 ErrorOrigin::Serialize,
1473 message.into(),
1474 )
1475 }
1476
1477 pub(crate) fn cursor_unsupported(message: impl Into<String>) -> Self {
1479 Self::new(ErrorClass::Unsupported, ErrorOrigin::Cursor, message.into())
1480 }
1481
1482 pub(crate) fn serialize_incompatible_persisted_format(message: impl Into<String>) -> Self {
1484 Self::new(
1485 ErrorClass::IncompatiblePersistedFormat,
1486 ErrorOrigin::Serialize,
1487 message.into(),
1488 )
1489 }
1490
1491 #[cfg(feature = "sql")]
1494 pub(crate) fn query_unsupported_sql_feature(feature: &'static str) -> Self {
1495 let message = format!(
1496 "SQL query is not executable in this release: unsupported SQL feature: {feature}"
1497 );
1498
1499 Self {
1500 class: ErrorClass::Unsupported,
1501 origin: ErrorOrigin::Query,
1502 message,
1503 detail: Some(ErrorDetail::Query(
1504 QueryErrorDetail::UnsupportedSqlFeature { feature },
1505 )),
1506 }
1507 }
1508
1509 pub fn store_not_found(key: impl Into<String>) -> Self {
1510 let key = key.into();
1511
1512 Self {
1513 class: ErrorClass::NotFound,
1514 origin: ErrorOrigin::Store,
1515 message: format!("data key not found: {key}"),
1516 detail: Some(ErrorDetail::Store(StoreError::NotFound { key })),
1517 }
1518 }
1519
1520 pub fn unsupported_entity_path(path: impl Into<String>) -> Self {
1522 let path = path.into();
1523
1524 Self::new(
1525 ErrorClass::Unsupported,
1526 ErrorOrigin::Store,
1527 format!("unsupported entity path: '{path}'"),
1528 )
1529 }
1530
1531 #[must_use]
1532 pub const fn is_not_found(&self) -> bool {
1533 matches!(
1534 self.detail,
1535 Some(ErrorDetail::Store(StoreError::NotFound { .. }))
1536 )
1537 }
1538
1539 #[must_use]
1540 pub fn display_with_class(&self) -> String {
1541 format!("{}:{}: {}", self.origin, self.class, self.message)
1542 }
1543
1544 #[cold]
1546 #[inline(never)]
1547 pub(crate) fn index_plan_corruption(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1548 let message = message.into();
1549 Self::new(
1550 ErrorClass::Corruption,
1551 origin,
1552 format!("corruption detected ({origin}): {message}"),
1553 )
1554 }
1555
1556 #[cold]
1558 #[inline(never)]
1559 pub(crate) fn index_plan_index_corruption(message: impl Into<String>) -> Self {
1560 Self::index_plan_corruption(ErrorOrigin::Index, message)
1561 }
1562
1563 #[cold]
1565 #[inline(never)]
1566 pub(crate) fn index_plan_store_corruption(message: impl Into<String>) -> Self {
1567 Self::index_plan_corruption(ErrorOrigin::Store, message)
1568 }
1569
1570 #[cold]
1572 #[inline(never)]
1573 pub(crate) fn index_plan_serialize_corruption(message: impl Into<String>) -> Self {
1574 Self::index_plan_corruption(ErrorOrigin::Serialize, message)
1575 }
1576
1577 #[cfg(test)]
1579 pub(crate) fn index_plan_invariant(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1580 let message = message.into();
1581 Self::new(
1582 ErrorClass::InvariantViolation,
1583 origin,
1584 format!("invariant violation detected ({origin}): {message}"),
1585 )
1586 }
1587
1588 #[cfg(test)]
1590 pub(crate) fn index_plan_store_invariant(message: impl Into<String>) -> Self {
1591 Self::index_plan_invariant(ErrorOrigin::Store, message)
1592 }
1593
1594 pub(crate) fn index_violation(path: &str, index_fields: &[&str]) -> Self {
1596 Self::new(
1597 ErrorClass::Conflict,
1598 ErrorOrigin::Index,
1599 format!(
1600 "index constraint violation: {path} ({})",
1601 index_fields.join(", ")
1602 ),
1603 )
1604 }
1605}
1606
1607#[derive(Debug, ThisError)]
1615pub enum ErrorDetail {
1616 #[error("{0}")]
1617 Store(StoreError),
1618 #[error("{0}")]
1619 Query(QueryErrorDetail),
1620 }
1627
1628#[derive(Debug, ThisError)]
1636pub enum StoreError {
1637 #[error("key not found: {key}")]
1638 NotFound { key: String },
1639
1640 #[error("store corruption: {message}")]
1641 Corrupt { message: String },
1642
1643 #[error("store invariant violation: {message}")]
1644 InvariantViolation { message: String },
1645}
1646
1647#[derive(Debug, ThisError)]
1654pub enum QueryErrorDetail {
1655 #[error("numeric overflow")]
1656 NumericOverflow,
1657
1658 #[error("numeric result is not representable")]
1659 NumericNotRepresentable,
1660
1661 #[error("unsupported SQL feature: {feature}")]
1662 UnsupportedSqlFeature { feature: &'static str },
1663}
1664
1665#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1672pub enum ErrorClass {
1673 Corruption,
1674 IncompatiblePersistedFormat,
1675 NotFound,
1676 Internal,
1677 Conflict,
1678 Unsupported,
1679 InvariantViolation,
1680}
1681
1682impl fmt::Display for ErrorClass {
1683 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1684 let label = match self {
1685 Self::Corruption => "corruption",
1686 Self::IncompatiblePersistedFormat => "incompatible_persisted_format",
1687 Self::NotFound => "not_found",
1688 Self::Internal => "internal",
1689 Self::Conflict => "conflict",
1690 Self::Unsupported => "unsupported",
1691 Self::InvariantViolation => "invariant_violation",
1692 };
1693 write!(f, "{label}")
1694 }
1695}
1696
1697#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1704pub enum ErrorOrigin {
1705 Serialize,
1706 Store,
1707 Index,
1708 Identity,
1709 Query,
1710 Planner,
1711 Cursor,
1712 Recovery,
1713 Response,
1714 Executor,
1715 Interface,
1716}
1717
1718impl fmt::Display for ErrorOrigin {
1719 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1720 let label = match self {
1721 Self::Serialize => "serialize",
1722 Self::Store => "store",
1723 Self::Index => "index",
1724 Self::Identity => "identity",
1725 Self::Query => "query",
1726 Self::Planner => "planner",
1727 Self::Cursor => "cursor",
1728 Self::Recovery => "recovery",
1729 Self::Response => "response",
1730 Self::Executor => "executor",
1731 Self::Interface => "interface",
1732 };
1733 write!(f, "{label}")
1734 }
1735}