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 pub(crate) fn recovery_integrity_validation_failed(
705 missing_index_entries: u64,
706 divergent_index_entries: u64,
707 orphan_index_references: u64,
708 ) -> Self {
709 Self::store_corruption(format!(
710 "recovery integrity validation failed: missing_index_entries={missing_index_entries} divergent_index_entries={divergent_index_entries} orphan_index_references={orphan_index_references}",
711 ))
712 }
713
714 #[cold]
716 #[inline(never)]
717 pub(crate) fn index_internal(message: impl Into<String>) -> Self {
718 Self::new(ErrorClass::Internal, ErrorOrigin::Index, message.into())
719 }
720
721 pub(crate) fn structural_index_removal_entity_key_required() -> Self {
723 Self::index_internal("missing old entity key for structural index removal")
724 }
725
726 pub(crate) fn structural_index_insertion_entity_key_required() -> Self {
728 Self::index_internal("missing new entity key for structural index insertion")
729 }
730
731 pub(crate) fn index_commit_op_old_entity_key_required() -> Self {
733 Self::index_internal("missing old entity key for index removal")
734 }
735
736 pub(crate) fn index_commit_op_new_entity_key_required() -> Self {
738 Self::index_internal("missing new entity key for index insertion")
739 }
740
741 #[cfg(test)]
743 pub(crate) fn query_internal(message: impl Into<String>) -> Self {
744 Self::new(ErrorClass::Internal, ErrorOrigin::Query, message.into())
745 }
746
747 #[cold]
749 #[inline(never)]
750 pub(crate) fn query_unsupported(message: impl Into<String>) -> Self {
751 Self::new(ErrorClass::Unsupported, ErrorOrigin::Query, message.into())
752 }
753
754 #[cold]
756 #[inline(never)]
757 pub(crate) fn query_schema_ddl_admission(
758 error: SchemaDdlAdmissionError,
759 message: impl Into<String>,
760 ) -> Self {
761 Self {
762 class: ErrorClass::Unsupported,
763 origin: ErrorOrigin::Query,
764 message: message.into(),
765 detail: Some(ErrorDetail::Query(QueryErrorDetail::SchemaDdlAdmission {
766 error,
767 })),
768 }
769 }
770
771 #[cold]
773 #[inline(never)]
774 pub(crate) fn query_numeric_overflow() -> Self {
775 Self {
776 class: ErrorClass::Unsupported,
777 origin: ErrorOrigin::Query,
778 message: "numeric overflow".to_string(),
779 detail: Some(ErrorDetail::Query(QueryErrorDetail::NumericOverflow)),
780 }
781 }
782
783 #[cold]
786 #[inline(never)]
787 pub(crate) fn query_numeric_not_representable() -> Self {
788 Self {
789 class: ErrorClass::Unsupported,
790 origin: ErrorOrigin::Query,
791 message: "numeric result is not representable".to_string(),
792 detail: Some(ErrorDetail::Query(
793 QueryErrorDetail::NumericNotRepresentable,
794 )),
795 }
796 }
797
798 #[cold]
800 #[inline(never)]
801 pub(crate) fn serialize_internal(message: impl Into<String>) -> Self {
802 Self::new(ErrorClass::Internal, ErrorOrigin::Serialize, message.into())
803 }
804
805 pub(crate) fn persisted_row_encode_failed(detail: impl fmt::Display) -> Self {
807 Self::serialize_internal(format!("row encode failed: {detail}"))
808 }
809
810 pub(crate) fn persisted_row_field_encode_failed(
812 field_name: &str,
813 detail: impl fmt::Display,
814 ) -> Self {
815 Self::serialize_internal(format!(
816 "row encode failed for field '{field_name}': {detail}",
817 ))
818 }
819
820 pub(crate) fn bytes_field_value_encode_failed(detail: impl fmt::Display) -> Self {
822 Self::serialize_internal(format!("bytes(field) value encode failed: {detail}"))
823 }
824
825 #[cold]
827 #[inline(never)]
828 pub(crate) fn store_corruption(message: impl Into<String>) -> Self {
829 Self::new(ErrorClass::Corruption, ErrorOrigin::Store, message.into())
830 }
831
832 pub(crate) fn commit_corruption(detail: impl fmt::Display) -> Self {
834 Self::store_corruption(format!("commit marker corrupted: {detail}"))
835 }
836
837 pub(crate) fn commit_component_corruption(component: &str, detail: impl fmt::Display) -> Self {
839 Self::store_corruption(format!("commit marker {component} corrupted: {detail}"))
840 }
841
842 pub(crate) fn commit_id_generation_failed(detail: impl fmt::Display) -> Self {
844 Self::store_internal(format!("commit id generation failed: {detail}"))
845 }
846
847 pub(crate) fn commit_marker_payload_exceeds_u32_length_limit(label: &str, len: usize) -> Self {
849 Self::store_unsupported(format!("{label} exceeds u32 length limit: {len} bytes"))
850 }
851
852 pub(crate) fn commit_component_length_invalid(
854 component: &str,
855 len: usize,
856 expected: impl fmt::Display,
857 ) -> Self {
858 Self::commit_component_corruption(
859 component,
860 format!("invalid length {len}, expected {expected}"),
861 )
862 }
863
864 pub(crate) fn commit_marker_exceeds_max_size(size: usize, max_size: u32) -> Self {
866 Self::commit_corruption(format!(
867 "commit marker exceeds max size: {size} bytes (limit {max_size})",
868 ))
869 }
870
871 pub(crate) fn commit_control_slot_exceeds_max_size(size: usize, max_size: u32) -> Self {
873 Self::store_unsupported(format!(
874 "commit control slot exceeds max size: {size} bytes (limit {max_size})",
875 ))
876 }
877
878 pub(crate) fn commit_control_slot_marker_bytes_exceed_u32_length_limit(size: usize) -> Self {
880 Self::store_unsupported(format!(
881 "commit marker bytes exceed u32 length limit: {size} bytes",
882 ))
883 }
884
885 pub(crate) fn startup_index_rebuild_invalid_data_key(
887 store_path: &str,
888 detail: impl fmt::Display,
889 ) -> Self {
890 Self::store_corruption(format!(
891 "startup index rebuild failed: invalid data key in store '{store_path}' ({detail})",
892 ))
893 }
894
895 #[cold]
897 #[inline(never)]
898 pub(crate) fn index_corruption(message: impl Into<String>) -> Self {
899 Self::new(ErrorClass::Corruption, ErrorOrigin::Index, message.into())
900 }
901
902 pub(crate) fn index_unique_validation_corruption(
904 entity_path: &str,
905 fields: &str,
906 detail: impl fmt::Display,
907 ) -> Self {
908 Self::index_plan_index_corruption(format!(
909 "index corrupted: {entity_path} ({fields}) -> {detail}",
910 ))
911 }
912
913 pub(crate) fn structural_index_entry_corruption(
915 entity_path: &str,
916 fields: &str,
917 detail: impl fmt::Display,
918 ) -> Self {
919 Self::index_plan_index_corruption(format!(
920 "index corrupted: {entity_path} ({fields}) -> {detail}",
921 ))
922 }
923
924 pub(crate) fn index_unique_validation_entity_key_required() -> Self {
926 Self::index_invariant("missing entity key during unique validation")
927 }
928
929 pub(crate) fn index_unique_validation_row_deserialize_failed(
931 data_key: impl fmt::Display,
932 source: impl fmt::Display,
933 ) -> Self {
934 Self::index_plan_serialize_corruption(format!(
935 "failed to structurally deserialize row: {data_key} ({source})"
936 ))
937 }
938
939 pub(crate) fn index_unique_validation_primary_key_decode_failed(
941 data_key: impl fmt::Display,
942 source: impl fmt::Display,
943 ) -> Self {
944 Self::index_plan_serialize_corruption(format!(
945 "failed to decode structural primary-key slot: {data_key} ({source})"
946 ))
947 }
948
949 pub(crate) fn index_unique_validation_key_rebuild_failed(
951 data_key: impl fmt::Display,
952 entity_path: &str,
953 source: impl fmt::Display,
954 ) -> Self {
955 Self::index_plan_serialize_corruption(format!(
956 "failed to structurally decode unique key row {data_key} for {entity_path}: {source}",
957 ))
958 }
959
960 pub(crate) fn index_unique_validation_row_required(data_key: impl fmt::Display) -> Self {
962 Self::index_plan_store_corruption(format!("missing row: {data_key}"))
963 }
964
965 pub(crate) fn index_only_predicate_component_required() -> Self {
967 Self::index_invariant("index-only predicate program referenced missing index component")
968 }
969
970 pub(crate) fn index_scan_continuation_anchor_within_envelope_required() -> Self {
972 Self::index_invariant(
973 "index-range continuation anchor is outside the requested range envelope",
974 )
975 }
976
977 pub(crate) fn index_scan_continuation_advancement_required() -> Self {
979 Self::index_invariant("index-range continuation scan did not advance beyond the anchor")
980 }
981
982 pub(crate) fn index_scan_key_corrupted_during(
984 context: &'static str,
985 err: impl fmt::Display,
986 ) -> Self {
987 Self::index_corruption(format!("index key corrupted during {context}: {err}"))
988 }
989
990 pub(crate) fn index_projection_component_required(
992 index_name: &str,
993 component_index: usize,
994 ) -> Self {
995 Self::index_invariant(format!(
996 "index projection referenced missing component: index='{index_name}' component_index={component_index}",
997 ))
998 }
999
1000 pub(crate) fn index_entry_decode_failed(err: impl fmt::Display) -> Self {
1002 Self::index_corruption(err.to_string())
1003 }
1004
1005 pub(crate) fn serialize_corruption(message: impl Into<String>) -> Self {
1007 Self::new(
1008 ErrorClass::Corruption,
1009 ErrorOrigin::Serialize,
1010 message.into(),
1011 )
1012 }
1013
1014 pub(crate) fn persisted_row_decode_failed(detail: impl fmt::Display) -> Self {
1016 Self::serialize_corruption(format!("row decode: {detail}"))
1017 }
1018
1019 pub(crate) fn persisted_row_field_decode_failed(
1021 field_name: &str,
1022 detail: impl fmt::Display,
1023 ) -> Self {
1024 Self::serialize_corruption(format!(
1025 "row decode failed for field '{field_name}': {detail}",
1026 ))
1027 }
1028
1029 pub(crate) fn persisted_row_field_kind_decode_failed(
1031 field_name: &str,
1032 field_kind: impl fmt::Debug,
1033 detail: impl fmt::Display,
1034 ) -> Self {
1035 Self::persisted_row_field_decode_failed(
1036 field_name,
1037 format!("kind={field_kind:?}: {detail}"),
1038 )
1039 }
1040
1041 pub(crate) fn persisted_row_field_payload_exact_len_required(
1043 field_name: &str,
1044 payload_kind: &str,
1045 expected_len: usize,
1046 ) -> Self {
1047 let unit = if expected_len == 1 { "byte" } else { "bytes" };
1048
1049 Self::persisted_row_field_decode_failed(
1050 field_name,
1051 format!("{payload_kind} payload must be exactly {expected_len} {unit}"),
1052 )
1053 }
1054
1055 pub(crate) fn persisted_row_field_payload_must_be_empty(
1057 field_name: &str,
1058 payload_kind: &str,
1059 ) -> Self {
1060 Self::persisted_row_field_decode_failed(
1061 field_name,
1062 format!("{payload_kind} payload must be empty"),
1063 )
1064 }
1065
1066 pub(crate) fn persisted_row_field_payload_invalid_byte(
1068 field_name: &str,
1069 payload_kind: &str,
1070 value: u8,
1071 ) -> Self {
1072 Self::persisted_row_field_decode_failed(
1073 field_name,
1074 format!("invalid {payload_kind} payload byte {value}"),
1075 )
1076 }
1077
1078 pub(crate) fn persisted_row_field_payload_non_finite(
1080 field_name: &str,
1081 payload_kind: &str,
1082 ) -> Self {
1083 Self::persisted_row_field_decode_failed(
1084 field_name,
1085 format!("{payload_kind} payload is non-finite"),
1086 )
1087 }
1088
1089 pub(crate) fn persisted_row_field_payload_out_of_range(
1091 field_name: &str,
1092 payload_kind: &str,
1093 ) -> Self {
1094 Self::persisted_row_field_decode_failed(
1095 field_name,
1096 format!("{payload_kind} payload out of range for target type"),
1097 )
1098 }
1099
1100 pub(crate) fn persisted_row_field_text_payload_invalid_utf8(
1102 field_name: &str,
1103 detail: impl fmt::Display,
1104 ) -> Self {
1105 Self::persisted_row_field_decode_failed(
1106 field_name,
1107 format!("invalid UTF-8 text payload ({detail})"),
1108 )
1109 }
1110
1111 pub(crate) fn persisted_row_slot_lookup_out_of_bounds(model_path: &str, slot: usize) -> Self {
1113 Self::index_invariant(format!(
1114 "slot lookup outside model bounds during structural row access: model='{model_path}' slot={slot}",
1115 ))
1116 }
1117
1118 pub(crate) fn persisted_row_slot_cache_lookup_out_of_bounds(
1120 model_path: &str,
1121 slot: usize,
1122 ) -> Self {
1123 Self::index_invariant(format!(
1124 "slot cache lookup outside model bounds during structural row access: model='{model_path}' slot={slot}",
1125 ))
1126 }
1127
1128 pub(crate) fn persisted_row_primary_key_not_primary_key_encodable(
1130 data_key: impl fmt::Debug,
1131 detail: impl fmt::Display,
1132 ) -> Self {
1133 Self::persisted_row_decode_failed(format!(
1134 "primary-key value is not primary-key encodable: {data_key:?} ({detail})",
1135 ))
1136 }
1137
1138 pub(crate) fn persisted_row_primary_key_slot_missing(data_key: impl fmt::Debug) -> Self {
1140 Self::persisted_row_decode_failed(format!(
1141 "missing primary-key slot while validating {data_key:?}",
1142 ))
1143 }
1144
1145 pub(crate) fn persisted_row_key_mismatch(
1147 expected_key: impl fmt::Debug,
1148 found_key: impl fmt::Debug,
1149 ) -> Self {
1150 Self::store_corruption(format!(
1151 "row key mismatch: expected {expected_key:?}, found {found_key:?}",
1152 ))
1153 }
1154
1155 pub(crate) fn persisted_row_declared_field_missing(field_name: &str) -> Self {
1157 Self::persisted_row_decode_failed(format!("missing declared field `{field_name}`"))
1158 }
1159
1160 pub(crate) fn data_key_entity_mismatch(
1162 expected: impl fmt::Display,
1163 found: impl fmt::Display,
1164 ) -> Self {
1165 Self::store_corruption(format!(
1166 "data key entity mismatch: expected {expected}, found {found}",
1167 ))
1168 }
1169
1170 pub(crate) fn reverse_index_ordinal_overflow(
1172 source_path: &str,
1173 field_name: &str,
1174 target_path: &str,
1175 detail: impl fmt::Display,
1176 ) -> Self {
1177 Self::index_internal(format!(
1178 "reverse index ordinal overflow: source={source_path} field={field_name} target={target_path} ({detail})",
1179 ))
1180 }
1181
1182 pub(crate) fn reverse_index_entry_corrupted(
1184 source_path: &str,
1185 field_name: &str,
1186 target_path: &str,
1187 index_key: impl fmt::Debug,
1188 detail: impl fmt::Display,
1189 ) -> Self {
1190 Self::index_corruption(format!(
1191 "reverse index entry corrupted: source={source_path} field={field_name} target={target_path} key={index_key:?} ({detail})",
1192 ))
1193 }
1194
1195 pub(crate) fn relation_target_store_missing(
1197 source_path: &str,
1198 field_name: &str,
1199 target_path: &str,
1200 store_path: &str,
1201 detail: impl fmt::Display,
1202 ) -> Self {
1203 Self::executor_internal(format!(
1204 "relation target store missing: source={source_path} field={field_name} target={target_path} store={store_path} ({detail})",
1205 ))
1206 }
1207
1208 pub(crate) fn relation_target_key_decode_failed(
1210 context_label: &str,
1211 source_path: &str,
1212 field_name: &str,
1213 target_path: &str,
1214 detail: impl fmt::Display,
1215 ) -> Self {
1216 Self::identity_corruption(format!(
1217 "{context_label}: source={source_path} field={field_name} target={target_path} ({detail})",
1218 ))
1219 }
1220
1221 pub(crate) fn relation_target_entity_mismatch(
1223 context_label: &str,
1224 source_path: &str,
1225 field_name: &str,
1226 target_path: &str,
1227 target_entity_name: &str,
1228 expected_tag: impl fmt::Display,
1229 actual_tag: impl fmt::Display,
1230 ) -> Self {
1231 Self::store_corruption(format!(
1232 "{context_label}: source={source_path} field={field_name} target={target_path} expected={target_entity_name} (tag={expected_tag}) actual_tag={actual_tag}",
1233 ))
1234 }
1235
1236 pub(crate) fn relation_source_row_decode_failed(
1238 source_path: &str,
1239 field_name: &str,
1240 target_path: &str,
1241 detail: impl fmt::Display,
1242 ) -> Self {
1243 Self::serialize_corruption(format!(
1244 "relation source row decode: source={source_path} field={field_name} target={target_path} ({detail})",
1245 ))
1246 }
1247
1248 pub(crate) fn relation_source_row_unsupported_scalar_relation_key(
1250 source_path: &str,
1251 field_name: &str,
1252 target_path: &str,
1253 ) -> Self {
1254 Self::serialize_corruption(format!(
1255 "relation source row decode: unsupported scalar relation key: source={source_path} field={field_name} target={target_path}",
1256 ))
1257 }
1258
1259 pub(crate) fn relation_source_row_unsupported_key_kind(field_kind: impl fmt::Debug) -> Self {
1261 Self::serialize_corruption(format!(
1262 "unsupported strong relation key kind during structural decode: {field_kind:?}"
1263 ))
1264 }
1265
1266 pub(crate) fn reverse_index_relation_target_decode_invariant_violated(
1268 source_path: &str,
1269 field_name: &str,
1270 target_path: &str,
1271 ) -> Self {
1272 Self::executor_internal(format!(
1273 "relation target decode invariant violated while preparing reverse index: source={source_path} field={field_name} target={target_path}",
1274 ))
1275 }
1276
1277 pub(crate) fn bytes_covering_component_payload_empty() -> Self {
1279 Self::index_corruption("index component payload is empty during covering projection decode")
1280 }
1281
1282 pub(crate) fn bytes_covering_bool_payload_truncated() -> Self {
1284 Self::index_corruption("bool covering component payload is truncated")
1285 }
1286
1287 pub(crate) fn bytes_covering_component_payload_invalid_length(payload_kind: &str) -> Self {
1289 Self::index_corruption(format!(
1290 "{payload_kind} covering component payload has invalid length"
1291 ))
1292 }
1293
1294 pub(crate) fn bytes_covering_bool_payload_invalid_value() -> Self {
1296 Self::index_corruption("bool covering component payload has invalid value")
1297 }
1298
1299 pub(crate) fn bytes_covering_text_payload_invalid_terminator() -> Self {
1301 Self::index_corruption("text covering component payload has invalid terminator")
1302 }
1303
1304 pub(crate) fn bytes_covering_text_payload_trailing_bytes() -> Self {
1306 Self::index_corruption("text covering component payload contains trailing bytes")
1307 }
1308
1309 pub(crate) fn bytes_covering_text_payload_invalid_utf8() -> Self {
1311 Self::index_corruption("text covering component payload is not valid UTF-8")
1312 }
1313
1314 pub(crate) fn bytes_covering_text_payload_invalid_escape_byte() -> Self {
1316 Self::index_corruption("text covering component payload has invalid escape byte")
1317 }
1318
1319 pub(crate) fn bytes_covering_text_payload_missing_terminator() -> Self {
1321 Self::index_corruption("text covering component payload is missing terminator")
1322 }
1323
1324 #[must_use]
1326 pub fn missing_persisted_slot(field_name: &'static str) -> Self {
1327 Self::serialize_corruption(format!("row decode: missing required field '{field_name}'"))
1328 }
1329
1330 pub(crate) fn identity_corruption(message: impl Into<String>) -> Self {
1332 Self::new(
1333 ErrorClass::Corruption,
1334 ErrorOrigin::Identity,
1335 message.into(),
1336 )
1337 }
1338
1339 #[cold]
1341 #[inline(never)]
1342 pub(crate) fn store_unsupported(message: impl Into<String>) -> Self {
1343 Self::new(ErrorClass::Unsupported, ErrorOrigin::Store, message.into())
1344 }
1345
1346 pub(crate) fn schema_ddl_publication_race_lost(entity_path: &'static str) -> Self {
1348 let message = format!(
1349 "SQL DDL publication race lost for entity '{entity_path}': accepted schema changed after DDL binding",
1350 );
1351
1352 Self {
1353 class: ErrorClass::Unsupported,
1354 origin: ErrorOrigin::Store,
1355 message,
1356 detail: Some(ErrorDetail::Store(
1357 StoreError::SchemaDdlPublicationRaceLost {
1358 entity_path: entity_path.to_string(),
1359 },
1360 )),
1361 }
1362 }
1363
1364 pub(crate) fn unsupported_entity_tag_in_data_store(
1366 entity_tag: crate::types::EntityTag,
1367 ) -> Self {
1368 Self::store_unsupported(format!(
1369 "unsupported entity tag in data store: '{}'",
1370 entity_tag.value()
1371 ))
1372 }
1373
1374 #[cfg_attr(test, allow(dead_code))]
1376 pub(crate) fn commit_memory_id_registration_failed(err: impl fmt::Display) -> Self {
1377 Self::store_internal(format!("commit memory id registration failed: {err}"))
1378 }
1379
1380 pub(crate) fn index_unsupported(message: impl Into<String>) -> Self {
1382 Self::new(ErrorClass::Unsupported, ErrorOrigin::Index, message.into())
1383 }
1384
1385 pub(crate) fn index_component_exceeds_max_size(
1387 key_item: impl fmt::Display,
1388 len: usize,
1389 max_component_size: usize,
1390 ) -> Self {
1391 Self::index_unsupported(format!(
1392 "index component exceeds max size: key item '{key_item}' -> {len} bytes (limit {max_component_size})",
1393 ))
1394 }
1395
1396 pub(crate) fn serialize_unsupported(message: impl Into<String>) -> Self {
1398 Self::new(
1399 ErrorClass::Unsupported,
1400 ErrorOrigin::Serialize,
1401 message.into(),
1402 )
1403 }
1404
1405 pub(crate) fn cursor_unsupported(message: impl Into<String>) -> Self {
1407 Self::new(ErrorClass::Unsupported, ErrorOrigin::Cursor, message.into())
1408 }
1409
1410 pub(crate) fn serialize_incompatible_persisted_format(message: impl Into<String>) -> Self {
1412 Self::new(
1413 ErrorClass::IncompatiblePersistedFormat,
1414 ErrorOrigin::Serialize,
1415 message.into(),
1416 )
1417 }
1418
1419 #[cfg(feature = "sql")]
1422 pub(crate) fn query_unsupported_sql_feature(feature: &'static str) -> Self {
1423 let message = format!(
1424 "SQL query is not executable in this release: unsupported SQL feature: {feature}"
1425 );
1426
1427 Self {
1428 class: ErrorClass::Unsupported,
1429 origin: ErrorOrigin::Query,
1430 message,
1431 detail: Some(ErrorDetail::Query(
1432 QueryErrorDetail::UnsupportedSqlFeature { feature },
1433 )),
1434 }
1435 }
1436
1437 pub fn store_not_found(key: impl Into<String>) -> Self {
1438 let key = key.into();
1439
1440 Self {
1441 class: ErrorClass::NotFound,
1442 origin: ErrorOrigin::Store,
1443 message: format!("data key not found: {key}"),
1444 detail: Some(ErrorDetail::Store(StoreError::NotFound { key })),
1445 }
1446 }
1447
1448 pub fn unsupported_entity_path(path: impl Into<String>) -> Self {
1450 let path = path.into();
1451
1452 Self::new(
1453 ErrorClass::Unsupported,
1454 ErrorOrigin::Store,
1455 format!("unsupported entity path: '{path}'"),
1456 )
1457 }
1458
1459 #[must_use]
1460 pub const fn is_not_found(&self) -> bool {
1461 matches!(
1462 self.detail,
1463 Some(ErrorDetail::Store(StoreError::NotFound { .. }))
1464 )
1465 }
1466
1467 #[must_use]
1468 pub fn display_with_class(&self) -> String {
1469 format!("{}:{}: {}", self.origin, self.class, self.message)
1470 }
1471
1472 #[cold]
1474 #[inline(never)]
1475 pub(crate) fn index_plan_corruption(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1476 let message = message.into();
1477 Self::new(
1478 ErrorClass::Corruption,
1479 origin,
1480 format!("corruption detected ({origin}): {message}"),
1481 )
1482 }
1483
1484 #[cold]
1486 #[inline(never)]
1487 pub(crate) fn index_plan_index_corruption(message: impl Into<String>) -> Self {
1488 Self::index_plan_corruption(ErrorOrigin::Index, message)
1489 }
1490
1491 #[cold]
1493 #[inline(never)]
1494 pub(crate) fn index_plan_store_corruption(message: impl Into<String>) -> Self {
1495 Self::index_plan_corruption(ErrorOrigin::Store, message)
1496 }
1497
1498 #[cold]
1500 #[inline(never)]
1501 pub(crate) fn index_plan_serialize_corruption(message: impl Into<String>) -> Self {
1502 Self::index_plan_corruption(ErrorOrigin::Serialize, message)
1503 }
1504
1505 #[cfg(test)]
1507 pub(crate) fn index_plan_invariant(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1508 let message = message.into();
1509 Self::new(
1510 ErrorClass::InvariantViolation,
1511 origin,
1512 format!("invariant violation detected ({origin}): {message}"),
1513 )
1514 }
1515
1516 #[cfg(test)]
1518 pub(crate) fn index_plan_store_invariant(message: impl Into<String>) -> Self {
1519 Self::index_plan_invariant(ErrorOrigin::Store, message)
1520 }
1521
1522 pub(crate) fn index_violation(path: &str, index_fields: &[&str]) -> Self {
1524 Self::new(
1525 ErrorClass::Conflict,
1526 ErrorOrigin::Index,
1527 format!(
1528 "index constraint violation: {path} ({})",
1529 index_fields.join(", ")
1530 ),
1531 )
1532 }
1533}
1534
1535#[derive(Debug, ThisError)]
1543pub enum ErrorDetail {
1544 #[error("{0}")]
1545 Store(StoreError),
1546 #[error("{0}")]
1547 Query(QueryErrorDetail),
1548 }
1555
1556#[derive(Debug, ThisError)]
1564pub enum StoreError {
1565 #[error("key not found: {key}")]
1566 NotFound { key: String },
1567
1568 #[error("store corruption: {message}")]
1569 Corrupt { message: String },
1570
1571 #[error("store invariant violation: {message}")]
1572 InvariantViolation { message: String },
1573
1574 #[error("schema DDL publication race lost for entity: {entity_path}")]
1575 SchemaDdlPublicationRaceLost { entity_path: String },
1576}
1577
1578#[derive(Debug, ThisError)]
1585pub enum QueryErrorDetail {
1586 #[error("numeric overflow")]
1587 NumericOverflow,
1588
1589 #[error("numeric result is not representable")]
1590 NumericNotRepresentable,
1591
1592 #[error("unsupported SQL feature: {feature}")]
1593 UnsupportedSqlFeature { feature: &'static str },
1594
1595 #[error("SQL DDL admission rejected: {error}")]
1596 SchemaDdlAdmission { error: SchemaDdlAdmissionError },
1597}
1598
1599#[derive(Clone, Copy, Debug, Eq, PartialEq, ThisError)]
1608pub enum SchemaDdlAdmissionError {
1609 #[error("missing expected schema version")]
1610 MissingExpectedSchemaVersion,
1611
1612 #[error("missing next schema version")]
1613 MissingNextSchemaVersion,
1614
1615 #[error("stale expected schema version")]
1616 StaleExpectedSchemaVersion,
1617
1618 #[error("invalid expected schema version")]
1619 InvalidExpectedSchemaVersion,
1620
1621 #[error("invalid next schema version")]
1622 InvalidNextSchemaVersion,
1623
1624 #[error("accepted schema changed without version bump")]
1625 AcceptedSchemaChangeWithoutVersionBump,
1626
1627 #[error("empty version bump")]
1628 EmptyVersionBump,
1629
1630 #[error("version gap")]
1631 VersionGap,
1632
1633 #[error("version rollback")]
1634 VersionRollback,
1635
1636 #[error("fingerprint method mismatch")]
1637 FingerprintMethodMismatch,
1638
1639 #[error("unsupported transition class")]
1640 UnsupportedTransitionClass,
1641
1642 #[error("physical runner missing")]
1643 PhysicalRunnerMissing,
1644
1645 #[error("validation failed")]
1646 ValidationFailed,
1647
1648 #[error("publication race lost")]
1649 PublicationRaceLost,
1650}
1651
1652#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1659pub enum ErrorClass {
1660 Corruption,
1661 IncompatiblePersistedFormat,
1662 NotFound,
1663 Internal,
1664 Conflict,
1665 Unsupported,
1666 InvariantViolation,
1667}
1668
1669impl fmt::Display for ErrorClass {
1670 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1671 let label = match self {
1672 Self::Corruption => "corruption",
1673 Self::IncompatiblePersistedFormat => "incompatible_persisted_format",
1674 Self::NotFound => "not_found",
1675 Self::Internal => "internal",
1676 Self::Conflict => "conflict",
1677 Self::Unsupported => "unsupported",
1678 Self::InvariantViolation => "invariant_violation",
1679 };
1680 write!(f, "{label}")
1681 }
1682}
1683
1684#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1691pub enum ErrorOrigin {
1692 Serialize,
1693 Store,
1694 Index,
1695 Identity,
1696 Query,
1697 Planner,
1698 Cursor,
1699 Recovery,
1700 Response,
1701 Executor,
1702 Interface,
1703}
1704
1705impl fmt::Display for ErrorOrigin {
1706 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1707 let label = match self {
1708 Self::Serialize => "serialize",
1709 Self::Store => "store",
1710 Self::Index => "index",
1711 Self::Identity => "identity",
1712 Self::Query => "query",
1713 Self::Planner => "planner",
1714 Self::Cursor => "cursor",
1715 Self::Recovery => "recovery",
1716 Self::Response => "response",
1717 Self::Executor => "executor",
1718 Self::Interface => "interface",
1719 };
1720 write!(f, "{label}")
1721 }
1722}