Skip to main content

icydb_core/error/
mod.rs

1//! Module: error
2//!
3//! Responsibility: module-local ownership and contracts for error.
4//! Does not own: cross-module orchestration outside this module.
5//! Boundary: exposes this module API while keeping implementation details internal.
6
7#[cfg(test)]
8mod tests;
9
10use crate::serialize::{SerializeError, SerializeErrorKind};
11use std::fmt;
12use thiserror::Error as ThisError;
13
14// ============================================================================
15// INTERNAL ERROR TAXONOMY — ARCHITECTURAL CONTRACT
16// ============================================================================
17//
18// This file defines the canonical runtime error classification system for
19// icydb-core. It is the single source of truth for:
20//
21//   • ErrorClass   (semantic domain)
22//   • ErrorOrigin  (subsystem boundary)
23//   • Structured detail payloads
24//   • Canonical constructor entry points
25//
26// -----------------------------------------------------------------------------
27// DESIGN INTENT
28// -----------------------------------------------------------------------------
29//
30// 1. InternalError is a *taxonomy carrier*, not a formatting utility.
31//
32//    - ErrorClass represents semantic meaning (corruption, invariant_violation,
33//      unsupported, etc).
34//    - ErrorOrigin represents the subsystem boundary (store, index, query,
35//      executor, serialize, interface, etc).
36//    - The (class, origin) pair must remain stable and intentional.
37//
38// 2. Call sites MUST prefer canonical constructors.
39//
40//    Do NOT construct errors manually via:
41//        InternalError::new(class, origin, ...)
42//    unless you are defining a new canonical helper here.
43//
44//    If a pattern appears more than once, centralize it here.
45//
46// 3. Constructors in this file must represent real architectural boundaries.
47//
48//    Add a new helper ONLY if it:
49//
50//      • Encodes a cross-cutting invariant,
51//      • Represents a subsystem boundary,
52//      • Or prevents taxonomy drift across call sites.
53//
54//    Do NOT add feature-specific helpers.
55//    Do NOT add one-off formatting helpers.
56//    Do NOT turn this file into a generic message factory.
57//
58// 4. ErrorDetail must align with ErrorOrigin.
59//
60//    If detail is present, it MUST correspond to the origin.
61//    Do not attach mismatched detail variants.
62//
63// 5. Plan-layer errors are NOT runtime failures.
64//
65//    PlanError and CursorPlanError must be translated into
66//    executor/query invariants via the canonical mapping functions.
67//    Do not leak plan-layer error types across execution boundaries.
68//
69// 6. Preserve taxonomy stability.
70//
71//    Do NOT:
72//      • Merge error classes.
73//      • Reclassify corruption as internal.
74//      • Downgrade invariant violations.
75//      • Introduce ambiguous class/origin combinations.
76//
77//    Any change to ErrorClass or ErrorOrigin is an architectural change
78//    and must be reviewed accordingly.
79//
80// -----------------------------------------------------------------------------
81// NON-GOALS
82// -----------------------------------------------------------------------------
83//
84// This is NOT:
85//
86//   • A public API contract.
87//   • A generic error abstraction layer.
88//   • A feature-specific message builder.
89//   • A dumping ground for temporary error conversions.
90//
91// -----------------------------------------------------------------------------
92// MAINTENANCE GUIDELINES
93// -----------------------------------------------------------------------------
94//
95// When modifying this file:
96//
97//   1. Ensure classification semantics remain consistent.
98//   2. Avoid constructor proliferation.
99//   3. Prefer narrow, origin-specific helpers over ad-hoc new(...).
100//   4. Keep formatting minimal and standardized.
101//   5. Keep this file boring and stable.
102//
103// If this file grows rapidly, something is wrong at the call sites.
104//
105// ============================================================================
106
107///
108/// InternalError
109///
110/// Structured runtime error with a stable internal classification.
111/// Not a stable API; intended for internal use and may change without notice.
112///
113
114#[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    /// Optional structured error detail.
122    /// The variant (if present) must correspond to `origin`.
123    pub(crate) detail: Option<ErrorDetail>,
124}
125
126impl InternalError {
127    /// Construct an InternalError with optional origin-specific detail.
128    /// This constructor provides default StoreError details for certain
129    /// (class, origin) combinations but does not guarantee a detail payload.
130    #[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    /// Return the internal error class taxonomy.
158    #[must_use]
159    pub const fn class(&self) -> ErrorClass {
160        self.class
161    }
162
163    /// Return the internal error origin taxonomy.
164    #[must_use]
165    pub const fn origin(&self) -> ErrorOrigin {
166        self.origin
167    }
168
169    /// Return the rendered internal error message.
170    #[must_use]
171    pub fn message(&self) -> &str {
172        &self.message
173    }
174
175    /// Return the optional structured detail payload.
176    #[must_use]
177    pub const fn detail(&self) -> Option<&ErrorDetail> {
178        self.detail.as_ref()
179    }
180
181    /// Consume and return the rendered internal error message.
182    #[must_use]
183    pub fn into_message(self) -> String {
184        self.message
185    }
186
187    /// Construct an error while preserving an explicit class/origin taxonomy pair.
188    #[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    /// Rebuild this error with a new message while preserving class/origin taxonomy.
199    #[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    /// Rebuild this error with a new origin while preserving class/message.
206    ///
207    /// Origin-scoped detail payloads are intentionally dropped when re-origining.
208    #[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    /// Construct an index-origin invariant violation.
215    #[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    /// Construct the canonical index field-count invariant for key building.
226    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    /// Construct the canonical index-key source-field-missing-on-model invariant.
237    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    /// Construct the canonical index-key source-field-missing-on-row invariant.
244    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    /// Construct the canonical index-expression source-type mismatch invariant.
251    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    /// Construct a planner-origin invariant violation with the canonical
263    /// executor-boundary invariant prefix preserved in the message payload.
264    #[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    /// Construct a query-origin invariant violation with the canonical
275    /// executor-boundary invariant prefix preserved in the message payload.
276    #[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    /// Construct a cursor-origin invariant violation with the canonical
287    /// executor-boundary invariant prefix preserved in the message payload.
288    #[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    /// Construct an executor-origin invariant violation.
299    #[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    /// Construct an executor-origin internal error.
310    #[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    /// Construct an executor-origin unsupported error.
317    #[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    /// Construct an executor-origin save-preflight schema invariant.
328    pub(crate) fn mutation_entity_schema_invalid(
329        entity_path: &str,
330        detail: impl fmt::Display,
331    ) -> Self {
332        Self::executor_invariant(format!("entity schema invalid for {entity_path}: {detail}"))
333    }
334
335    /// Construct an executor-origin save-preflight primary-key missing invariant.
336    pub(crate) fn mutation_entity_primary_key_missing(entity_path: &str, field_name: &str) -> Self {
337        Self::executor_invariant(format!(
338            "entity primary key field missing: {entity_path} field={field_name}",
339        ))
340    }
341
342    /// Construct an executor-origin save-preflight primary-key invalid-value invariant.
343    pub(crate) fn mutation_entity_primary_key_invalid_value(
344        entity_path: &str,
345        field_name: &str,
346        value: &crate::value::Value,
347    ) -> Self {
348        Self::executor_invariant(format!(
349            "entity primary key field has invalid value: {entity_path} field={field_name} value={value:?}",
350        ))
351    }
352
353    /// Construct an executor-origin save-preflight primary-key type mismatch invariant.
354    pub(crate) fn mutation_entity_primary_key_type_mismatch(
355        entity_path: &str,
356        field_name: &str,
357        value: &crate::value::Value,
358    ) -> Self {
359        Self::executor_invariant(format!(
360            "entity primary key field type mismatch: {entity_path} field={field_name} value={value:?}",
361        ))
362    }
363
364    /// Construct an executor-origin save-preflight primary-key identity mismatch invariant.
365    pub(crate) fn mutation_entity_primary_key_mismatch(
366        entity_path: &str,
367        field_name: &str,
368        field_value: &crate::value::Value,
369        identity_key: &crate::value::Value,
370    ) -> Self {
371        Self::executor_invariant(format!(
372            "entity primary key mismatch: {entity_path} field={field_name} field_value={field_value:?} id_key={identity_key:?}",
373        ))
374    }
375
376    /// Construct an executor-origin save-preflight field-missing invariant.
377    pub(crate) fn mutation_entity_field_missing(
378        entity_path: &str,
379        field_name: &str,
380        indexed: bool,
381    ) -> Self {
382        let indexed_note = if indexed { " (indexed)" } else { "" };
383
384        Self::executor_invariant(format!(
385            "entity field missing: {entity_path} field={field_name}{indexed_note}",
386        ))
387    }
388
389    /// Construct an executor-origin save-preflight field-type mismatch invariant.
390    pub(crate) fn mutation_entity_field_type_mismatch(
391        entity_path: &str,
392        field_name: &str,
393        value: &crate::value::Value,
394    ) -> Self {
395        Self::executor_invariant(format!(
396            "entity field type mismatch: {entity_path} field={field_name} value={value:?}",
397        ))
398    }
399
400    /// Construct an executor-origin save-preflight decimal-scale unsupported error.
401    pub(crate) fn mutation_decimal_scale_mismatch(
402        entity_path: &str,
403        field_name: &str,
404        expected_scale: impl fmt::Display,
405        actual_scale: impl fmt::Display,
406    ) -> Self {
407        Self::executor_unsupported(format!(
408            "decimal field scale mismatch: {entity_path} field={field_name} expected_scale={expected_scale} actual_scale={actual_scale}",
409        ))
410    }
411
412    /// Construct an executor-origin save-preflight set-encoding invariant.
413    pub(crate) fn mutation_set_field_list_required(entity_path: &str, field_name: &str) -> Self {
414        Self::executor_invariant(format!(
415            "set field must encode as Value::List: {entity_path} field={field_name}",
416        ))
417    }
418
419    /// Construct an executor-origin save-preflight set-canonicality invariant.
420    pub(crate) fn mutation_set_field_not_canonical(entity_path: &str, field_name: &str) -> Self {
421        Self::executor_invariant(format!(
422            "set field must be strictly ordered and deduplicated: {entity_path} field={field_name}",
423        ))
424    }
425
426    /// Construct an executor-origin save-preflight map-encoding invariant.
427    pub(crate) fn mutation_map_field_map_required(entity_path: &str, field_name: &str) -> Self {
428        Self::executor_invariant(format!(
429            "map field must encode as Value::Map: {entity_path} field={field_name}",
430        ))
431    }
432
433    /// Construct an executor-origin save-preflight map-entry invariant.
434    pub(crate) fn mutation_map_field_entries_invalid(
435        entity_path: &str,
436        field_name: &str,
437        detail: impl fmt::Display,
438    ) -> Self {
439        Self::executor_invariant(format!(
440            "map field entries violate map invariants: {entity_path} field={field_name} ({detail})",
441        ))
442    }
443
444    /// Construct an executor-origin save-preflight map-canonicality invariant.
445    pub(crate) fn mutation_map_field_entries_not_canonical(
446        entity_path: &str,
447        field_name: &str,
448    ) -> Self {
449        Self::executor_invariant(format!(
450            "map field entries are not in canonical deterministic order: {entity_path} field={field_name}",
451        ))
452    }
453
454    /// Construct a query-origin scalar page invariant for missing predicate slots.
455    pub(crate) fn scalar_page_predicate_slots_required() -> Self {
456        Self::query_executor_invariant("post-access filtering requires precompiled predicate slots")
457    }
458
459    /// Construct a query-origin scalar page invariant for ordering before filtering.
460    pub(crate) fn scalar_page_ordering_after_filtering_required() -> Self {
461        Self::query_executor_invariant("ordering must run after filtering")
462    }
463
464    /// Construct a query-origin scalar page invariant for missing order at the cursor boundary.
465    pub(crate) fn scalar_page_cursor_boundary_order_required() -> Self {
466        Self::query_executor_invariant("cursor boundary requires ordering")
467    }
468
469    /// Construct a query-origin scalar page invariant for cursor-before-ordering drift.
470    pub(crate) fn scalar_page_cursor_boundary_after_ordering_required() -> Self {
471        Self::query_executor_invariant("cursor boundary must run after ordering")
472    }
473
474    /// Construct a query-origin scalar page invariant for pagination-before-ordering drift.
475    pub(crate) fn scalar_page_pagination_after_ordering_required() -> Self {
476        Self::query_executor_invariant("pagination must run after ordering")
477    }
478
479    /// Construct a query-origin scalar page invariant for delete-limit-before-ordering drift.
480    pub(crate) fn scalar_page_delete_limit_after_ordering_required() -> Self {
481        Self::query_executor_invariant("delete limit must run after ordering")
482    }
483
484    /// Construct a query-origin load-runtime invariant for scalar-mode payload mismatch.
485    pub(crate) fn load_runtime_scalar_payload_required() -> Self {
486        Self::query_executor_invariant("scalar load mode must carry scalar runtime payload")
487    }
488
489    /// Construct a query-origin load-runtime invariant for grouped-mode payload mismatch.
490    pub(crate) fn load_runtime_grouped_payload_required() -> Self {
491        Self::query_executor_invariant("grouped load mode must carry grouped runtime payload")
492    }
493
494    /// Construct a query-origin load-surface invariant for scalar-page payload mismatch.
495    pub(crate) fn load_runtime_scalar_surface_payload_required() -> Self {
496        Self::query_executor_invariant("scalar page load mode must carry scalar runtime payload")
497    }
498
499    /// Construct a query-origin load-surface invariant for grouped-page payload mismatch.
500    pub(crate) fn load_runtime_grouped_surface_payload_required() -> Self {
501        Self::query_executor_invariant("grouped page load mode must carry grouped runtime payload")
502    }
503
504    /// Construct a query-origin load-entrypoint invariant for non-load plans.
505    pub(crate) fn load_executor_load_plan_required() -> Self {
506        Self::query_executor_invariant("load executor requires load plans")
507    }
508
509    /// Construct an executor-origin delete-entrypoint unsupported grouped-mode error.
510    pub(crate) fn delete_executor_grouped_unsupported() -> Self {
511        Self::executor_unsupported("grouped query execution is not yet enabled in this release")
512    }
513
514    /// Construct a query-origin delete-entrypoint invariant for non-delete plans.
515    pub(crate) fn delete_executor_delete_plan_required() -> Self {
516        Self::query_executor_invariant("delete executor requires delete plans")
517    }
518
519    /// Construct a query-origin aggregate kernel invariant for fold-mode contract drift.
520    pub(crate) fn aggregate_fold_mode_terminal_contract_required() -> Self {
521        Self::query_executor_invariant(
522            "aggregate fold mode must match route fold-mode contract for aggregate terminal",
523        )
524    }
525
526    /// Construct a query-origin fast-stream invariant for missing exact key-count observability.
527    pub(crate) fn fast_stream_exact_key_count_required() -> Self {
528        Self::query_executor_invariant("fast-path stream must expose an exact key-count hint")
529    }
530
531    /// Construct a query-origin fast-stream invariant for route kind/request mismatch.
532    pub(crate) fn fast_stream_route_kind_request_match_required() -> Self {
533        Self::query_executor_invariant("fast-stream route kind/request mismatch")
534    }
535
536    /// Construct a query-origin scan invariant for missing index-prefix executable specs.
537    pub(crate) fn secondary_index_prefix_spec_required() -> Self {
538        Self::query_executor_invariant(
539            "index-prefix executable spec must be materialized for index-prefix plans",
540        )
541    }
542
543    /// Construct a query-origin scan invariant for missing index-range executable specs.
544    pub(crate) fn index_range_limit_spec_required() -> Self {
545        Self::query_executor_invariant(
546            "index-range executable spec must be materialized for index-range plans",
547        )
548    }
549
550    /// Construct a query-origin row-decode invariant for missing primary-key layout slots.
551    pub(crate) fn row_layout_primary_key_slot_required() -> Self {
552        Self::query_executor_invariant("row layout missing primary-key slot")
553    }
554
555    /// Construct an executor-origin mutation unsupported error for duplicate atomic save keys.
556    pub(crate) fn mutation_atomic_save_duplicate_key(
557        entity_path: &str,
558        key: impl fmt::Display,
559    ) -> Self {
560        Self::executor_unsupported(format!(
561            "atomic save batch rejected duplicate key: entity={entity_path} key={key}",
562        ))
563    }
564
565    /// Construct an executor-origin mutation invariant for index-store generation drift.
566    pub(crate) fn mutation_index_store_generation_changed(
567        expected_generation: u64,
568        observed_generation: u64,
569    ) -> Self {
570        Self::executor_invariant(format!(
571            "index store generation changed between preflight and apply: expected {expected_generation}, found {observed_generation}",
572        ))
573    }
574
575    /// Build the canonical executor-invariant message prefix.
576    #[must_use]
577    #[cold]
578    #[inline(never)]
579    pub(crate) fn executor_invariant_message(reason: impl Into<String>) -> String {
580        format!("executor invariant violated: {}", reason.into())
581    }
582
583    /// Construct a planner-origin invariant violation.
584    #[cold]
585    #[inline(never)]
586    pub(crate) fn planner_invariant(message: impl Into<String>) -> Self {
587        Self::new(
588            ErrorClass::InvariantViolation,
589            ErrorOrigin::Planner,
590            message.into(),
591        )
592    }
593
594    /// Build the canonical invalid-logical-plan message prefix.
595    #[must_use]
596    pub(crate) fn invalid_logical_plan_message(reason: impl Into<String>) -> String {
597        format!("invalid logical plan: {}", reason.into())
598    }
599
600    /// Construct a planner-origin invariant with the canonical invalid-plan prefix.
601    pub(crate) fn query_invalid_logical_plan(reason: impl Into<String>) -> Self {
602        Self::planner_invariant(Self::invalid_logical_plan_message(reason))
603    }
604
605    /// Construct a query-origin invariant violation.
606    #[cold]
607    #[inline(never)]
608    pub(crate) fn query_invariant(message: impl Into<String>) -> Self {
609        Self::new(
610            ErrorClass::InvariantViolation,
611            ErrorOrigin::Query,
612            message.into(),
613        )
614    }
615
616    /// Construct a store-origin invariant violation.
617    pub(crate) fn store_invariant(message: impl Into<String>) -> Self {
618        Self::new(
619            ErrorClass::InvariantViolation,
620            ErrorOrigin::Store,
621            message.into(),
622        )
623    }
624
625    /// Construct the canonical duplicate runtime-hook entity-tag invariant.
626    pub(crate) fn duplicate_runtime_hooks_for_entity_tag(
627        entity_tag: crate::types::EntityTag,
628    ) -> Self {
629        Self::store_invariant(format!(
630            "duplicate runtime hooks for entity tag '{}'",
631            entity_tag.value()
632        ))
633    }
634
635    /// Construct the canonical duplicate runtime-hook entity-path invariant.
636    pub(crate) fn duplicate_runtime_hooks_for_entity_path(entity_path: &str) -> Self {
637        Self::store_invariant(format!(
638            "duplicate runtime hooks for entity path '{entity_path}'"
639        ))
640    }
641
642    /// Construct a store-origin internal error.
643    #[cold]
644    #[inline(never)]
645    pub(crate) fn store_internal(message: impl Into<String>) -> Self {
646        Self::new(ErrorClass::Internal, ErrorOrigin::Store, message.into())
647    }
648
649    /// Construct the canonical unconfigured commit-memory id internal error.
650    pub(crate) fn commit_memory_id_unconfigured() -> Self {
651        Self::store_internal(
652            "commit memory id is not configured; initialize recovery before commit store access",
653        )
654    }
655
656    /// Construct the canonical commit-memory id mismatch internal error.
657    pub(crate) fn commit_memory_id_mismatch(cached_id: u8, configured_id: u8) -> Self {
658        Self::store_internal(format!(
659            "commit memory id mismatch: cached={cached_id}, configured={configured_id}",
660        ))
661    }
662
663    /// Construct the canonical memory-registry initialization failure for commit memory.
664    pub(crate) fn commit_memory_registry_init_failed(err: impl fmt::Display) -> Self {
665        Self::store_internal(format!("memory registry init failed: {err}"))
666    }
667
668    /// Construct the canonical migration cursor persistence-width internal error.
669    pub(crate) fn migration_next_step_index_u64_required(id: &str, version: u64) -> Self {
670        Self::store_internal(format!(
671            "migration '{id}@{version}' next step index does not fit persisted u64 cursor",
672        ))
673    }
674
675    /// Construct the canonical recovery-integrity totals corruption error.
676    pub(crate) fn recovery_integrity_validation_failed(
677        missing_index_entries: u64,
678        divergent_index_entries: u64,
679        orphan_index_references: u64,
680    ) -> Self {
681        Self::store_corruption(format!(
682            "recovery integrity validation failed: missing_index_entries={missing_index_entries} divergent_index_entries={divergent_index_entries} orphan_index_references={orphan_index_references}",
683        ))
684    }
685
686    /// Construct an index-origin internal error.
687    #[cold]
688    #[inline(never)]
689    pub(crate) fn index_internal(message: impl Into<String>) -> Self {
690        Self::new(ErrorClass::Internal, ErrorOrigin::Index, message.into())
691    }
692
693    /// Construct the canonical missing old entity-key internal error for structural index removal.
694    pub(crate) fn structural_index_removal_entity_key_required() -> Self {
695        Self::index_internal("missing old entity key for structural index removal")
696    }
697
698    /// Construct the canonical missing new entity-key internal error for structural index insertion.
699    pub(crate) fn structural_index_insertion_entity_key_required() -> Self {
700        Self::index_internal("missing new entity key for structural index insertion")
701    }
702
703    /// Construct the canonical missing old entity-key internal error for index commit-op removal.
704    pub(crate) fn index_commit_op_old_entity_key_required() -> Self {
705        Self::index_internal("missing old entity key for index removal")
706    }
707
708    /// Construct the canonical missing new entity-key internal error for index commit-op insertion.
709    pub(crate) fn index_commit_op_new_entity_key_required() -> Self {
710        Self::index_internal("missing new entity key for index insertion")
711    }
712
713    /// Construct a query-origin internal error.
714    #[cfg(test)]
715    pub(crate) fn query_internal(message: impl Into<String>) -> Self {
716        Self::new(ErrorClass::Internal, ErrorOrigin::Query, message.into())
717    }
718
719    /// Construct a query-origin unsupported error.
720    #[cold]
721    #[inline(never)]
722    pub(crate) fn query_unsupported(message: impl Into<String>) -> Self {
723        Self::new(ErrorClass::Unsupported, ErrorOrigin::Query, message.into())
724    }
725
726    /// Construct a serialize-origin internal error.
727    #[cold]
728    #[inline(never)]
729    pub(crate) fn serialize_internal(message: impl Into<String>) -> Self {
730        Self::new(ErrorClass::Internal, ErrorOrigin::Serialize, message.into())
731    }
732
733    /// Construct the canonical persisted-row encode internal error.
734    pub(crate) fn persisted_row_encode_failed(detail: impl fmt::Display) -> Self {
735        Self::serialize_internal(format!("row encode failed: {detail}"))
736    }
737
738    /// Construct the canonical persisted-row field encode internal error.
739    pub(crate) fn persisted_row_field_encode_failed(
740        field_name: &str,
741        detail: impl fmt::Display,
742    ) -> Self {
743        Self::serialize_internal(format!(
744            "row encode failed for field '{field_name}': {detail}",
745        ))
746    }
747
748    /// Construct the canonical bytes(field) value encode internal error.
749    pub(crate) fn bytes_field_value_encode_failed(detail: impl fmt::Display) -> Self {
750        Self::serialize_internal(format!("bytes(field) value encode failed: {detail}"))
751    }
752
753    /// Construct the canonical migration-state serialization failure.
754    pub(crate) fn migration_state_serialize_failed(err: impl fmt::Display) -> Self {
755        Self::serialize_internal(format!("failed to serialize migration state: {err}"))
756    }
757
758    /// Construct a store-origin corruption error.
759    #[cold]
760    #[inline(never)]
761    pub(crate) fn store_corruption(message: impl Into<String>) -> Self {
762        Self::new(ErrorClass::Corruption, ErrorOrigin::Store, message.into())
763    }
764
765    /// Construct the canonical multiple-commit-memory-ids corruption error.
766    pub(crate) fn multiple_commit_memory_ids_registered(ids: impl fmt::Debug) -> Self {
767        Self::store_corruption(format!(
768            "multiple commit marker memory ids registered: {ids:?}"
769        ))
770    }
771
772    /// Construct the canonical persisted migration-step index conversion corruption error.
773    pub(crate) fn migration_persisted_step_index_invalid_usize(
774        id: &str,
775        version: u64,
776        step_index: u64,
777    ) -> Self {
778        Self::store_corruption(format!(
779            "migration '{id}@{version}' persisted step index does not fit runtime usize: {step_index}",
780        ))
781    }
782
783    /// Construct the canonical persisted migration-step index bounds corruption error.
784    pub(crate) fn migration_persisted_step_index_out_of_bounds(
785        id: &str,
786        version: u64,
787        step_index: usize,
788        total_steps: usize,
789    ) -> Self {
790        Self::store_corruption(format!(
791            "migration '{id}@{version}' persisted step index out of bounds: {step_index} > {total_steps}",
792        ))
793    }
794
795    /// Construct a store-origin commit-marker corruption error.
796    pub(crate) fn commit_corruption(detail: impl fmt::Display) -> Self {
797        Self::store_corruption(format!("commit marker corrupted: {detail}"))
798    }
799
800    /// Construct a store-origin commit-marker component corruption error.
801    pub(crate) fn commit_component_corruption(component: &str, detail: impl fmt::Display) -> Self {
802        Self::store_corruption(format!("commit marker {component} corrupted: {detail}"))
803    }
804
805    /// Construct the canonical commit-marker id generation internal error.
806    pub(crate) fn commit_id_generation_failed(detail: impl fmt::Display) -> Self {
807        Self::store_internal(format!("commit id generation failed: {detail}"))
808    }
809
810    /// Construct the canonical commit-marker payload u32-length-limit error.
811    pub(crate) fn commit_marker_payload_exceeds_u32_length_limit(label: &str, len: usize) -> Self {
812        Self::store_unsupported(format!("{label} exceeds u32 length limit: {len} bytes"))
813    }
814
815    /// Construct the canonical commit-marker component invalid-length corruption error.
816    pub(crate) fn commit_component_length_invalid(
817        component: &str,
818        len: usize,
819        expected: impl fmt::Display,
820    ) -> Self {
821        Self::commit_component_corruption(
822            component,
823            format!("invalid length {len}, expected {expected}"),
824        )
825    }
826
827    /// Construct the canonical commit-marker max-size corruption error.
828    pub(crate) fn commit_marker_exceeds_max_size(size: usize, max_size: u32) -> Self {
829        Self::commit_corruption(format!(
830            "commit marker exceeds max size: {size} bytes (limit {max_size})",
831        ))
832    }
833
834    /// Construct the canonical pre-persist commit-marker max-size unsupported error.
835    pub(crate) fn commit_marker_exceeds_max_size_before_persist(
836        size: usize,
837        max_size: u32,
838    ) -> Self {
839        Self::store_unsupported(format!(
840            "commit marker exceeds max size: {size} bytes (limit {max_size})",
841        ))
842    }
843
844    /// Construct the canonical commit-control slot max-size unsupported error.
845    pub(crate) fn commit_control_slot_exceeds_max_size(size: usize, max_size: u32) -> Self {
846        Self::store_unsupported(format!(
847            "commit control slot exceeds max size: {size} bytes (limit {max_size})",
848        ))
849    }
850
851    /// Construct the canonical commit-control marker-bytes length-limit error.
852    pub(crate) fn commit_control_slot_marker_bytes_exceed_u32_length_limit(size: usize) -> Self {
853        Self::store_unsupported(format!(
854            "commit marker bytes exceed u32 length limit: {size} bytes",
855        ))
856    }
857
858    /// Construct the canonical commit-control migration-bytes length-limit error.
859    pub(crate) fn commit_control_slot_migration_bytes_exceed_u32_length_limit(size: usize) -> Self {
860        Self::store_unsupported(format!(
861            "commit migration bytes exceed u32 length limit: {size} bytes",
862        ))
863    }
864
865    /// Construct the canonical startup index-rebuild invalid-data-key corruption error.
866    pub(crate) fn startup_index_rebuild_invalid_data_key(
867        store_path: &str,
868        detail: impl fmt::Display,
869    ) -> Self {
870        Self::store_corruption(format!(
871            "startup index rebuild failed: invalid data key in store '{store_path}' ({detail})",
872        ))
873    }
874
875    /// Construct an index-origin corruption error.
876    #[cold]
877    #[inline(never)]
878    pub(crate) fn index_corruption(message: impl Into<String>) -> Self {
879        Self::new(ErrorClass::Corruption, ErrorOrigin::Index, message.into())
880    }
881
882    /// Construct the canonical unique-validation corruption wrapper.
883    pub(crate) fn index_unique_validation_corruption(
884        entity_path: &str,
885        fields: &str,
886        detail: impl fmt::Display,
887    ) -> Self {
888        Self::index_plan_index_corruption(format!(
889            "index corrupted: {entity_path} ({fields}) -> {detail}",
890        ))
891    }
892
893    /// Construct the canonical structural index-entry corruption wrapper.
894    pub(crate) fn structural_index_entry_corruption(
895        entity_path: &str,
896        fields: &str,
897        detail: impl fmt::Display,
898    ) -> Self {
899        Self::index_plan_index_corruption(format!(
900            "index corrupted: {entity_path} ({fields}) -> {detail}",
901        ))
902    }
903
904    /// Construct the canonical missing new entity-key invariant during unique validation.
905    pub(crate) fn index_unique_validation_entity_key_required() -> Self {
906        Self::index_invariant("missing entity key during unique validation")
907    }
908
909    /// Construct the canonical missing key-component invariant during unique validation.
910    pub(crate) fn index_unique_validation_key_component_missing(
911        component_index: usize,
912        entity_path: &str,
913        fields: &str,
914    ) -> Self {
915        Self::index_invariant(format!(
916            "index key missing component {component_index} during unique validation: {entity_path} ({fields})",
917        ))
918    }
919
920    /// Construct the canonical missing expected key-component invariant during unique validation.
921    pub(crate) fn index_unique_validation_expected_component_missing(
922        component_index: usize,
923        entity_path: &str,
924        fields: &str,
925    ) -> Self {
926        Self::index_invariant(format!(
927            "index key missing expected component {component_index} during unique validation: {entity_path} ({fields})",
928        ))
929    }
930
931    /// Construct the canonical missing primary-key field invariant during unique validation.
932    pub(crate) fn index_unique_validation_primary_key_field_missing(
933        entity_path: &str,
934        primary_key_name: &str,
935    ) -> Self {
936        Self::index_invariant(format!(
937            "entity primary key field missing during unique validation: {entity_path} field={primary_key_name}",
938        ))
939    }
940
941    /// Construct the canonical unique-validation structural row-decode corruption error.
942    pub(crate) fn index_unique_validation_row_deserialize_failed(
943        data_key: impl fmt::Display,
944        source: impl fmt::Display,
945    ) -> Self {
946        Self::index_plan_serialize_corruption(format!(
947            "failed to structurally deserialize row: {data_key} ({source})"
948        ))
949    }
950
951    /// Construct the canonical unique-validation primary-key slot decode corruption error.
952    pub(crate) fn index_unique_validation_primary_key_decode_failed(
953        data_key: impl fmt::Display,
954        source: impl fmt::Display,
955    ) -> Self {
956        Self::index_plan_serialize_corruption(format!(
957            "failed to decode structural primary-key slot: {data_key} ({source})"
958        ))
959    }
960
961    /// Construct the canonical unique-validation stored key rebuild corruption error.
962    pub(crate) fn index_unique_validation_key_rebuild_failed(
963        data_key: impl fmt::Display,
964        entity_path: &str,
965        source: impl fmt::Display,
966    ) -> Self {
967        Self::index_plan_serialize_corruption(format!(
968            "failed to structurally decode unique key row {data_key} for {entity_path}: {source}",
969        ))
970    }
971
972    /// Construct the canonical unique-validation missing-row corruption error.
973    pub(crate) fn index_unique_validation_row_required(data_key: impl fmt::Display) -> Self {
974        Self::index_plan_store_corruption(format!("missing row: {data_key}"))
975    }
976
977    /// Construct the canonical unique-validation row-key invariant error.
978    pub(crate) fn index_unique_validation_row_key_mismatch(
979        entity_path: &str,
980        fields: &str,
981        detail: impl fmt::Display,
982    ) -> Self {
983        Self::index_plan_store_invariant(format!(
984            "index invariant violated: {entity_path} ({fields}) -> {detail}",
985        ))
986    }
987
988    /// Construct the canonical structural index-predicate parse invariant.
989    pub(crate) fn index_predicate_parse_failed(
990        entity_path: &str,
991        index_name: &str,
992        predicate_sql: &str,
993        err: impl fmt::Display,
994    ) -> Self {
995        Self::index_invariant(format!(
996            "index predicate parse failed: {entity_path} ({index_name}) WHERE {predicate_sql} -> {err}",
997        ))
998    }
999
1000    /// Construct the canonical index-only predicate missing-component invariant.
1001    pub(crate) fn index_only_predicate_component_required() -> Self {
1002        Self::index_invariant("index-only predicate program referenced missing index component")
1003    }
1004
1005    /// Construct the canonical index-scan continuation-envelope invariant.
1006    pub(crate) fn index_scan_continuation_anchor_within_envelope_required() -> Self {
1007        Self::index_invariant(
1008            "index-range continuation anchor is outside the requested range envelope",
1009        )
1010    }
1011
1012    /// Construct the canonical index-scan continuation-advancement invariant.
1013    pub(crate) fn index_scan_continuation_advancement_required() -> Self {
1014        Self::index_invariant("index-range continuation scan did not advance beyond the anchor")
1015    }
1016
1017    /// Construct the canonical index-scan key-decode corruption error.
1018    pub(crate) fn index_scan_key_corrupted_during(
1019        context: &'static str,
1020        err: impl fmt::Display,
1021    ) -> Self {
1022        Self::index_corruption(format!("index key corrupted during {context}: {err}"))
1023    }
1024
1025    /// Construct the canonical index-scan missing projection-component invariant.
1026    pub(crate) fn index_projection_component_required(
1027        index_name: &str,
1028        component_index: usize,
1029    ) -> Self {
1030        Self::index_invariant(format!(
1031            "index projection referenced missing component: index='{index_name}' component_index={component_index}",
1032        ))
1033    }
1034
1035    /// Construct the canonical unexpected unique index-entry cardinality corruption error.
1036    pub(crate) fn unique_index_entry_single_key_required() -> Self {
1037        Self::index_corruption("unique index entry contains an unexpected number of keys")
1038    }
1039
1040    /// Construct the canonical scan-time index-entry decode corruption error.
1041    pub(crate) fn index_entry_decode_failed(err: impl fmt::Display) -> Self {
1042        Self::index_corruption(err.to_string())
1043    }
1044
1045    /// Construct a serialize-origin corruption error.
1046    pub(crate) fn serialize_corruption(message: impl Into<String>) -> Self {
1047        Self::new(
1048            ErrorClass::Corruption,
1049            ErrorOrigin::Serialize,
1050            message.into(),
1051        )
1052    }
1053
1054    /// Construct the canonical persisted-row decode corruption error.
1055    pub(crate) fn persisted_row_decode_failed(detail: impl fmt::Display) -> Self {
1056        Self::serialize_corruption(format!("row decode failed: {detail}"))
1057    }
1058
1059    /// Construct the canonical persisted-row field decode corruption error.
1060    pub(crate) fn persisted_row_field_decode_failed(
1061        field_name: &str,
1062        detail: impl fmt::Display,
1063    ) -> Self {
1064        Self::serialize_corruption(format!(
1065            "row decode failed for field '{field_name}': {detail}",
1066        ))
1067    }
1068
1069    /// Construct the canonical persisted-row field-kind decode corruption error.
1070    pub(crate) fn persisted_row_field_kind_decode_failed(
1071        field_name: &str,
1072        field_kind: impl fmt::Debug,
1073        detail: impl fmt::Display,
1074    ) -> Self {
1075        Self::persisted_row_field_decode_failed(
1076            field_name,
1077            format!("kind={field_kind:?}: {detail}"),
1078        )
1079    }
1080
1081    /// Construct the canonical persisted-row scalar-payload length corruption error.
1082    pub(crate) fn persisted_row_field_payload_exact_len_required(
1083        field_name: &str,
1084        payload_kind: &str,
1085        expected_len: usize,
1086    ) -> Self {
1087        let unit = if expected_len == 1 { "byte" } else { "bytes" };
1088
1089        Self::persisted_row_field_decode_failed(
1090            field_name,
1091            format!("{payload_kind} payload must be exactly {expected_len} {unit}"),
1092        )
1093    }
1094
1095    /// Construct the canonical persisted-row scalar-payload empty-body corruption error.
1096    pub(crate) fn persisted_row_field_payload_must_be_empty(
1097        field_name: &str,
1098        payload_kind: &str,
1099    ) -> Self {
1100        Self::persisted_row_field_decode_failed(
1101            field_name,
1102            format!("{payload_kind} payload must be empty"),
1103        )
1104    }
1105
1106    /// Construct the canonical persisted-row scalar-payload invalid-byte corruption error.
1107    pub(crate) fn persisted_row_field_payload_invalid_byte(
1108        field_name: &str,
1109        payload_kind: &str,
1110        value: u8,
1111    ) -> Self {
1112        Self::persisted_row_field_decode_failed(
1113            field_name,
1114            format!("invalid {payload_kind} payload byte {value}"),
1115        )
1116    }
1117
1118    /// Construct the canonical persisted-row scalar-payload non-finite corruption error.
1119    pub(crate) fn persisted_row_field_payload_non_finite(
1120        field_name: &str,
1121        payload_kind: &str,
1122    ) -> Self {
1123        Self::persisted_row_field_decode_failed(
1124            field_name,
1125            format!("{payload_kind} payload is non-finite"),
1126        )
1127    }
1128
1129    /// Construct the canonical persisted-row scalar-payload out-of-range corruption error.
1130    pub(crate) fn persisted_row_field_payload_out_of_range(
1131        field_name: &str,
1132        payload_kind: &str,
1133    ) -> Self {
1134        Self::persisted_row_field_decode_failed(
1135            field_name,
1136            format!("{payload_kind} payload out of range for target type"),
1137        )
1138    }
1139
1140    /// Construct the canonical persisted-row invalid text payload corruption error.
1141    pub(crate) fn persisted_row_field_text_payload_invalid_utf8(
1142        field_name: &str,
1143        detail: impl fmt::Display,
1144    ) -> Self {
1145        Self::persisted_row_field_decode_failed(
1146            field_name,
1147            format!("invalid UTF-8 text payload ({detail})"),
1148        )
1149    }
1150
1151    /// Construct the canonical persisted-row structural slot-lookup invariant.
1152    pub(crate) fn persisted_row_slot_lookup_out_of_bounds(model_path: &str, slot: usize) -> Self {
1153        Self::index_invariant(format!(
1154            "slot lookup outside model bounds during structural row access: model='{model_path}' slot={slot}",
1155        ))
1156    }
1157
1158    /// Construct the canonical persisted-row structural slot-cache invariant.
1159    pub(crate) fn persisted_row_slot_cache_lookup_out_of_bounds(
1160        model_path: &str,
1161        slot: usize,
1162    ) -> Self {
1163        Self::index_invariant(format!(
1164            "slot cache lookup outside model bounds during structural row access: model='{model_path}' slot={slot}",
1165        ))
1166    }
1167
1168    /// Construct the canonical persisted-row primary-key-slot-missing invariant.
1169    pub(crate) fn persisted_row_primary_key_field_missing(model_path: &str) -> Self {
1170        Self::index_invariant(format!(
1171            "entity primary key field missing during structural row validation: {model_path}",
1172        ))
1173    }
1174
1175    /// Construct the canonical persisted-row primary-key decode corruption error.
1176    pub(crate) fn persisted_row_primary_key_not_storage_encodable(
1177        data_key: impl fmt::Display,
1178        detail: impl fmt::Display,
1179    ) -> Self {
1180        Self::persisted_row_decode_failed(format!(
1181            "primary-key value is not storage-key encodable: {data_key} ({detail})",
1182        ))
1183    }
1184
1185    /// Construct the canonical persisted-row missing primary-key slot corruption error.
1186    pub(crate) fn persisted_row_primary_key_slot_missing(data_key: impl fmt::Display) -> Self {
1187        Self::persisted_row_decode_failed(format!(
1188            "missing primary-key slot while validating {data_key}",
1189        ))
1190    }
1191
1192    /// Construct the canonical persisted-row key mismatch corruption error.
1193    pub(crate) fn persisted_row_key_mismatch(
1194        expected_key: impl fmt::Display,
1195        found_key: impl fmt::Display,
1196    ) -> Self {
1197        Self::store_corruption(format!(
1198            "row key mismatch: expected {expected_key}, found {found_key}",
1199        ))
1200    }
1201
1202    /// Construct the canonical row-decoder missing-field corruption error.
1203    pub(crate) fn row_decode_declared_field_missing(field_name: &str) -> Self {
1204        Self::persisted_row_decode_failed(format!("missing declared field `{field_name}`"))
1205    }
1206
1207    /// Construct the canonical row-decoder field-decode corruption error.
1208    pub(crate) fn row_decode_field_decode_failed(
1209        field_name: &str,
1210        field_kind: impl fmt::Debug,
1211        detail: impl fmt::Display,
1212    ) -> Self {
1213        Self::serialize_corruption(format!(
1214            "row decode failed for field '{field_name}' kind={field_kind:?}: {detail}",
1215        ))
1216    }
1217
1218    /// Construct the canonical row-decoder missing primary-key slot corruption error.
1219    pub(crate) fn row_decode_primary_key_slot_missing() -> Self {
1220        Self::persisted_row_decode_failed("missing primary-key slot value")
1221    }
1222
1223    /// Construct the canonical row-decoder primary-key encoding corruption error.
1224    pub(crate) fn row_decode_primary_key_not_storage_encodable(detail: impl fmt::Display) -> Self {
1225        Self::persisted_row_decode_failed(format!(
1226            "primary-key value is not storage-key encodable: {detail}",
1227        ))
1228    }
1229
1230    /// Construct the canonical row-decoder key-mismatch corruption error.
1231    pub(crate) fn row_decode_key_mismatch(
1232        expected_key: impl fmt::Display,
1233        found_key: impl fmt::Display,
1234    ) -> Self {
1235        Self::persisted_row_key_mismatch(expected_key, found_key)
1236    }
1237
1238    /// Construct the canonical data-key entity mismatch corruption error.
1239    pub(crate) fn data_key_entity_mismatch(
1240        expected: impl fmt::Display,
1241        found: impl fmt::Display,
1242    ) -> Self {
1243        Self::store_corruption(format!(
1244            "data key entity mismatch: expected {expected}, found {found}",
1245        ))
1246    }
1247
1248    /// Construct the canonical data-key primary-key decode corruption error.
1249    pub(crate) fn data_key_primary_key_decode_failed(value: impl fmt::Debug) -> Self {
1250        Self::store_corruption(format!("data key primary key decode failed: {value:?}",))
1251    }
1252
1253    /// Construct the canonical reverse-index ordinal overflow internal error.
1254    pub(crate) fn reverse_index_ordinal_overflow(
1255        source_path: &str,
1256        field_name: &str,
1257        target_path: &str,
1258        detail: impl fmt::Display,
1259    ) -> Self {
1260        Self::index_internal(format!(
1261            "reverse index ordinal overflow: source={source_path} field={field_name} target={target_path} ({detail})",
1262        ))
1263    }
1264
1265    /// Construct the canonical reverse-index entry corruption error.
1266    pub(crate) fn reverse_index_entry_corrupted(
1267        source_path: &str,
1268        field_name: &str,
1269        target_path: &str,
1270        index_key: impl fmt::Debug,
1271        detail: impl fmt::Display,
1272    ) -> Self {
1273        Self::index_corruption(format!(
1274            "reverse index entry corrupted: source={source_path} field={field_name} target={target_path} key={index_key:?} ({detail})",
1275        ))
1276    }
1277
1278    /// Construct the canonical reverse-index entry encode unsupported error.
1279    pub(crate) fn reverse_index_entry_encode_failed(
1280        source_path: &str,
1281        field_name: &str,
1282        target_path: &str,
1283        detail: impl fmt::Display,
1284    ) -> Self {
1285        Self::index_unsupported(format!(
1286            "reverse index entry encoding failed: source={source_path} field={field_name} target={target_path} ({detail})",
1287        ))
1288    }
1289
1290    /// Construct the canonical relation-target store missing internal error.
1291    pub(crate) fn relation_target_store_missing(
1292        source_path: &str,
1293        field_name: &str,
1294        target_path: &str,
1295        store_path: &str,
1296        detail: impl fmt::Display,
1297    ) -> Self {
1298        Self::executor_internal(format!(
1299            "relation target store missing: source={source_path} field={field_name} target={target_path} store={store_path} ({detail})",
1300        ))
1301    }
1302
1303    /// Construct the canonical relation-target key decode corruption error.
1304    pub(crate) fn relation_target_key_decode_failed(
1305        context_label: &str,
1306        source_path: &str,
1307        field_name: &str,
1308        target_path: &str,
1309        detail: impl fmt::Display,
1310    ) -> Self {
1311        Self::identity_corruption(format!(
1312            "{context_label}: source={source_path} field={field_name} target={target_path} ({detail})",
1313        ))
1314    }
1315
1316    /// Construct the canonical relation-target entity mismatch corruption error.
1317    pub(crate) fn relation_target_entity_mismatch(
1318        context_label: &str,
1319        source_path: &str,
1320        field_name: &str,
1321        target_path: &str,
1322        target_entity_name: &str,
1323        expected_tag: impl fmt::Display,
1324        actual_tag: impl fmt::Display,
1325    ) -> Self {
1326        Self::store_corruption(format!(
1327            "{context_label}: source={source_path} field={field_name} target={target_path} expected={target_entity_name} (tag={expected_tag}) actual_tag={actual_tag}",
1328        ))
1329    }
1330
1331    /// Construct the canonical relation-source row missing-field corruption error.
1332    pub(crate) fn relation_source_row_missing_field(
1333        source_path: &str,
1334        field_name: &str,
1335        target_path: &str,
1336    ) -> Self {
1337        Self::serialize_corruption(format!(
1338            "relation source row decode failed: missing field: source={source_path} field={field_name} target={target_path}",
1339        ))
1340    }
1341
1342    /// Construct the canonical relation-source row decode corruption error.
1343    pub(crate) fn relation_source_row_decode_failed(
1344        source_path: &str,
1345        field_name: &str,
1346        target_path: &str,
1347        detail: impl fmt::Display,
1348    ) -> Self {
1349        Self::serialize_corruption(format!(
1350            "relation source row decode failed: source={source_path} field={field_name} target={target_path} ({detail})",
1351        ))
1352    }
1353
1354    /// Construct the canonical relation-source unsupported scalar relation-key corruption error.
1355    pub(crate) fn relation_source_row_unsupported_scalar_relation_key(
1356        source_path: &str,
1357        field_name: &str,
1358        target_path: &str,
1359    ) -> Self {
1360        Self::serialize_corruption(format!(
1361            "relation source row decode failed: unsupported scalar relation key: source={source_path} field={field_name} target={target_path}",
1362        ))
1363    }
1364
1365    /// Construct the canonical invalid strong-relation field-kind corruption error.
1366    pub(crate) fn relation_source_row_invalid_field_kind(field_kind: impl fmt::Debug) -> Self {
1367        Self::serialize_corruption(format!(
1368            "invalid strong relation field kind during structural decode: {field_kind:?}"
1369        ))
1370    }
1371
1372    /// Construct the canonical unsupported strong-relation key-kind corruption error.
1373    pub(crate) fn relation_source_row_unsupported_key_kind(field_kind: impl fmt::Debug) -> Self {
1374        Self::serialize_corruption(format!(
1375            "unsupported strong relation key kind during structural decode: {field_kind:?}"
1376        ))
1377    }
1378
1379    /// Construct the canonical reverse-index relation-target decode invariant failure.
1380    pub(crate) fn reverse_index_relation_target_decode_invariant_violated(
1381        source_path: &str,
1382        field_name: &str,
1383        target_path: &str,
1384    ) -> Self {
1385        Self::executor_internal(format!(
1386            "relation target decode invariant violated while preparing reverse index: source={source_path} field={field_name} target={target_path}",
1387        ))
1388    }
1389
1390    /// Construct the canonical covering-component empty-payload corruption error.
1391    pub(crate) fn bytes_covering_component_payload_empty() -> Self {
1392        Self::index_corruption("index component payload is empty during covering projection decode")
1393    }
1394
1395    /// Construct the canonical covering-component truncated bool corruption error.
1396    pub(crate) fn bytes_covering_bool_payload_truncated() -> Self {
1397        Self::index_corruption("bool covering component payload is truncated")
1398    }
1399
1400    /// Construct the canonical covering-component invalid-length corruption error.
1401    pub(crate) fn bytes_covering_component_payload_invalid_length(payload_kind: &str) -> Self {
1402        Self::index_corruption(format!(
1403            "{payload_kind} covering component payload has invalid length"
1404        ))
1405    }
1406
1407    /// Construct the canonical covering-component invalid-bool corruption error.
1408    pub(crate) fn bytes_covering_bool_payload_invalid_value() -> Self {
1409        Self::index_corruption("bool covering component payload has invalid value")
1410    }
1411
1412    /// Construct the canonical covering-component invalid text terminator corruption error.
1413    pub(crate) fn bytes_covering_text_payload_invalid_terminator() -> Self {
1414        Self::index_corruption("text covering component payload has invalid terminator")
1415    }
1416
1417    /// Construct the canonical covering-component trailing-text corruption error.
1418    pub(crate) fn bytes_covering_text_payload_trailing_bytes() -> Self {
1419        Self::index_corruption("text covering component payload contains trailing bytes")
1420    }
1421
1422    /// Construct the canonical covering-component invalid-UTF-8 text corruption error.
1423    pub(crate) fn bytes_covering_text_payload_invalid_utf8() -> Self {
1424        Self::index_corruption("text covering component payload is not valid UTF-8")
1425    }
1426
1427    /// Construct the canonical covering-component invalid text escape corruption error.
1428    pub(crate) fn bytes_covering_text_payload_invalid_escape_byte() -> Self {
1429        Self::index_corruption("text covering component payload has invalid escape byte")
1430    }
1431
1432    /// Construct the canonical covering-component missing text terminator corruption error.
1433    pub(crate) fn bytes_covering_text_payload_missing_terminator() -> Self {
1434        Self::index_corruption("text covering component payload is missing terminator")
1435    }
1436
1437    /// Construct the canonical missing persisted-field decode error.
1438    #[must_use]
1439    pub fn missing_persisted_slot(field_name: &'static str) -> Self {
1440        Self::serialize_corruption(format!(
1441            "row decode failed: missing required field '{field_name}'",
1442        ))
1443    }
1444
1445    /// Construct an identity-origin corruption error.
1446    pub(crate) fn identity_corruption(message: impl Into<String>) -> Self {
1447        Self::new(
1448            ErrorClass::Corruption,
1449            ErrorOrigin::Identity,
1450            message.into(),
1451        )
1452    }
1453
1454    /// Construct a store-origin unsupported error.
1455    #[cold]
1456    #[inline(never)]
1457    pub(crate) fn store_unsupported(message: impl Into<String>) -> Self {
1458        Self::new(ErrorClass::Unsupported, ErrorOrigin::Store, message.into())
1459    }
1460
1461    /// Construct the canonical empty migration label unsupported error.
1462    pub(crate) fn migration_label_empty(label: &str) -> Self {
1463        Self::store_unsupported(format!("{label} cannot be empty"))
1464    }
1465
1466    /// Construct the canonical empty migration-step row-op set unsupported error.
1467    pub(crate) fn migration_step_row_ops_required(name: &str) -> Self {
1468        Self::store_unsupported(format!(
1469            "migration step '{name}' must include at least one row op",
1470        ))
1471    }
1472
1473    /// Construct the canonical invalid migration-plan version unsupported error.
1474    pub(crate) fn migration_plan_version_required(id: &str) -> Self {
1475        Self::store_unsupported(format!("migration plan '{id}' version must be > 0",))
1476    }
1477
1478    /// Construct the canonical empty migration-plan steps unsupported error.
1479    pub(crate) fn migration_plan_steps_required(id: &str) -> Self {
1480        Self::store_unsupported(format!(
1481            "migration plan '{id}' must include at least one step",
1482        ))
1483    }
1484
1485    /// Construct the canonical migration cursor out-of-bounds unsupported error.
1486    pub(crate) fn migration_cursor_out_of_bounds(
1487        id: &str,
1488        version: u64,
1489        next_step: usize,
1490        total_steps: usize,
1491    ) -> Self {
1492        Self::store_unsupported(format!(
1493            "migration '{id}@{version}' cursor out of bounds: next_step={next_step} total_steps={total_steps}",
1494        ))
1495    }
1496
1497    /// Construct the canonical max-steps-required migration execution error.
1498    pub(crate) fn migration_execution_requires_max_steps(id: &str) -> Self {
1499        Self::store_unsupported(format!("migration '{id}' execution requires max_steps > 0",))
1500    }
1501
1502    /// Construct the canonical in-progress migration-plan conflict error.
1503    pub(crate) fn migration_in_progress_conflict(
1504        requested_id: &str,
1505        requested_version: u64,
1506        active_id: &str,
1507        active_version: u64,
1508    ) -> Self {
1509        Self::store_unsupported(format!(
1510            "migration '{requested_id}@{requested_version}' cannot execute while migration '{active_id}@{active_version}' is in progress",
1511        ))
1512    }
1513
1514    /// Construct the canonical unsupported persisted entity-tag store error.
1515    pub(crate) fn unsupported_entity_tag_in_data_store(
1516        entity_tag: crate::types::EntityTag,
1517    ) -> Self {
1518        Self::store_unsupported(format!(
1519            "unsupported entity tag in data store: '{}'",
1520            entity_tag.value()
1521        ))
1522    }
1523
1524    /// Construct the canonical configured-vs-registered commit-memory id mismatch error.
1525    pub(crate) fn configured_commit_memory_id_mismatch(
1526        configured_id: u8,
1527        registered_id: u8,
1528    ) -> Self {
1529        Self::store_unsupported(format!(
1530            "configured commit memory id {configured_id} does not match existing commit marker id {registered_id}",
1531        ))
1532    }
1533
1534    /// Construct the canonical occupied commit-memory id unsupported error.
1535    pub(crate) fn commit_memory_id_already_registered(memory_id: u8, label: &str) -> Self {
1536        Self::store_unsupported(format!(
1537            "configured commit memory id {memory_id} is already registered as '{label}'",
1538        ))
1539    }
1540
1541    /// Construct the canonical out-of-range commit-memory id unsupported error.
1542    pub(crate) fn commit_memory_id_outside_reserved_ranges(memory_id: u8) -> Self {
1543        Self::store_unsupported(format!(
1544            "configured commit memory id {memory_id} is outside reserved ranges",
1545        ))
1546    }
1547
1548    /// Construct the canonical commit-memory id registration failure.
1549    pub(crate) fn commit_memory_id_registration_failed(err: impl fmt::Display) -> Self {
1550        Self::store_internal(format!("commit memory id registration failed: {err}"))
1551    }
1552
1553    /// Construct an index-origin unsupported error.
1554    pub(crate) fn index_unsupported(message: impl Into<String>) -> Self {
1555        Self::new(ErrorClass::Unsupported, ErrorOrigin::Index, message.into())
1556    }
1557
1558    /// Construct the canonical index-key component size-limit unsupported error.
1559    pub(crate) fn index_component_exceeds_max_size(
1560        key_item: impl fmt::Display,
1561        len: usize,
1562        max_component_size: usize,
1563    ) -> Self {
1564        Self::index_unsupported(format!(
1565            "index component exceeds max size: key item '{key_item}' -> {len} bytes (limit {max_component_size})",
1566        ))
1567    }
1568
1569    /// Construct the canonical index-entry max-keys unsupported error during commit encoding.
1570    pub(crate) fn index_entry_exceeds_max_keys(
1571        entity_path: &str,
1572        fields: &str,
1573        keys: usize,
1574    ) -> Self {
1575        Self::index_unsupported(format!(
1576            "index entry exceeds max keys: {entity_path} ({fields}) -> {keys} keys",
1577        ))
1578    }
1579
1580    /// Construct the canonical duplicate-key invariant during commit entry encoding.
1581    pub(crate) fn index_entry_duplicate_keys_unexpected(entity_path: &str, fields: &str) -> Self {
1582        Self::index_invariant(format!(
1583            "index entry unexpectedly contains duplicate keys: {entity_path} ({fields})",
1584        ))
1585    }
1586
1587    /// Construct the canonical index-entry key-encoding unsupported error during commit encoding.
1588    pub(crate) fn index_entry_key_encoding_failed(
1589        entity_path: &str,
1590        fields: &str,
1591        err: impl fmt::Display,
1592    ) -> Self {
1593        Self::index_unsupported(format!(
1594            "index entry key encoding failed: {entity_path} ({fields}) -> {err}",
1595        ))
1596    }
1597
1598    /// Construct a serialize-origin unsupported error.
1599    pub(crate) fn serialize_unsupported(message: impl Into<String>) -> Self {
1600        Self::new(
1601            ErrorClass::Unsupported,
1602            ErrorOrigin::Serialize,
1603            message.into(),
1604        )
1605    }
1606
1607    /// Construct a cursor-origin unsupported error.
1608    pub(crate) fn cursor_unsupported(message: impl Into<String>) -> Self {
1609        Self::new(ErrorClass::Unsupported, ErrorOrigin::Cursor, message.into())
1610    }
1611
1612    /// Construct a serialize-origin incompatible persisted-format error.
1613    pub(crate) fn serialize_incompatible_persisted_format(message: impl Into<String>) -> Self {
1614        Self::new(
1615            ErrorClass::IncompatiblePersistedFormat,
1616            ErrorOrigin::Serialize,
1617            message.into(),
1618        )
1619    }
1620
1621    /// Construct the canonical persisted-payload decode failure mapping for one
1622    /// DB-owned serialized payload boundary.
1623    pub(crate) fn serialize_payload_decode_failed(
1624        source: SerializeError,
1625        payload_label: &'static str,
1626    ) -> Self {
1627        match source {
1628            // DB codec only decodes engine-owned persisted payloads.
1629            // Size-limit breaches indicate persisted bytes violate DB storage policy.
1630            SerializeError::DeserializeSizeLimitExceeded { len, max_bytes } => {
1631                Self::serialize_corruption(format!(
1632                    "{payload_label} decode failed: payload size {len} exceeds limit {max_bytes}"
1633                ))
1634            }
1635            SerializeError::Deserialize(_) => Self::serialize_corruption(format!(
1636                "{payload_label} decode failed: {}",
1637                SerializeErrorKind::Deserialize
1638            )),
1639            SerializeError::Serialize(_) => Self::serialize_corruption(format!(
1640                "{payload_label} decode failed: {}",
1641                SerializeErrorKind::Serialize
1642            )),
1643        }
1644    }
1645
1646    /// Construct a query-origin unsupported error preserving one SQL parser
1647    /// unsupported-feature label in structured error detail.
1648    #[cfg(feature = "sql")]
1649    pub(crate) fn query_unsupported_sql_feature(feature: &'static str) -> Self {
1650        let message = format!(
1651            "SQL query is not executable in this release: unsupported SQL feature: {feature}"
1652        );
1653
1654        Self {
1655            class: ErrorClass::Unsupported,
1656            origin: ErrorOrigin::Query,
1657            message,
1658            detail: Some(ErrorDetail::Query(
1659                QueryErrorDetail::UnsupportedSqlFeature { feature },
1660            )),
1661        }
1662    }
1663
1664    pub fn store_not_found(key: impl Into<String>) -> Self {
1665        let key = key.into();
1666
1667        Self {
1668            class: ErrorClass::NotFound,
1669            origin: ErrorOrigin::Store,
1670            message: format!("data key not found: {key}"),
1671            detail: Some(ErrorDetail::Store(StoreError::NotFound { key })),
1672        }
1673    }
1674
1675    /// Construct a standardized unsupported-entity-path error.
1676    pub fn unsupported_entity_path(path: impl Into<String>) -> Self {
1677        let path = path.into();
1678
1679        Self::new(
1680            ErrorClass::Unsupported,
1681            ErrorOrigin::Store,
1682            format!("unsupported entity path: '{path}'"),
1683        )
1684    }
1685
1686    #[must_use]
1687    pub const fn is_not_found(&self) -> bool {
1688        matches!(
1689            self.detail,
1690            Some(ErrorDetail::Store(StoreError::NotFound { .. }))
1691        )
1692    }
1693
1694    #[must_use]
1695    pub fn display_with_class(&self) -> String {
1696        format!("{}:{}: {}", self.origin, self.class, self.message)
1697    }
1698
1699    /// Construct an index-plan corruption error with a canonical prefix.
1700    #[cold]
1701    #[inline(never)]
1702    pub(crate) fn index_plan_corruption(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1703        let message = message.into();
1704        Self::new(
1705            ErrorClass::Corruption,
1706            origin,
1707            format!("corruption detected ({origin}): {message}"),
1708        )
1709    }
1710
1711    /// Construct an index-plan corruption error for index-origin failures.
1712    #[cold]
1713    #[inline(never)]
1714    pub(crate) fn index_plan_index_corruption(message: impl Into<String>) -> Self {
1715        Self::index_plan_corruption(ErrorOrigin::Index, message)
1716    }
1717
1718    /// Construct an index-plan corruption error for store-origin failures.
1719    #[cold]
1720    #[inline(never)]
1721    pub(crate) fn index_plan_store_corruption(message: impl Into<String>) -> Self {
1722        Self::index_plan_corruption(ErrorOrigin::Store, message)
1723    }
1724
1725    /// Construct an index-plan corruption error for serialize-origin failures.
1726    #[cold]
1727    #[inline(never)]
1728    pub(crate) fn index_plan_serialize_corruption(message: impl Into<String>) -> Self {
1729        Self::index_plan_corruption(ErrorOrigin::Serialize, message)
1730    }
1731
1732    /// Construct an index-plan invariant violation error with a canonical prefix.
1733    pub(crate) fn index_plan_invariant(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1734        let message = message.into();
1735        Self::new(
1736            ErrorClass::InvariantViolation,
1737            origin,
1738            format!("invariant violation detected ({origin}): {message}"),
1739        )
1740    }
1741
1742    /// Construct an index-plan invariant violation error for store-origin failures.
1743    pub(crate) fn index_plan_store_invariant(message: impl Into<String>) -> Self {
1744        Self::index_plan_invariant(ErrorOrigin::Store, message)
1745    }
1746
1747    /// Construct an index uniqueness violation conflict error.
1748    pub(crate) fn index_violation(path: &str, index_fields: &[&str]) -> Self {
1749        Self::new(
1750            ErrorClass::Conflict,
1751            ErrorOrigin::Index,
1752            format!(
1753                "index constraint violation: {path} ({})",
1754                index_fields.join(", ")
1755            ),
1756        )
1757    }
1758}
1759
1760///
1761/// ErrorDetail
1762///
1763/// Structured, origin-specific error detail carried by [`InternalError`].
1764/// This enum is intentionally extensible.
1765///
1766
1767#[derive(Debug, ThisError)]
1768pub enum ErrorDetail {
1769    #[error("{0}")]
1770    Store(StoreError),
1771    #[error("{0}")]
1772    Query(QueryErrorDetail),
1773    // Future-proofing:
1774    // #[error("{0}")]
1775    // Index(IndexError),
1776    //
1777    // #[error("{0}")]
1778    // Executor(ExecutorErrorDetail),
1779}
1780
1781///
1782/// StoreError
1783///
1784/// Store-specific structured error detail.
1785/// Never returned directly; always wrapped in [`ErrorDetail::Store`].
1786///
1787
1788#[derive(Debug, ThisError)]
1789pub enum StoreError {
1790    #[error("key not found: {key}")]
1791    NotFound { key: String },
1792
1793    #[error("store corruption: {message}")]
1794    Corrupt { message: String },
1795
1796    #[error("store invariant violation: {message}")]
1797    InvariantViolation { message: String },
1798}
1799
1800///
1801/// QueryErrorDetail
1802///
1803/// Query-origin structured error detail payload.
1804///
1805
1806#[derive(Debug, ThisError)]
1807pub enum QueryErrorDetail {
1808    #[error("unsupported SQL feature: {feature}")]
1809    UnsupportedSqlFeature { feature: &'static str },
1810}
1811
1812///
1813/// ErrorClass
1814/// Internal error taxonomy for runtime classification.
1815/// Not a stable API; may change without notice.
1816///
1817
1818#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1819pub enum ErrorClass {
1820    Corruption,
1821    IncompatiblePersistedFormat,
1822    NotFound,
1823    Internal,
1824    Conflict,
1825    Unsupported,
1826    InvariantViolation,
1827}
1828
1829impl fmt::Display for ErrorClass {
1830    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1831        let label = match self {
1832            Self::Corruption => "corruption",
1833            Self::IncompatiblePersistedFormat => "incompatible_persisted_format",
1834            Self::NotFound => "not_found",
1835            Self::Internal => "internal",
1836            Self::Conflict => "conflict",
1837            Self::Unsupported => "unsupported",
1838            Self::InvariantViolation => "invariant_violation",
1839        };
1840        write!(f, "{label}")
1841    }
1842}
1843
1844///
1845/// ErrorOrigin
1846/// Internal origin taxonomy for runtime classification.
1847/// Not a stable API; may change without notice.
1848///
1849
1850#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1851pub enum ErrorOrigin {
1852    Serialize,
1853    Store,
1854    Index,
1855    Identity,
1856    Query,
1857    Planner,
1858    Cursor,
1859    Recovery,
1860    Response,
1861    Executor,
1862    Interface,
1863}
1864
1865impl fmt::Display for ErrorOrigin {
1866    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1867        let label = match self {
1868            Self::Serialize => "serialize",
1869            Self::Store => "store",
1870            Self::Index => "index",
1871            Self::Identity => "identity",
1872            Self::Query => "query",
1873            Self::Planner => "planner",
1874            Self::Cursor => "cursor",
1875            Self::Recovery => "recovery",
1876            Self::Response => "response",
1877            Self::Executor => "executor",
1878            Self::Interface => "interface",
1879        };
1880        write!(f, "{label}")
1881    }
1882}