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 #[must_use]
411 pub fn mutation_create_missing_authored_fields(entity_path: &str, field_names: &str) -> Self {
412 Self::executor_unsupported(format!(
413 "create requires explicit values for authorable fields {field_names}: {entity_path}",
414 ))
415 }
416
417 pub(crate) fn mutation_structural_after_image_invalid(
422 entity_path: &str,
423 data_key: impl fmt::Display,
424 detail: impl AsRef<str>,
425 ) -> Self {
426 Self::executor_invariant(format!(
427 "mutation result is invalid: {entity_path} key={data_key} ({})",
428 detail.as_ref(),
429 ))
430 }
431
432 pub(crate) fn mutation_structural_field_unknown(entity_path: &str, field_name: &str) -> Self {
434 Self::executor_invariant(format!(
435 "mutation field not found: {entity_path} field={field_name}",
436 ))
437 }
438
439 pub(crate) fn mutation_decimal_scale_mismatch(
441 entity_path: &str,
442 field_name: &str,
443 expected_scale: impl fmt::Display,
444 actual_scale: impl fmt::Display,
445 ) -> Self {
446 Self::executor_unsupported(format!(
447 "decimal field scale mismatch: {entity_path} field={field_name} expected_scale={expected_scale} actual_scale={actual_scale}",
448 ))
449 }
450
451 pub(crate) fn mutation_text_max_len_exceeded(
453 entity_path: &str,
454 field_name: &str,
455 max_len: impl fmt::Display,
456 actual_len: impl fmt::Display,
457 ) -> Self {
458 Self::executor_unsupported(format!(
459 "text length exceeds max_len: {entity_path} field={field_name} max_len={max_len} actual_len={actual_len}",
460 ))
461 }
462
463 pub(crate) fn mutation_set_field_list_required(entity_path: &str, field_name: &str) -> Self {
465 Self::executor_invariant(format!(
466 "set field must encode as Value::List: {entity_path} field={field_name}",
467 ))
468 }
469
470 pub(crate) fn mutation_set_field_not_canonical(entity_path: &str, field_name: &str) -> Self {
472 Self::executor_invariant(format!(
473 "set field must be strictly ordered and deduplicated: {entity_path} field={field_name}",
474 ))
475 }
476
477 pub(crate) fn mutation_map_field_map_required(entity_path: &str, field_name: &str) -> Self {
479 Self::executor_invariant(format!(
480 "map field must encode as Value::Map: {entity_path} field={field_name}",
481 ))
482 }
483
484 pub(crate) fn mutation_map_field_entries_invalid(
486 entity_path: &str,
487 field_name: &str,
488 detail: impl fmt::Display,
489 ) -> Self {
490 Self::executor_invariant(format!(
491 "map field entries violate map invariants: {entity_path} field={field_name} ({detail})",
492 ))
493 }
494
495 pub(crate) fn mutation_map_field_entries_not_canonical(
497 entity_path: &str,
498 field_name: &str,
499 ) -> Self {
500 Self::executor_invariant(format!(
501 "map field entries are not in canonical deterministic order: {entity_path} field={field_name}",
502 ))
503 }
504
505 pub(crate) fn scalar_page_ordering_after_filtering_required() -> Self {
507 Self::query_executor_invariant("ordering must run after filtering")
508 }
509
510 pub(crate) fn scalar_page_cursor_boundary_order_required() -> Self {
512 Self::query_executor_invariant("cursor boundary requires ordering")
513 }
514
515 pub(crate) fn scalar_page_cursor_boundary_after_ordering_required() -> Self {
517 Self::query_executor_invariant("cursor boundary must run after ordering")
518 }
519
520 pub(crate) fn scalar_page_pagination_after_ordering_required() -> Self {
522 Self::query_executor_invariant("pagination must run after ordering")
523 }
524
525 pub(crate) fn scalar_page_delete_limit_after_ordering_required() -> Self {
527 Self::query_executor_invariant("delete limit must run after ordering")
528 }
529
530 pub(crate) fn load_runtime_scalar_payload_required() -> Self {
532 Self::query_executor_invariant("scalar load mode must carry scalar runtime payload")
533 }
534
535 pub(crate) fn load_runtime_grouped_payload_required() -> Self {
537 Self::query_executor_invariant("grouped load mode must carry grouped runtime payload")
538 }
539
540 pub(crate) fn load_runtime_scalar_surface_payload_required() -> Self {
542 Self::query_executor_invariant("scalar page load mode must carry scalar runtime payload")
543 }
544
545 pub(crate) fn load_runtime_grouped_surface_payload_required() -> Self {
547 Self::query_executor_invariant("grouped page load mode must carry grouped runtime payload")
548 }
549
550 pub(crate) fn load_executor_load_plan_required() -> Self {
552 Self::query_executor_invariant("load executor requires load plans")
553 }
554
555 pub(crate) fn delete_executor_grouped_unsupported() -> Self {
557 Self::executor_unsupported("grouped query execution is not yet enabled in this release")
558 }
559
560 pub(crate) fn delete_executor_delete_plan_required() -> Self {
562 Self::query_executor_invariant("delete executor requires delete plans")
563 }
564
565 pub(crate) fn aggregate_fold_mode_terminal_contract_required() -> Self {
567 Self::query_executor_invariant(
568 "aggregate fold mode must match route fold-mode contract for aggregate terminal",
569 )
570 }
571
572 pub(crate) fn fast_stream_route_kind_request_match_required() -> Self {
574 Self::query_executor_invariant("fast-stream route kind/request mismatch")
575 }
576
577 pub(crate) fn secondary_index_prefix_spec_required() -> Self {
579 Self::query_executor_invariant(
580 "index-prefix executable spec must be materialized for index-prefix plans",
581 )
582 }
583
584 pub(crate) fn index_range_limit_spec_required() -> Self {
586 Self::query_executor_invariant(
587 "index-range executable spec must be materialized for index-range plans",
588 )
589 }
590
591 pub(crate) fn mutation_atomic_save_duplicate_key(
593 entity_path: &str,
594 key: impl fmt::Display,
595 ) -> Self {
596 Self::executor_unsupported(format!(
597 "atomic save batch rejected duplicate key: entity={entity_path} key={key}",
598 ))
599 }
600
601 pub(crate) fn mutation_index_store_generation_changed(
603 expected_generation: u64,
604 observed_generation: u64,
605 ) -> Self {
606 Self::executor_invariant(format!(
607 "index store generation changed between preflight and apply: expected {expected_generation}, found {observed_generation}",
608 ))
609 }
610
611 #[must_use]
613 #[cold]
614 #[inline(never)]
615 pub(crate) fn executor_invariant_message(reason: impl Into<String>) -> String {
616 format!("executor invariant violated: {}", reason.into())
617 }
618
619 #[cold]
621 #[inline(never)]
622 pub(crate) fn planner_invariant(message: impl Into<String>) -> Self {
623 Self::new(
624 ErrorClass::InvariantViolation,
625 ErrorOrigin::Planner,
626 message.into(),
627 )
628 }
629
630 #[must_use]
632 pub(crate) fn invalid_logical_plan_message(reason: impl Into<String>) -> String {
633 format!("invalid logical plan: {}", reason.into())
634 }
635
636 pub(crate) fn query_invalid_logical_plan(reason: impl Into<String>) -> Self {
638 Self::planner_invariant(Self::invalid_logical_plan_message(reason))
639 }
640
641 pub(crate) fn store_invariant(message: impl Into<String>) -> Self {
643 Self::new(
644 ErrorClass::InvariantViolation,
645 ErrorOrigin::Store,
646 message.into(),
647 )
648 }
649
650 pub(crate) fn duplicate_runtime_hooks_for_entity_tag(
652 entity_tag: crate::types::EntityTag,
653 ) -> Self {
654 Self::store_invariant(format!(
655 "duplicate runtime hooks for entity tag '{}'",
656 entity_tag.value()
657 ))
658 }
659
660 pub(crate) fn duplicate_runtime_hooks_for_entity_path(entity_path: &str) -> Self {
662 Self::store_invariant(format!(
663 "duplicate runtime hooks for entity path '{entity_path}'"
664 ))
665 }
666
667 #[cold]
669 #[inline(never)]
670 pub(crate) fn store_internal(message: impl Into<String>) -> Self {
671 Self::new(ErrorClass::Internal, ErrorOrigin::Store, message.into())
672 }
673
674 pub(crate) fn commit_memory_id_unconfigured() -> Self {
676 Self::store_internal(
677 "commit memory id is not configured; initialize recovery before commit store access",
678 )
679 }
680
681 pub(crate) fn commit_memory_id_mismatch(cached_id: u8, configured_id: u8) -> Self {
683 Self::store_internal(format!(
684 "commit memory id mismatch: cached={cached_id}, configured={configured_id}",
685 ))
686 }
687
688 pub(crate) fn commit_memory_stable_key_mismatch(
690 cached_key: &str,
691 configured_key: &str,
692 ) -> Self {
693 Self::store_internal(format!(
694 "commit memory stable key mismatch: cached={cached_key}, configured={configured_key}",
695 ))
696 }
697
698 pub(crate) fn delete_rollback_row_required() -> Self {
700 Self::store_internal("missing raw row for delete rollback")
701 }
702
703 #[cfg_attr(test, allow(dead_code))]
705 pub(crate) fn commit_memory_registry_init_failed(err: impl fmt::Display) -> Self {
706 Self::store_internal(format!("memory registry init failed: {err}"))
707 }
708
709 pub(crate) fn recovery_integrity_validation_failed(
711 missing_index_entries: u64,
712 divergent_index_entries: u64,
713 orphan_index_references: u64,
714 ) -> Self {
715 Self::store_corruption(format!(
716 "recovery integrity validation failed: missing_index_entries={missing_index_entries} divergent_index_entries={divergent_index_entries} orphan_index_references={orphan_index_references}",
717 ))
718 }
719
720 #[cold]
722 #[inline(never)]
723 pub(crate) fn index_internal(message: impl Into<String>) -> Self {
724 Self::new(ErrorClass::Internal, ErrorOrigin::Index, message.into())
725 }
726
727 pub(crate) fn structural_index_removal_entity_key_required() -> Self {
729 Self::index_internal("missing old entity key for structural index removal")
730 }
731
732 pub(crate) fn structural_index_insertion_entity_key_required() -> Self {
734 Self::index_internal("missing new entity key for structural index insertion")
735 }
736
737 pub(crate) fn index_commit_op_old_entity_key_required() -> Self {
739 Self::index_internal("missing old entity key for index removal")
740 }
741
742 pub(crate) fn index_commit_op_new_entity_key_required() -> Self {
744 Self::index_internal("missing new entity key for index insertion")
745 }
746
747 #[cfg(test)]
749 pub(crate) fn query_internal(message: impl Into<String>) -> Self {
750 Self::new(ErrorClass::Internal, ErrorOrigin::Query, message.into())
751 }
752
753 #[cold]
755 #[inline(never)]
756 pub(crate) fn query_unsupported(message: impl Into<String>) -> Self {
757 Self::new(ErrorClass::Unsupported, ErrorOrigin::Query, message.into())
758 }
759
760 #[cold]
762 #[inline(never)]
763 pub(crate) fn query_numeric_overflow() -> Self {
764 Self {
765 class: ErrorClass::Unsupported,
766 origin: ErrorOrigin::Query,
767 message: "numeric overflow".to_string(),
768 detail: Some(ErrorDetail::Query(QueryErrorDetail::NumericOverflow)),
769 }
770 }
771
772 #[cold]
775 #[inline(never)]
776 pub(crate) fn query_numeric_not_representable() -> Self {
777 Self {
778 class: ErrorClass::Unsupported,
779 origin: ErrorOrigin::Query,
780 message: "numeric result is not representable".to_string(),
781 detail: Some(ErrorDetail::Query(
782 QueryErrorDetail::NumericNotRepresentable,
783 )),
784 }
785 }
786
787 #[cold]
789 #[inline(never)]
790 pub(crate) fn serialize_internal(message: impl Into<String>) -> Self {
791 Self::new(ErrorClass::Internal, ErrorOrigin::Serialize, message.into())
792 }
793
794 pub(crate) fn persisted_row_encode_failed(detail: impl fmt::Display) -> Self {
796 Self::serialize_internal(format!("row encode failed: {detail}"))
797 }
798
799 pub(crate) fn persisted_row_field_encode_failed(
801 field_name: &str,
802 detail: impl fmt::Display,
803 ) -> Self {
804 Self::serialize_internal(format!(
805 "row encode failed for field '{field_name}': {detail}",
806 ))
807 }
808
809 pub(crate) fn bytes_field_value_encode_failed(detail: impl fmt::Display) -> Self {
811 Self::serialize_internal(format!("bytes(field) value encode failed: {detail}"))
812 }
813
814 #[cold]
816 #[inline(never)]
817 pub(crate) fn store_corruption(message: impl Into<String>) -> Self {
818 Self::new(ErrorClass::Corruption, ErrorOrigin::Store, message.into())
819 }
820
821 #[cfg_attr(test, allow(dead_code))]
823 pub(crate) fn multiple_commit_memory_ids_registered(ids: impl fmt::Debug) -> Self {
824 Self::store_corruption(format!(
825 "multiple commit marker memory ids registered: {ids:?}"
826 ))
827 }
828
829 pub(crate) fn commit_corruption(detail: impl fmt::Display) -> Self {
831 Self::store_corruption(format!("commit marker corrupted: {detail}"))
832 }
833
834 pub(crate) fn commit_component_corruption(component: &str, detail: impl fmt::Display) -> Self {
836 Self::store_corruption(format!("commit marker {component} corrupted: {detail}"))
837 }
838
839 pub(crate) fn commit_id_generation_failed(detail: impl fmt::Display) -> Self {
841 Self::store_internal(format!("commit id generation failed: {detail}"))
842 }
843
844 pub(crate) fn commit_marker_payload_exceeds_u32_length_limit(label: &str, len: usize) -> Self {
846 Self::store_unsupported(format!("{label} exceeds u32 length limit: {len} bytes"))
847 }
848
849 pub(crate) fn commit_component_length_invalid(
851 component: &str,
852 len: usize,
853 expected: impl fmt::Display,
854 ) -> Self {
855 Self::commit_component_corruption(
856 component,
857 format!("invalid length {len}, expected {expected}"),
858 )
859 }
860
861 pub(crate) fn commit_marker_exceeds_max_size(size: usize, max_size: u32) -> Self {
863 Self::commit_corruption(format!(
864 "commit marker exceeds max size: {size} bytes (limit {max_size})",
865 ))
866 }
867
868 #[cfg(test)]
870 pub(crate) fn commit_marker_exceeds_max_size_before_persist(
871 size: usize,
872 max_size: u32,
873 ) -> Self {
874 Self::store_unsupported(format!(
875 "commit marker exceeds max size: {size} bytes (limit {max_size})",
876 ))
877 }
878
879 pub(crate) fn commit_control_slot_exceeds_max_size(size: usize, max_size: u32) -> Self {
881 Self::store_unsupported(format!(
882 "commit control slot exceeds max size: {size} bytes (limit {max_size})",
883 ))
884 }
885
886 pub(crate) fn commit_control_slot_marker_bytes_exceed_u32_length_limit(size: usize) -> Self {
888 Self::store_unsupported(format!(
889 "commit marker bytes exceed u32 length limit: {size} bytes",
890 ))
891 }
892
893 pub(crate) fn startup_index_rebuild_invalid_data_key(
895 store_path: &str,
896 detail: impl fmt::Display,
897 ) -> Self {
898 Self::store_corruption(format!(
899 "startup index rebuild failed: invalid data key in store '{store_path}' ({detail})",
900 ))
901 }
902
903 #[cold]
905 #[inline(never)]
906 pub(crate) fn index_corruption(message: impl Into<String>) -> Self {
907 Self::new(ErrorClass::Corruption, ErrorOrigin::Index, message.into())
908 }
909
910 pub(crate) fn index_unique_validation_corruption(
912 entity_path: &str,
913 fields: &str,
914 detail: impl fmt::Display,
915 ) -> Self {
916 Self::index_plan_index_corruption(format!(
917 "index corrupted: {entity_path} ({fields}) -> {detail}",
918 ))
919 }
920
921 pub(crate) fn structural_index_entry_corruption(
923 entity_path: &str,
924 fields: &str,
925 detail: impl fmt::Display,
926 ) -> Self {
927 Self::index_plan_index_corruption(format!(
928 "index corrupted: {entity_path} ({fields}) -> {detail}",
929 ))
930 }
931
932 pub(crate) fn index_unique_validation_entity_key_required() -> Self {
934 Self::index_invariant("missing entity key during unique validation")
935 }
936
937 pub(crate) fn index_unique_validation_row_deserialize_failed(
939 data_key: impl fmt::Display,
940 source: impl fmt::Display,
941 ) -> Self {
942 Self::index_plan_serialize_corruption(format!(
943 "failed to structurally deserialize row: {data_key} ({source})"
944 ))
945 }
946
947 pub(crate) fn index_unique_validation_primary_key_decode_failed(
949 data_key: impl fmt::Display,
950 source: impl fmt::Display,
951 ) -> Self {
952 Self::index_plan_serialize_corruption(format!(
953 "failed to decode structural primary-key slot: {data_key} ({source})"
954 ))
955 }
956
957 pub(crate) fn index_unique_validation_key_rebuild_failed(
959 data_key: impl fmt::Display,
960 entity_path: &str,
961 source: impl fmt::Display,
962 ) -> Self {
963 Self::index_plan_serialize_corruption(format!(
964 "failed to structurally decode unique key row {data_key} for {entity_path}: {source}",
965 ))
966 }
967
968 pub(crate) fn index_unique_validation_row_required(data_key: impl fmt::Display) -> Self {
970 Self::index_plan_store_corruption(format!("missing row: {data_key}"))
971 }
972
973 pub(crate) fn index_only_predicate_component_required() -> Self {
975 Self::index_invariant("index-only predicate program referenced missing index component")
976 }
977
978 pub(crate) fn index_scan_continuation_anchor_within_envelope_required() -> Self {
980 Self::index_invariant(
981 "index-range continuation anchor is outside the requested range envelope",
982 )
983 }
984
985 pub(crate) fn index_scan_continuation_advancement_required() -> Self {
987 Self::index_invariant("index-range continuation scan did not advance beyond the anchor")
988 }
989
990 pub(crate) fn index_scan_key_corrupted_during(
992 context: &'static str,
993 err: impl fmt::Display,
994 ) -> Self {
995 Self::index_corruption(format!("index key corrupted during {context}: {err}"))
996 }
997
998 pub(crate) fn index_projection_component_required(
1000 index_name: &str,
1001 component_index: usize,
1002 ) -> Self {
1003 Self::index_invariant(format!(
1004 "index projection referenced missing component: index='{index_name}' component_index={component_index}",
1005 ))
1006 }
1007
1008 pub(crate) fn unique_index_entry_single_key_required() -> Self {
1010 Self::index_corruption("unique index entry contains an unexpected number of keys")
1011 }
1012
1013 pub(crate) fn index_entry_decode_failed(err: impl fmt::Display) -> Self {
1015 Self::index_corruption(err.to_string())
1016 }
1017
1018 pub(crate) fn serialize_corruption(message: impl Into<String>) -> Self {
1020 Self::new(
1021 ErrorClass::Corruption,
1022 ErrorOrigin::Serialize,
1023 message.into(),
1024 )
1025 }
1026
1027 pub(crate) fn persisted_row_decode_failed(detail: impl fmt::Display) -> Self {
1029 Self::serialize_corruption(format!("row decode: {detail}"))
1030 }
1031
1032 pub(crate) fn persisted_row_field_decode_failed(
1034 field_name: &str,
1035 detail: impl fmt::Display,
1036 ) -> Self {
1037 Self::serialize_corruption(format!(
1038 "row decode failed for field '{field_name}': {detail}",
1039 ))
1040 }
1041
1042 pub(crate) fn persisted_row_field_kind_decode_failed(
1044 field_name: &str,
1045 field_kind: impl fmt::Debug,
1046 detail: impl fmt::Display,
1047 ) -> Self {
1048 Self::persisted_row_field_decode_failed(
1049 field_name,
1050 format!("kind={field_kind:?}: {detail}"),
1051 )
1052 }
1053
1054 pub(crate) fn persisted_row_field_payload_exact_len_required(
1056 field_name: &str,
1057 payload_kind: &str,
1058 expected_len: usize,
1059 ) -> Self {
1060 let unit = if expected_len == 1 { "byte" } else { "bytes" };
1061
1062 Self::persisted_row_field_decode_failed(
1063 field_name,
1064 format!("{payload_kind} payload must be exactly {expected_len} {unit}"),
1065 )
1066 }
1067
1068 pub(crate) fn persisted_row_field_payload_must_be_empty(
1070 field_name: &str,
1071 payload_kind: &str,
1072 ) -> Self {
1073 Self::persisted_row_field_decode_failed(
1074 field_name,
1075 format!("{payload_kind} payload must be empty"),
1076 )
1077 }
1078
1079 pub(crate) fn persisted_row_field_payload_invalid_byte(
1081 field_name: &str,
1082 payload_kind: &str,
1083 value: u8,
1084 ) -> Self {
1085 Self::persisted_row_field_decode_failed(
1086 field_name,
1087 format!("invalid {payload_kind} payload byte {value}"),
1088 )
1089 }
1090
1091 pub(crate) fn persisted_row_field_payload_non_finite(
1093 field_name: &str,
1094 payload_kind: &str,
1095 ) -> Self {
1096 Self::persisted_row_field_decode_failed(
1097 field_name,
1098 format!("{payload_kind} payload is non-finite"),
1099 )
1100 }
1101
1102 pub(crate) fn persisted_row_field_payload_out_of_range(
1104 field_name: &str,
1105 payload_kind: &str,
1106 ) -> Self {
1107 Self::persisted_row_field_decode_failed(
1108 field_name,
1109 format!("{payload_kind} payload out of range for target type"),
1110 )
1111 }
1112
1113 pub(crate) fn persisted_row_field_text_payload_invalid_utf8(
1115 field_name: &str,
1116 detail: impl fmt::Display,
1117 ) -> Self {
1118 Self::persisted_row_field_decode_failed(
1119 field_name,
1120 format!("invalid UTF-8 text payload ({detail})"),
1121 )
1122 }
1123
1124 pub(crate) fn persisted_row_slot_lookup_out_of_bounds(model_path: &str, slot: usize) -> Self {
1126 Self::index_invariant(format!(
1127 "slot lookup outside model bounds during structural row access: model='{model_path}' slot={slot}",
1128 ))
1129 }
1130
1131 pub(crate) fn persisted_row_slot_cache_lookup_out_of_bounds(
1133 model_path: &str,
1134 slot: usize,
1135 ) -> Self {
1136 Self::index_invariant(format!(
1137 "slot cache lookup outside model bounds during structural row access: model='{model_path}' slot={slot}",
1138 ))
1139 }
1140
1141 pub(crate) fn persisted_row_primary_key_not_storage_encodable(
1143 data_key: impl fmt::Debug,
1144 detail: impl fmt::Display,
1145 ) -> Self {
1146 Self::persisted_row_decode_failed(format!(
1147 "primary-key value is not storage-key encodable: {data_key:?} ({detail})",
1148 ))
1149 }
1150
1151 pub(crate) fn persisted_row_primary_key_slot_missing(data_key: impl fmt::Debug) -> Self {
1153 Self::persisted_row_decode_failed(format!(
1154 "missing primary-key slot while validating {data_key:?}",
1155 ))
1156 }
1157
1158 pub(crate) fn persisted_row_key_mismatch(
1160 expected_key: impl fmt::Debug,
1161 found_key: impl fmt::Debug,
1162 ) -> Self {
1163 Self::store_corruption(format!(
1164 "row key mismatch: expected {expected_key:?}, found {found_key:?}",
1165 ))
1166 }
1167
1168 pub(crate) fn persisted_row_declared_field_missing(field_name: &str) -> Self {
1170 Self::persisted_row_decode_failed(format!("missing declared field `{field_name}`"))
1171 }
1172
1173 pub(crate) fn data_key_entity_mismatch(
1175 expected: impl fmt::Display,
1176 found: impl fmt::Display,
1177 ) -> Self {
1178 Self::store_corruption(format!(
1179 "data key entity mismatch: expected {expected}, found {found}",
1180 ))
1181 }
1182
1183 pub(crate) fn reverse_index_ordinal_overflow(
1185 source_path: &str,
1186 field_name: &str,
1187 target_path: &str,
1188 detail: impl fmt::Display,
1189 ) -> Self {
1190 Self::index_internal(format!(
1191 "reverse index ordinal overflow: source={source_path} field={field_name} target={target_path} ({detail})",
1192 ))
1193 }
1194
1195 pub(crate) fn reverse_index_entry_corrupted(
1197 source_path: &str,
1198 field_name: &str,
1199 target_path: &str,
1200 index_key: impl fmt::Debug,
1201 detail: impl fmt::Display,
1202 ) -> Self {
1203 Self::index_corruption(format!(
1204 "reverse index entry corrupted: source={source_path} field={field_name} target={target_path} key={index_key:?} ({detail})",
1205 ))
1206 }
1207
1208 pub(crate) fn reverse_index_entry_encode_failed(
1210 source_path: &str,
1211 field_name: &str,
1212 target_path: &str,
1213 detail: impl fmt::Display,
1214 ) -> Self {
1215 Self::index_unsupported(format!(
1216 "reverse index entry encoding failed: source={source_path} field={field_name} target={target_path} ({detail})",
1217 ))
1218 }
1219
1220 pub(crate) fn relation_target_store_missing(
1222 source_path: &str,
1223 field_name: &str,
1224 target_path: &str,
1225 store_path: &str,
1226 detail: impl fmt::Display,
1227 ) -> Self {
1228 Self::executor_internal(format!(
1229 "relation target store missing: source={source_path} field={field_name} target={target_path} store={store_path} ({detail})",
1230 ))
1231 }
1232
1233 pub(crate) fn relation_target_key_decode_failed(
1235 context_label: &str,
1236 source_path: &str,
1237 field_name: &str,
1238 target_path: &str,
1239 detail: impl fmt::Display,
1240 ) -> Self {
1241 Self::identity_corruption(format!(
1242 "{context_label}: source={source_path} field={field_name} target={target_path} ({detail})",
1243 ))
1244 }
1245
1246 pub(crate) fn relation_target_entity_mismatch(
1248 context_label: &str,
1249 source_path: &str,
1250 field_name: &str,
1251 target_path: &str,
1252 target_entity_name: &str,
1253 expected_tag: impl fmt::Display,
1254 actual_tag: impl fmt::Display,
1255 ) -> Self {
1256 Self::store_corruption(format!(
1257 "{context_label}: source={source_path} field={field_name} target={target_path} expected={target_entity_name} (tag={expected_tag}) actual_tag={actual_tag}",
1258 ))
1259 }
1260
1261 pub(crate) fn relation_source_row_decode_failed(
1263 source_path: &str,
1264 field_name: &str,
1265 target_path: &str,
1266 detail: impl fmt::Display,
1267 ) -> Self {
1268 Self::serialize_corruption(format!(
1269 "relation source row decode: source={source_path} field={field_name} target={target_path} ({detail})",
1270 ))
1271 }
1272
1273 pub(crate) fn relation_source_row_unsupported_scalar_relation_key(
1275 source_path: &str,
1276 field_name: &str,
1277 target_path: &str,
1278 ) -> Self {
1279 Self::serialize_corruption(format!(
1280 "relation source row decode: unsupported scalar relation key: source={source_path} field={field_name} target={target_path}",
1281 ))
1282 }
1283
1284 pub(crate) fn relation_source_row_invalid_field_kind(field_kind: impl fmt::Debug) -> Self {
1286 Self::serialize_corruption(format!(
1287 "invalid strong relation field kind during structural decode: {field_kind:?}"
1288 ))
1289 }
1290
1291 pub(crate) fn relation_source_row_unsupported_key_kind(field_kind: impl fmt::Debug) -> Self {
1293 Self::serialize_corruption(format!(
1294 "unsupported strong relation key kind during structural decode: {field_kind:?}"
1295 ))
1296 }
1297
1298 pub(crate) fn reverse_index_relation_target_decode_invariant_violated(
1300 source_path: &str,
1301 field_name: &str,
1302 target_path: &str,
1303 ) -> Self {
1304 Self::executor_internal(format!(
1305 "relation target decode invariant violated while preparing reverse index: source={source_path} field={field_name} target={target_path}",
1306 ))
1307 }
1308
1309 pub(crate) fn bytes_covering_component_payload_empty() -> Self {
1311 Self::index_corruption("index component payload is empty during covering projection decode")
1312 }
1313
1314 pub(crate) fn bytes_covering_bool_payload_truncated() -> Self {
1316 Self::index_corruption("bool covering component payload is truncated")
1317 }
1318
1319 pub(crate) fn bytes_covering_component_payload_invalid_length(payload_kind: &str) -> Self {
1321 Self::index_corruption(format!(
1322 "{payload_kind} covering component payload has invalid length"
1323 ))
1324 }
1325
1326 pub(crate) fn bytes_covering_bool_payload_invalid_value() -> Self {
1328 Self::index_corruption("bool covering component payload has invalid value")
1329 }
1330
1331 pub(crate) fn bytes_covering_text_payload_invalid_terminator() -> Self {
1333 Self::index_corruption("text covering component payload has invalid terminator")
1334 }
1335
1336 pub(crate) fn bytes_covering_text_payload_trailing_bytes() -> Self {
1338 Self::index_corruption("text covering component payload contains trailing bytes")
1339 }
1340
1341 pub(crate) fn bytes_covering_text_payload_invalid_utf8() -> Self {
1343 Self::index_corruption("text covering component payload is not valid UTF-8")
1344 }
1345
1346 pub(crate) fn bytes_covering_text_payload_invalid_escape_byte() -> Self {
1348 Self::index_corruption("text covering component payload has invalid escape byte")
1349 }
1350
1351 pub(crate) fn bytes_covering_text_payload_missing_terminator() -> Self {
1353 Self::index_corruption("text covering component payload is missing terminator")
1354 }
1355
1356 #[must_use]
1358 pub fn missing_persisted_slot(field_name: &'static str) -> Self {
1359 Self::serialize_corruption(format!("row decode: missing required field '{field_name}'"))
1360 }
1361
1362 pub(crate) fn identity_corruption(message: impl Into<String>) -> Self {
1364 Self::new(
1365 ErrorClass::Corruption,
1366 ErrorOrigin::Identity,
1367 message.into(),
1368 )
1369 }
1370
1371 #[cold]
1373 #[inline(never)]
1374 pub(crate) fn store_unsupported(message: impl Into<String>) -> Self {
1375 Self::new(ErrorClass::Unsupported, ErrorOrigin::Store, message.into())
1376 }
1377
1378 pub(crate) fn unsupported_entity_tag_in_data_store(
1380 entity_tag: crate::types::EntityTag,
1381 ) -> Self {
1382 Self::store_unsupported(format!(
1383 "unsupported entity tag in data store: '{}'",
1384 entity_tag.value()
1385 ))
1386 }
1387
1388 #[cfg_attr(test, allow(dead_code))]
1390 pub(crate) fn configured_commit_memory_id_mismatch(
1391 configured_id: u8,
1392 registered_id: u8,
1393 ) -> Self {
1394 Self::store_unsupported(format!(
1395 "configured commit memory id {configured_id} does not match existing commit marker id {registered_id}",
1396 ))
1397 }
1398
1399 #[cfg_attr(test, allow(dead_code))]
1401 pub(crate) fn commit_memory_stable_key_unregistered(memory_id: u8, stable_key: &str) -> Self {
1402 Self::store_unsupported(format!(
1403 "configured commit memory id {memory_id} is not declared with stable key '{stable_key}'",
1404 ))
1405 }
1406
1407 pub(crate) fn commit_memory_id_outside_reserved_ranges(memory_id: u8) -> Self {
1409 Self::store_unsupported(format!(
1410 "configured commit memory id {memory_id} is outside reserved ranges",
1411 ))
1412 }
1413
1414 #[cfg_attr(test, allow(dead_code))]
1416 pub(crate) fn commit_memory_id_registration_failed(err: impl fmt::Display) -> Self {
1417 Self::store_internal(format!("commit memory id registration failed: {err}"))
1418 }
1419
1420 pub(crate) fn index_unsupported(message: impl Into<String>) -> Self {
1422 Self::new(ErrorClass::Unsupported, ErrorOrigin::Index, message.into())
1423 }
1424
1425 pub(crate) fn index_component_exceeds_max_size(
1427 key_item: impl fmt::Display,
1428 len: usize,
1429 max_component_size: usize,
1430 ) -> Self {
1431 Self::index_unsupported(format!(
1432 "index component exceeds max size: key item '{key_item}' -> {len} bytes (limit {max_component_size})",
1433 ))
1434 }
1435
1436 pub(crate) fn index_entry_exceeds_max_keys(
1438 entity_path: &str,
1439 fields: &str,
1440 keys: usize,
1441 ) -> Self {
1442 Self::index_unsupported(format!(
1443 "index entry exceeds max keys: {entity_path} ({fields}) -> {keys} keys",
1444 ))
1445 }
1446
1447 #[cfg(test)]
1449 pub(crate) fn index_entry_duplicate_keys_unexpected(entity_path: &str, fields: &str) -> Self {
1450 Self::index_invariant(format!(
1451 "index entry unexpectedly contains duplicate keys: {entity_path} ({fields})",
1452 ))
1453 }
1454
1455 pub(crate) fn index_entry_key_encoding_failed(
1457 entity_path: &str,
1458 fields: &str,
1459 err: impl fmt::Display,
1460 ) -> Self {
1461 Self::index_unsupported(format!(
1462 "index entry key encoding failed: {entity_path} ({fields}) -> {err}",
1463 ))
1464 }
1465
1466 pub(crate) fn serialize_unsupported(message: impl Into<String>) -> Self {
1468 Self::new(
1469 ErrorClass::Unsupported,
1470 ErrorOrigin::Serialize,
1471 message.into(),
1472 )
1473 }
1474
1475 pub(crate) fn cursor_unsupported(message: impl Into<String>) -> Self {
1477 Self::new(ErrorClass::Unsupported, ErrorOrigin::Cursor, message.into())
1478 }
1479
1480 pub(crate) fn serialize_incompatible_persisted_format(message: impl Into<String>) -> Self {
1482 Self::new(
1483 ErrorClass::IncompatiblePersistedFormat,
1484 ErrorOrigin::Serialize,
1485 message.into(),
1486 )
1487 }
1488
1489 #[cfg(feature = "sql")]
1492 pub(crate) fn query_unsupported_sql_feature(feature: &'static str) -> Self {
1493 let message = format!(
1494 "SQL query is not executable in this release: unsupported SQL feature: {feature}"
1495 );
1496
1497 Self {
1498 class: ErrorClass::Unsupported,
1499 origin: ErrorOrigin::Query,
1500 message,
1501 detail: Some(ErrorDetail::Query(
1502 QueryErrorDetail::UnsupportedSqlFeature { feature },
1503 )),
1504 }
1505 }
1506
1507 pub fn store_not_found(key: impl Into<String>) -> Self {
1508 let key = key.into();
1509
1510 Self {
1511 class: ErrorClass::NotFound,
1512 origin: ErrorOrigin::Store,
1513 message: format!("data key not found: {key}"),
1514 detail: Some(ErrorDetail::Store(StoreError::NotFound { key })),
1515 }
1516 }
1517
1518 pub fn unsupported_entity_path(path: impl Into<String>) -> Self {
1520 let path = path.into();
1521
1522 Self::new(
1523 ErrorClass::Unsupported,
1524 ErrorOrigin::Store,
1525 format!("unsupported entity path: '{path}'"),
1526 )
1527 }
1528
1529 #[must_use]
1530 pub const fn is_not_found(&self) -> bool {
1531 matches!(
1532 self.detail,
1533 Some(ErrorDetail::Store(StoreError::NotFound { .. }))
1534 )
1535 }
1536
1537 #[must_use]
1538 pub fn display_with_class(&self) -> String {
1539 format!("{}:{}: {}", self.origin, self.class, self.message)
1540 }
1541
1542 #[cold]
1544 #[inline(never)]
1545 pub(crate) fn index_plan_corruption(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1546 let message = message.into();
1547 Self::new(
1548 ErrorClass::Corruption,
1549 origin,
1550 format!("corruption detected ({origin}): {message}"),
1551 )
1552 }
1553
1554 #[cold]
1556 #[inline(never)]
1557 pub(crate) fn index_plan_index_corruption(message: impl Into<String>) -> Self {
1558 Self::index_plan_corruption(ErrorOrigin::Index, message)
1559 }
1560
1561 #[cold]
1563 #[inline(never)]
1564 pub(crate) fn index_plan_store_corruption(message: impl Into<String>) -> Self {
1565 Self::index_plan_corruption(ErrorOrigin::Store, message)
1566 }
1567
1568 #[cold]
1570 #[inline(never)]
1571 pub(crate) fn index_plan_serialize_corruption(message: impl Into<String>) -> Self {
1572 Self::index_plan_corruption(ErrorOrigin::Serialize, message)
1573 }
1574
1575 #[cfg(test)]
1577 pub(crate) fn index_plan_invariant(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1578 let message = message.into();
1579 Self::new(
1580 ErrorClass::InvariantViolation,
1581 origin,
1582 format!("invariant violation detected ({origin}): {message}"),
1583 )
1584 }
1585
1586 #[cfg(test)]
1588 pub(crate) fn index_plan_store_invariant(message: impl Into<String>) -> Self {
1589 Self::index_plan_invariant(ErrorOrigin::Store, message)
1590 }
1591
1592 pub(crate) fn index_violation(path: &str, index_fields: &[&str]) -> Self {
1594 Self::new(
1595 ErrorClass::Conflict,
1596 ErrorOrigin::Index,
1597 format!(
1598 "index constraint violation: {path} ({})",
1599 index_fields.join(", ")
1600 ),
1601 )
1602 }
1603}
1604
1605#[derive(Debug, ThisError)]
1613pub enum ErrorDetail {
1614 #[error("{0}")]
1615 Store(StoreError),
1616 #[error("{0}")]
1617 Query(QueryErrorDetail),
1618 }
1625
1626#[derive(Debug, ThisError)]
1634pub enum StoreError {
1635 #[error("key not found: {key}")]
1636 NotFound { key: String },
1637
1638 #[error("store corruption: {message}")]
1639 Corrupt { message: String },
1640
1641 #[error("store invariant violation: {message}")]
1642 InvariantViolation { message: String },
1643}
1644
1645#[derive(Debug, ThisError)]
1652pub enum QueryErrorDetail {
1653 #[error("numeric overflow")]
1654 NumericOverflow,
1655
1656 #[error("numeric result is not representable")]
1657 NumericNotRepresentable,
1658
1659 #[error("unsupported SQL feature: {feature}")]
1660 UnsupportedSqlFeature { feature: &'static str },
1661}
1662
1663#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1670pub enum ErrorClass {
1671 Corruption,
1672 IncompatiblePersistedFormat,
1673 NotFound,
1674 Internal,
1675 Conflict,
1676 Unsupported,
1677 InvariantViolation,
1678}
1679
1680impl fmt::Display for ErrorClass {
1681 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1682 let label = match self {
1683 Self::Corruption => "corruption",
1684 Self::IncompatiblePersistedFormat => "incompatible_persisted_format",
1685 Self::NotFound => "not_found",
1686 Self::Internal => "internal",
1687 Self::Conflict => "conflict",
1688 Self::Unsupported => "unsupported",
1689 Self::InvariantViolation => "invariant_violation",
1690 };
1691 write!(f, "{label}")
1692 }
1693}
1694
1695#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1702pub enum ErrorOrigin {
1703 Serialize,
1704 Store,
1705 Index,
1706 Identity,
1707 Query,
1708 Planner,
1709 Cursor,
1710 Recovery,
1711 Response,
1712 Executor,
1713 Interface,
1714}
1715
1716impl fmt::Display for ErrorOrigin {
1717 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1718 let label = match self {
1719 Self::Serialize => "serialize",
1720 Self::Store => "store",
1721 Self::Index => "index",
1722 Self::Identity => "identity",
1723 Self::Query => "query",
1724 Self::Planner => "planner",
1725 Self::Cursor => "cursor",
1726 Self::Recovery => "recovery",
1727 Self::Response => "response",
1728 Self::Executor => "executor",
1729 Self::Interface => "interface",
1730 };
1731 write!(f, "{label}")
1732 }
1733}