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 primary-key missing invariant.
328    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    /// Construct an executor-origin save-preflight primary-key invalid-value invariant.
335    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    /// Construct an executor-origin save-preflight primary-key type mismatch invariant.
346    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    /// Construct an executor-origin save-preflight primary-key identity mismatch invariant.
357    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    /// Construct an executor-origin save-preflight field-missing invariant.
369    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    /// Construct an executor-origin save-preflight field-type mismatch invariant.
382    pub(crate) fn mutation_entity_field_type_mismatch(
383        entity_path: &str,
384        field_name: &str,
385        value: &crate::value::Value,
386    ) -> Self {
387        Self::executor_invariant(format!(
388            "entity field type mismatch: {entity_path} field={field_name} value={value:?}",
389        ))
390    }
391
392    /// Construct an executor-origin mutation result invariant.
393    ///
394    /// This constructor lands ahead of the public structural mutation surface,
395    /// so the library target may not route through it until that caller exists.
396    pub(crate) fn mutation_structural_after_image_invalid(
397        entity_path: &str,
398        data_key: impl fmt::Display,
399        detail: impl AsRef<str>,
400    ) -> Self {
401        Self::executor_invariant(format!(
402            "mutation result is invalid: {entity_path} key={data_key} ({})",
403            detail.as_ref(),
404        ))
405    }
406
407    /// Construct an executor-origin mutation unknown-field invariant.
408    pub(crate) fn mutation_structural_field_unknown(entity_path: &str, field_name: &str) -> Self {
409        Self::executor_invariant(format!(
410            "mutation field not found: {entity_path} field={field_name}",
411        ))
412    }
413
414    /// Construct an executor-origin save-preflight decimal-scale unsupported error.
415    pub(crate) fn mutation_decimal_scale_mismatch(
416        entity_path: &str,
417        field_name: &str,
418        expected_scale: impl fmt::Display,
419        actual_scale: impl fmt::Display,
420    ) -> Self {
421        Self::executor_unsupported(format!(
422            "decimal field scale mismatch: {entity_path} field={field_name} expected_scale={expected_scale} actual_scale={actual_scale}",
423        ))
424    }
425
426    /// Construct an executor-origin save-preflight set-encoding invariant.
427    pub(crate) fn mutation_set_field_list_required(entity_path: &str, field_name: &str) -> Self {
428        Self::executor_invariant(format!(
429            "set field must encode as Value::List: {entity_path} field={field_name}",
430        ))
431    }
432
433    /// Construct an executor-origin save-preflight set-canonicality invariant.
434    pub(crate) fn mutation_set_field_not_canonical(entity_path: &str, field_name: &str) -> Self {
435        Self::executor_invariant(format!(
436            "set field must be strictly ordered and deduplicated: {entity_path} field={field_name}",
437        ))
438    }
439
440    /// Construct an executor-origin save-preflight map-encoding invariant.
441    pub(crate) fn mutation_map_field_map_required(entity_path: &str, field_name: &str) -> Self {
442        Self::executor_invariant(format!(
443            "map field must encode as Value::Map: {entity_path} field={field_name}",
444        ))
445    }
446
447    /// Construct an executor-origin save-preflight map-entry invariant.
448    pub(crate) fn mutation_map_field_entries_invalid(
449        entity_path: &str,
450        field_name: &str,
451        detail: impl fmt::Display,
452    ) -> Self {
453        Self::executor_invariant(format!(
454            "map field entries violate map invariants: {entity_path} field={field_name} ({detail})",
455        ))
456    }
457
458    /// Construct an executor-origin save-preflight map-canonicality invariant.
459    pub(crate) fn mutation_map_field_entries_not_canonical(
460        entity_path: &str,
461        field_name: &str,
462    ) -> Self {
463        Self::executor_invariant(format!(
464            "map field entries are not in canonical deterministic order: {entity_path} field={field_name}",
465        ))
466    }
467
468    /// Construct a query-origin scalar page invariant for missing predicate slots.
469    pub(crate) fn scalar_page_predicate_slots_required() -> Self {
470        Self::query_executor_invariant("post-access filtering requires precompiled predicate slots")
471    }
472
473    /// Construct a query-origin scalar page invariant for ordering before filtering.
474    pub(crate) fn scalar_page_ordering_after_filtering_required() -> Self {
475        Self::query_executor_invariant("ordering must run after filtering")
476    }
477
478    /// Construct a query-origin scalar page invariant for missing order at the cursor boundary.
479    pub(crate) fn scalar_page_cursor_boundary_order_required() -> Self {
480        Self::query_executor_invariant("cursor boundary requires ordering")
481    }
482
483    /// Construct a query-origin scalar page invariant for cursor-before-ordering drift.
484    pub(crate) fn scalar_page_cursor_boundary_after_ordering_required() -> Self {
485        Self::query_executor_invariant("cursor boundary must run after ordering")
486    }
487
488    /// Construct a query-origin scalar page invariant for pagination-before-ordering drift.
489    pub(crate) fn scalar_page_pagination_after_ordering_required() -> Self {
490        Self::query_executor_invariant("pagination must run after ordering")
491    }
492
493    /// Construct a query-origin scalar page invariant for delete-limit-before-ordering drift.
494    pub(crate) fn scalar_page_delete_limit_after_ordering_required() -> Self {
495        Self::query_executor_invariant("delete limit must run after ordering")
496    }
497
498    /// Construct a query-origin load-runtime invariant for scalar-mode payload mismatch.
499    pub(crate) fn load_runtime_scalar_payload_required() -> Self {
500        Self::query_executor_invariant("scalar load mode must carry scalar runtime payload")
501    }
502
503    /// Construct a query-origin load-runtime invariant for grouped-mode payload mismatch.
504    pub(crate) fn load_runtime_grouped_payload_required() -> Self {
505        Self::query_executor_invariant("grouped load mode must carry grouped runtime payload")
506    }
507
508    /// Construct a query-origin load-surface invariant for scalar-page payload mismatch.
509    pub(crate) fn load_runtime_scalar_surface_payload_required() -> Self {
510        Self::query_executor_invariant("scalar page load mode must carry scalar runtime payload")
511    }
512
513    /// Construct a query-origin load-surface invariant for grouped-page payload mismatch.
514    pub(crate) fn load_runtime_grouped_surface_payload_required() -> Self {
515        Self::query_executor_invariant("grouped page load mode must carry grouped runtime payload")
516    }
517
518    /// Construct a query-origin load-entrypoint invariant for non-load plans.
519    pub(crate) fn load_executor_load_plan_required() -> Self {
520        Self::query_executor_invariant("load executor requires load plans")
521    }
522
523    /// Construct an executor-origin delete-entrypoint unsupported grouped-mode error.
524    pub(crate) fn delete_executor_grouped_unsupported() -> Self {
525        Self::executor_unsupported("grouped query execution is not yet enabled in this release")
526    }
527
528    /// Construct a query-origin delete-entrypoint invariant for non-delete plans.
529    pub(crate) fn delete_executor_delete_plan_required() -> Self {
530        Self::query_executor_invariant("delete executor requires delete plans")
531    }
532
533    /// Construct a query-origin aggregate kernel invariant for fold-mode contract drift.
534    pub(crate) fn aggregate_fold_mode_terminal_contract_required() -> Self {
535        Self::query_executor_invariant(
536            "aggregate fold mode must match route fold-mode contract for aggregate terminal",
537        )
538    }
539
540    /// Construct a query-origin fast-stream invariant for missing exact key-count observability.
541    pub(crate) fn fast_stream_exact_key_count_required() -> Self {
542        Self::query_executor_invariant("fast-path stream must expose an exact key-count hint")
543    }
544
545    /// Construct a query-origin fast-stream invariant for route kind/request mismatch.
546    pub(crate) fn fast_stream_route_kind_request_match_required() -> Self {
547        Self::query_executor_invariant("fast-stream route kind/request mismatch")
548    }
549
550    /// Construct a query-origin scan invariant for missing index-prefix executable specs.
551    pub(crate) fn secondary_index_prefix_spec_required() -> Self {
552        Self::query_executor_invariant(
553            "index-prefix executable spec must be materialized for index-prefix plans",
554        )
555    }
556
557    /// Construct a query-origin scan invariant for missing index-range executable specs.
558    pub(crate) fn index_range_limit_spec_required() -> Self {
559        Self::query_executor_invariant(
560            "index-range executable spec must be materialized for index-range plans",
561        )
562    }
563
564    /// Construct an executor-origin mutation unsupported error for duplicate atomic save keys.
565    pub(crate) fn mutation_atomic_save_duplicate_key(
566        entity_path: &str,
567        key: impl fmt::Display,
568    ) -> Self {
569        Self::executor_unsupported(format!(
570            "atomic save batch rejected duplicate key: entity={entity_path} key={key}",
571        ))
572    }
573
574    /// Construct an executor-origin mutation invariant for index-store generation drift.
575    pub(crate) fn mutation_index_store_generation_changed(
576        expected_generation: u64,
577        observed_generation: u64,
578    ) -> Self {
579        Self::executor_invariant(format!(
580            "index store generation changed between preflight and apply: expected {expected_generation}, found {observed_generation}",
581        ))
582    }
583
584    /// Build the canonical executor-invariant message prefix.
585    #[must_use]
586    #[cold]
587    #[inline(never)]
588    pub(crate) fn executor_invariant_message(reason: impl Into<String>) -> String {
589        format!("executor invariant violated: {}", reason.into())
590    }
591
592    /// Construct a planner-origin invariant violation.
593    #[cold]
594    #[inline(never)]
595    pub(crate) fn planner_invariant(message: impl Into<String>) -> Self {
596        Self::new(
597            ErrorClass::InvariantViolation,
598            ErrorOrigin::Planner,
599            message.into(),
600        )
601    }
602
603    /// Build the canonical invalid-logical-plan message prefix.
604    #[must_use]
605    pub(crate) fn invalid_logical_plan_message(reason: impl Into<String>) -> String {
606        format!("invalid logical plan: {}", reason.into())
607    }
608
609    /// Construct a planner-origin invariant with the canonical invalid-plan prefix.
610    pub(crate) fn query_invalid_logical_plan(reason: impl Into<String>) -> Self {
611        Self::planner_invariant(Self::invalid_logical_plan_message(reason))
612    }
613
614    /// Construct a query-origin invariant violation.
615    #[cold]
616    #[inline(never)]
617    pub(crate) fn query_invariant(message: impl Into<String>) -> Self {
618        Self::new(
619            ErrorClass::InvariantViolation,
620            ErrorOrigin::Query,
621            message.into(),
622        )
623    }
624
625    /// Construct a store-origin invariant violation.
626    pub(crate) fn store_invariant(message: impl Into<String>) -> Self {
627        Self::new(
628            ErrorClass::InvariantViolation,
629            ErrorOrigin::Store,
630            message.into(),
631        )
632    }
633
634    /// Construct the canonical duplicate runtime-hook entity-tag invariant.
635    pub(crate) fn duplicate_runtime_hooks_for_entity_tag(
636        entity_tag: crate::types::EntityTag,
637    ) -> Self {
638        Self::store_invariant(format!(
639            "duplicate runtime hooks for entity tag '{}'",
640            entity_tag.value()
641        ))
642    }
643
644    /// Construct the canonical duplicate runtime-hook entity-path invariant.
645    pub(crate) fn duplicate_runtime_hooks_for_entity_path(entity_path: &str) -> Self {
646        Self::store_invariant(format!(
647            "duplicate runtime hooks for entity path '{entity_path}'"
648        ))
649    }
650
651    /// Construct a store-origin internal error.
652    #[cold]
653    #[inline(never)]
654    pub(crate) fn store_internal(message: impl Into<String>) -> Self {
655        Self::new(ErrorClass::Internal, ErrorOrigin::Store, message.into())
656    }
657
658    /// Construct the canonical unconfigured commit-memory id internal error.
659    pub(crate) fn commit_memory_id_unconfigured() -> Self {
660        Self::store_internal(
661            "commit memory id is not configured; initialize recovery before commit store access",
662        )
663    }
664
665    /// Construct the canonical commit-memory id mismatch internal error.
666    pub(crate) fn commit_memory_id_mismatch(cached_id: u8, configured_id: u8) -> Self {
667        Self::store_internal(format!(
668            "commit memory id mismatch: cached={cached_id}, configured={configured_id}",
669        ))
670    }
671
672    /// Construct the canonical missing rollback-row invariant for delete execution.
673    pub(crate) fn delete_rollback_row_required() -> Self {
674        Self::store_internal("missing raw row for delete rollback")
675    }
676
677    /// Construct the canonical memory-registry initialization failure for commit memory.
678    pub(crate) fn commit_memory_registry_init_failed(err: impl fmt::Display) -> Self {
679        Self::store_internal(format!("memory registry init failed: {err}"))
680    }
681
682    /// Construct the canonical migration cursor persistence-width internal error.
683    pub(crate) fn migration_next_step_index_u64_required(id: &str, version: u64) -> Self {
684        Self::store_internal(format!(
685            "migration '{id}@{version}' next step index does not fit persisted u64 cursor",
686        ))
687    }
688
689    /// Construct the canonical recovery-integrity totals corruption error.
690    pub(crate) fn recovery_integrity_validation_failed(
691        missing_index_entries: u64,
692        divergent_index_entries: u64,
693        orphan_index_references: u64,
694    ) -> Self {
695        Self::store_corruption(format!(
696            "recovery integrity validation failed: missing_index_entries={missing_index_entries} divergent_index_entries={divergent_index_entries} orphan_index_references={orphan_index_references}",
697        ))
698    }
699
700    /// Construct an index-origin internal error.
701    #[cold]
702    #[inline(never)]
703    pub(crate) fn index_internal(message: impl Into<String>) -> Self {
704        Self::new(ErrorClass::Internal, ErrorOrigin::Index, message.into())
705    }
706
707    /// Construct the canonical missing old entity-key internal error for structural index removal.
708    pub(crate) fn structural_index_removal_entity_key_required() -> Self {
709        Self::index_internal("missing old entity key for structural index removal")
710    }
711
712    /// Construct the canonical missing new entity-key internal error for structural index insertion.
713    pub(crate) fn structural_index_insertion_entity_key_required() -> Self {
714        Self::index_internal("missing new entity key for structural index insertion")
715    }
716
717    /// Construct the canonical missing old entity-key internal error for index commit-op removal.
718    pub(crate) fn index_commit_op_old_entity_key_required() -> Self {
719        Self::index_internal("missing old entity key for index removal")
720    }
721
722    /// Construct the canonical missing new entity-key internal error for index commit-op insertion.
723    pub(crate) fn index_commit_op_new_entity_key_required() -> Self {
724        Self::index_internal("missing new entity key for index insertion")
725    }
726
727    /// Construct a query-origin internal error.
728    #[cfg(test)]
729    pub(crate) fn query_internal(message: impl Into<String>) -> Self {
730        Self::new(ErrorClass::Internal, ErrorOrigin::Query, message.into())
731    }
732
733    /// Construct a query-origin unsupported error.
734    #[cold]
735    #[inline(never)]
736    pub(crate) fn query_unsupported(message: impl Into<String>) -> Self {
737        Self::new(ErrorClass::Unsupported, ErrorOrigin::Query, message.into())
738    }
739
740    /// Construct a serialize-origin internal error.
741    #[cold]
742    #[inline(never)]
743    pub(crate) fn serialize_internal(message: impl Into<String>) -> Self {
744        Self::new(ErrorClass::Internal, ErrorOrigin::Serialize, message.into())
745    }
746
747    /// Construct the canonical persisted-row encode internal error.
748    pub(crate) fn persisted_row_encode_failed(detail: impl fmt::Display) -> Self {
749        Self::serialize_internal(format!("row encode failed: {detail}"))
750    }
751
752    /// Construct the canonical persisted-row field encode internal error.
753    pub(crate) fn persisted_row_field_encode_failed(
754        field_name: &str,
755        detail: impl fmt::Display,
756    ) -> Self {
757        Self::serialize_internal(format!(
758            "row encode failed for field '{field_name}': {detail}",
759        ))
760    }
761
762    /// Construct the canonical bytes(field) value encode internal error.
763    pub(crate) fn bytes_field_value_encode_failed(detail: impl fmt::Display) -> Self {
764        Self::serialize_internal(format!("bytes(field) value encode failed: {detail}"))
765    }
766
767    /// Construct the canonical migration-state serialization failure.
768    pub(crate) fn migration_state_serialize_failed(err: impl fmt::Display) -> Self {
769        Self::serialize_internal(format!("failed to serialize migration state: {err}"))
770    }
771
772    /// Construct a store-origin corruption error.
773    #[cold]
774    #[inline(never)]
775    pub(crate) fn store_corruption(message: impl Into<String>) -> Self {
776        Self::new(ErrorClass::Corruption, ErrorOrigin::Store, message.into())
777    }
778
779    /// Construct the canonical multiple-commit-memory-ids corruption error.
780    pub(crate) fn multiple_commit_memory_ids_registered(ids: impl fmt::Debug) -> Self {
781        Self::store_corruption(format!(
782            "multiple commit marker memory ids registered: {ids:?}"
783        ))
784    }
785
786    /// Construct the canonical persisted migration-step index conversion corruption error.
787    pub(crate) fn migration_persisted_step_index_invalid_usize(
788        id: &str,
789        version: u64,
790        step_index: u64,
791    ) -> Self {
792        Self::store_corruption(format!(
793            "migration '{id}@{version}' persisted step index does not fit runtime usize: {step_index}",
794        ))
795    }
796
797    /// Construct the canonical persisted migration-step index bounds corruption error.
798    pub(crate) fn migration_persisted_step_index_out_of_bounds(
799        id: &str,
800        version: u64,
801        step_index: usize,
802        total_steps: usize,
803    ) -> Self {
804        Self::store_corruption(format!(
805            "migration '{id}@{version}' persisted step index out of bounds: {step_index} > {total_steps}",
806        ))
807    }
808
809    /// Construct a store-origin commit-marker corruption error.
810    pub(crate) fn commit_corruption(detail: impl fmt::Display) -> Self {
811        Self::store_corruption(format!("commit marker corrupted: {detail}"))
812    }
813
814    /// Construct a store-origin commit-marker component corruption error.
815    pub(crate) fn commit_component_corruption(component: &str, detail: impl fmt::Display) -> Self {
816        Self::store_corruption(format!("commit marker {component} corrupted: {detail}"))
817    }
818
819    /// Construct the canonical commit-marker id generation internal error.
820    pub(crate) fn commit_id_generation_failed(detail: impl fmt::Display) -> Self {
821        Self::store_internal(format!("commit id generation failed: {detail}"))
822    }
823
824    /// Construct the canonical commit-marker payload u32-length-limit error.
825    pub(crate) fn commit_marker_payload_exceeds_u32_length_limit(label: &str, len: usize) -> Self {
826        Self::store_unsupported(format!("{label} exceeds u32 length limit: {len} bytes"))
827    }
828
829    /// Construct the canonical commit-marker component invalid-length corruption error.
830    pub(crate) fn commit_component_length_invalid(
831        component: &str,
832        len: usize,
833        expected: impl fmt::Display,
834    ) -> Self {
835        Self::commit_component_corruption(
836            component,
837            format!("invalid length {len}, expected {expected}"),
838        )
839    }
840
841    /// Construct the canonical commit-marker max-size corruption error.
842    pub(crate) fn commit_marker_exceeds_max_size(size: usize, max_size: u32) -> Self {
843        Self::commit_corruption(format!(
844            "commit marker exceeds max size: {size} bytes (limit {max_size})",
845        ))
846    }
847
848    /// Construct the canonical pre-persist commit-marker max-size unsupported error.
849    #[cfg(test)]
850    pub(crate) fn commit_marker_exceeds_max_size_before_persist(
851        size: usize,
852        max_size: u32,
853    ) -> Self {
854        Self::store_unsupported(format!(
855            "commit marker exceeds max size: {size} bytes (limit {max_size})",
856        ))
857    }
858
859    /// Construct the canonical commit-control slot max-size unsupported error.
860    pub(crate) fn commit_control_slot_exceeds_max_size(size: usize, max_size: u32) -> Self {
861        Self::store_unsupported(format!(
862            "commit control slot exceeds max size: {size} bytes (limit {max_size})",
863        ))
864    }
865
866    /// Construct the canonical commit-control marker-bytes length-limit error.
867    pub(crate) fn commit_control_slot_marker_bytes_exceed_u32_length_limit(size: usize) -> Self {
868        Self::store_unsupported(format!(
869            "commit marker bytes exceed u32 length limit: {size} bytes",
870        ))
871    }
872
873    /// Construct the canonical commit-control migration-bytes length-limit error.
874    pub(crate) fn commit_control_slot_migration_bytes_exceed_u32_length_limit(size: usize) -> Self {
875        Self::store_unsupported(format!(
876            "commit migration bytes exceed u32 length limit: {size} bytes",
877        ))
878    }
879
880    /// Construct the canonical startup index-rebuild invalid-data-key corruption error.
881    pub(crate) fn startup_index_rebuild_invalid_data_key(
882        store_path: &str,
883        detail: impl fmt::Display,
884    ) -> Self {
885        Self::store_corruption(format!(
886            "startup index rebuild failed: invalid data key in store '{store_path}' ({detail})",
887        ))
888    }
889
890    /// Construct an index-origin corruption error.
891    #[cold]
892    #[inline(never)]
893    pub(crate) fn index_corruption(message: impl Into<String>) -> Self {
894        Self::new(ErrorClass::Corruption, ErrorOrigin::Index, message.into())
895    }
896
897    /// Construct the canonical unique-validation corruption wrapper.
898    pub(crate) fn index_unique_validation_corruption(
899        entity_path: &str,
900        fields: &str,
901        detail: impl fmt::Display,
902    ) -> Self {
903        Self::index_plan_index_corruption(format!(
904            "index corrupted: {entity_path} ({fields}) -> {detail}",
905        ))
906    }
907
908    /// Construct the canonical structural index-entry corruption wrapper.
909    pub(crate) fn structural_index_entry_corruption(
910        entity_path: &str,
911        fields: &str,
912        detail: impl fmt::Display,
913    ) -> Self {
914        Self::index_plan_index_corruption(format!(
915            "index corrupted: {entity_path} ({fields}) -> {detail}",
916        ))
917    }
918
919    /// Construct the canonical missing new entity-key invariant during unique validation.
920    pub(crate) fn index_unique_validation_entity_key_required() -> Self {
921        Self::index_invariant("missing entity key during unique validation")
922    }
923
924    /// Construct the canonical unique-validation structural row-decode corruption error.
925    pub(crate) fn index_unique_validation_row_deserialize_failed(
926        data_key: impl fmt::Display,
927        source: impl fmt::Display,
928    ) -> Self {
929        Self::index_plan_serialize_corruption(format!(
930            "failed to structurally deserialize row: {data_key} ({source})"
931        ))
932    }
933
934    /// Construct the canonical unique-validation primary-key slot decode corruption error.
935    pub(crate) fn index_unique_validation_primary_key_decode_failed(
936        data_key: impl fmt::Display,
937        source: impl fmt::Display,
938    ) -> Self {
939        Self::index_plan_serialize_corruption(format!(
940            "failed to decode structural primary-key slot: {data_key} ({source})"
941        ))
942    }
943
944    /// Construct the canonical unique-validation stored key rebuild corruption error.
945    pub(crate) fn index_unique_validation_key_rebuild_failed(
946        data_key: impl fmt::Display,
947        entity_path: &str,
948        source: impl fmt::Display,
949    ) -> Self {
950        Self::index_plan_serialize_corruption(format!(
951            "failed to structurally decode unique key row {data_key} for {entity_path}: {source}",
952        ))
953    }
954
955    /// Construct the canonical unique-validation missing-row corruption error.
956    pub(crate) fn index_unique_validation_row_required(data_key: impl fmt::Display) -> Self {
957        Self::index_plan_store_corruption(format!("missing row: {data_key}"))
958    }
959
960    /// Construct the canonical index-only predicate missing-component invariant.
961    pub(crate) fn index_only_predicate_component_required() -> Self {
962        Self::index_invariant("index-only predicate program referenced missing index component")
963    }
964
965    /// Construct the canonical index-scan continuation-envelope invariant.
966    pub(crate) fn index_scan_continuation_anchor_within_envelope_required() -> Self {
967        Self::index_invariant(
968            "index-range continuation anchor is outside the requested range envelope",
969        )
970    }
971
972    /// Construct the canonical index-scan continuation-advancement invariant.
973    pub(crate) fn index_scan_continuation_advancement_required() -> Self {
974        Self::index_invariant("index-range continuation scan did not advance beyond the anchor")
975    }
976
977    /// Construct the canonical index-scan key-decode corruption error.
978    pub(crate) fn index_scan_key_corrupted_during(
979        context: &'static str,
980        err: impl fmt::Display,
981    ) -> Self {
982        Self::index_corruption(format!("index key corrupted during {context}: {err}"))
983    }
984
985    /// Construct the canonical index-scan missing projection-component invariant.
986    pub(crate) fn index_projection_component_required(
987        index_name: &str,
988        component_index: usize,
989    ) -> Self {
990        Self::index_invariant(format!(
991            "index projection referenced missing component: index='{index_name}' component_index={component_index}",
992        ))
993    }
994
995    /// Construct the canonical unexpected unique index-entry cardinality corruption error.
996    pub(crate) fn unique_index_entry_single_key_required() -> Self {
997        Self::index_corruption("unique index entry contains an unexpected number of keys")
998    }
999
1000    /// Construct the canonical scan-time index-entry decode corruption error.
1001    pub(crate) fn index_entry_decode_failed(err: impl fmt::Display) -> Self {
1002        Self::index_corruption(err.to_string())
1003    }
1004
1005    /// Construct a serialize-origin corruption error.
1006    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    /// Construct the canonical persisted-row decode corruption error.
1015    pub(crate) fn persisted_row_decode_failed(detail: impl fmt::Display) -> Self {
1016        Self::serialize_corruption(format!("row decode: {detail}"))
1017    }
1018
1019    /// Construct the canonical persisted-row field decode corruption error.
1020    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    /// Construct the canonical persisted-row field-kind decode corruption error.
1030    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    /// Construct the canonical persisted-row scalar-payload length corruption error.
1042    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    /// Construct the canonical persisted-row scalar-payload empty-body corruption error.
1056    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    /// Construct the canonical persisted-row scalar-payload invalid-byte corruption error.
1067    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    /// Construct the canonical persisted-row scalar-payload non-finite corruption error.
1079    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    /// Construct the canonical persisted-row scalar-payload out-of-range corruption error.
1090    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    /// Construct the canonical persisted-row invalid text payload corruption error.
1101    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    /// Construct the canonical persisted-row structural slot-lookup invariant.
1112    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    /// Construct the canonical persisted-row structural slot-cache invariant.
1119    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    /// Construct the canonical persisted-row primary-key decode corruption error.
1129    pub(crate) fn persisted_row_primary_key_not_storage_encodable(
1130        data_key: impl fmt::Display,
1131        detail: impl fmt::Display,
1132    ) -> Self {
1133        Self::persisted_row_decode_failed(format!(
1134            "primary-key value is not storage-key encodable: {data_key} ({detail})",
1135        ))
1136    }
1137
1138    /// Construct the canonical persisted-row missing primary-key slot corruption error.
1139    pub(crate) fn persisted_row_primary_key_slot_missing(data_key: impl fmt::Display) -> Self {
1140        Self::persisted_row_decode_failed(format!(
1141            "missing primary-key slot while validating {data_key}",
1142        ))
1143    }
1144
1145    /// Construct the canonical persisted-row key mismatch corruption error.
1146    pub(crate) fn persisted_row_key_mismatch(
1147        expected_key: impl fmt::Display,
1148        found_key: impl fmt::Display,
1149    ) -> Self {
1150        Self::store_corruption(format!(
1151            "row key mismatch: expected {expected_key}, found {found_key}",
1152        ))
1153    }
1154
1155    /// Construct the canonical persisted-row missing declared-field corruption error.
1156    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    /// Construct the canonical data-key entity mismatch corruption error.
1161    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    /// Construct the canonical data-key primary-key decode corruption error.
1171    pub(crate) fn data_key_primary_key_decode_failed(value: impl fmt::Debug) -> Self {
1172        Self::store_corruption(format!("data key primary key decode failed: {value:?}",))
1173    }
1174
1175    /// Construct the canonical reverse-index ordinal overflow internal error.
1176    pub(crate) fn reverse_index_ordinal_overflow(
1177        source_path: &str,
1178        field_name: &str,
1179        target_path: &str,
1180        detail: impl fmt::Display,
1181    ) -> Self {
1182        Self::index_internal(format!(
1183            "reverse index ordinal overflow: source={source_path} field={field_name} target={target_path} ({detail})",
1184        ))
1185    }
1186
1187    /// Construct the canonical reverse-index entry corruption error.
1188    pub(crate) fn reverse_index_entry_corrupted(
1189        source_path: &str,
1190        field_name: &str,
1191        target_path: &str,
1192        index_key: impl fmt::Debug,
1193        detail: impl fmt::Display,
1194    ) -> Self {
1195        Self::index_corruption(format!(
1196            "reverse index entry corrupted: source={source_path} field={field_name} target={target_path} key={index_key:?} ({detail})",
1197        ))
1198    }
1199
1200    /// Construct the canonical reverse-index entry encode unsupported error.
1201    pub(crate) fn reverse_index_entry_encode_failed(
1202        source_path: &str,
1203        field_name: &str,
1204        target_path: &str,
1205        detail: impl fmt::Display,
1206    ) -> Self {
1207        Self::index_unsupported(format!(
1208            "reverse index entry encoding failed: source={source_path} field={field_name} target={target_path} ({detail})",
1209        ))
1210    }
1211
1212    /// Construct the canonical relation-target store missing internal error.
1213    pub(crate) fn relation_target_store_missing(
1214        source_path: &str,
1215        field_name: &str,
1216        target_path: &str,
1217        store_path: &str,
1218        detail: impl fmt::Display,
1219    ) -> Self {
1220        Self::executor_internal(format!(
1221            "relation target store missing: source={source_path} field={field_name} target={target_path} store={store_path} ({detail})",
1222        ))
1223    }
1224
1225    /// Construct the canonical relation-target key decode corruption error.
1226    pub(crate) fn relation_target_key_decode_failed(
1227        context_label: &str,
1228        source_path: &str,
1229        field_name: &str,
1230        target_path: &str,
1231        detail: impl fmt::Display,
1232    ) -> Self {
1233        Self::identity_corruption(format!(
1234            "{context_label}: source={source_path} field={field_name} target={target_path} ({detail})",
1235        ))
1236    }
1237
1238    /// Construct the canonical relation-target entity mismatch corruption error.
1239    pub(crate) fn relation_target_entity_mismatch(
1240        context_label: &str,
1241        source_path: &str,
1242        field_name: &str,
1243        target_path: &str,
1244        target_entity_name: &str,
1245        expected_tag: impl fmt::Display,
1246        actual_tag: impl fmt::Display,
1247    ) -> Self {
1248        Self::store_corruption(format!(
1249            "{context_label}: source={source_path} field={field_name} target={target_path} expected={target_entity_name} (tag={expected_tag}) actual_tag={actual_tag}",
1250        ))
1251    }
1252
1253    /// Construct the canonical relation-source row decode corruption error.
1254    pub(crate) fn relation_source_row_decode_failed(
1255        source_path: &str,
1256        field_name: &str,
1257        target_path: &str,
1258        detail: impl fmt::Display,
1259    ) -> Self {
1260        Self::serialize_corruption(format!(
1261            "relation source row decode: source={source_path} field={field_name} target={target_path} ({detail})",
1262        ))
1263    }
1264
1265    /// Construct the canonical relation-source unsupported scalar relation-key corruption error.
1266    pub(crate) fn relation_source_row_unsupported_scalar_relation_key(
1267        source_path: &str,
1268        field_name: &str,
1269        target_path: &str,
1270    ) -> Self {
1271        Self::serialize_corruption(format!(
1272            "relation source row decode: unsupported scalar relation key: source={source_path} field={field_name} target={target_path}",
1273        ))
1274    }
1275
1276    /// Construct the canonical invalid strong-relation field-kind corruption error.
1277    pub(crate) fn relation_source_row_invalid_field_kind(field_kind: impl fmt::Debug) -> Self {
1278        Self::serialize_corruption(format!(
1279            "invalid strong relation field kind during structural decode: {field_kind:?}"
1280        ))
1281    }
1282
1283    /// Construct the canonical unsupported strong-relation key-kind corruption error.
1284    pub(crate) fn relation_source_row_unsupported_key_kind(field_kind: impl fmt::Debug) -> Self {
1285        Self::serialize_corruption(format!(
1286            "unsupported strong relation key kind during structural decode: {field_kind:?}"
1287        ))
1288    }
1289
1290    /// Construct the canonical reverse-index relation-target decode invariant failure.
1291    pub(crate) fn reverse_index_relation_target_decode_invariant_violated(
1292        source_path: &str,
1293        field_name: &str,
1294        target_path: &str,
1295    ) -> Self {
1296        Self::executor_internal(format!(
1297            "relation target decode invariant violated while preparing reverse index: source={source_path} field={field_name} target={target_path}",
1298        ))
1299    }
1300
1301    /// Construct the canonical covering-component empty-payload corruption error.
1302    pub(crate) fn bytes_covering_component_payload_empty() -> Self {
1303        Self::index_corruption("index component payload is empty during covering projection decode")
1304    }
1305
1306    /// Construct the canonical covering-component truncated bool corruption error.
1307    pub(crate) fn bytes_covering_bool_payload_truncated() -> Self {
1308        Self::index_corruption("bool covering component payload is truncated")
1309    }
1310
1311    /// Construct the canonical covering-component invalid-length corruption error.
1312    pub(crate) fn bytes_covering_component_payload_invalid_length(payload_kind: &str) -> Self {
1313        Self::index_corruption(format!(
1314            "{payload_kind} covering component payload has invalid length"
1315        ))
1316    }
1317
1318    /// Construct the canonical covering-component invalid-bool corruption error.
1319    pub(crate) fn bytes_covering_bool_payload_invalid_value() -> Self {
1320        Self::index_corruption("bool covering component payload has invalid value")
1321    }
1322
1323    /// Construct the canonical covering-component invalid text terminator corruption error.
1324    pub(crate) fn bytes_covering_text_payload_invalid_terminator() -> Self {
1325        Self::index_corruption("text covering component payload has invalid terminator")
1326    }
1327
1328    /// Construct the canonical covering-component trailing-text corruption error.
1329    pub(crate) fn bytes_covering_text_payload_trailing_bytes() -> Self {
1330        Self::index_corruption("text covering component payload contains trailing bytes")
1331    }
1332
1333    /// Construct the canonical covering-component invalid-UTF-8 text corruption error.
1334    pub(crate) fn bytes_covering_text_payload_invalid_utf8() -> Self {
1335        Self::index_corruption("text covering component payload is not valid UTF-8")
1336    }
1337
1338    /// Construct the canonical covering-component invalid text escape corruption error.
1339    pub(crate) fn bytes_covering_text_payload_invalid_escape_byte() -> Self {
1340        Self::index_corruption("text covering component payload has invalid escape byte")
1341    }
1342
1343    /// Construct the canonical covering-component missing text terminator corruption error.
1344    pub(crate) fn bytes_covering_text_payload_missing_terminator() -> Self {
1345        Self::index_corruption("text covering component payload is missing terminator")
1346    }
1347
1348    /// Construct the canonical missing persisted-field decode error.
1349    #[must_use]
1350    pub fn missing_persisted_slot(field_name: &'static str) -> Self {
1351        Self::serialize_corruption(format!("row decode: missing required field '{field_name}'",))
1352    }
1353
1354    /// Construct an identity-origin corruption error.
1355    pub(crate) fn identity_corruption(message: impl Into<String>) -> Self {
1356        Self::new(
1357            ErrorClass::Corruption,
1358            ErrorOrigin::Identity,
1359            message.into(),
1360        )
1361    }
1362
1363    /// Construct a store-origin unsupported error.
1364    #[cold]
1365    #[inline(never)]
1366    pub(crate) fn store_unsupported(message: impl Into<String>) -> Self {
1367        Self::new(ErrorClass::Unsupported, ErrorOrigin::Store, message.into())
1368    }
1369
1370    /// Construct the canonical empty migration label unsupported error.
1371    pub(crate) fn migration_label_empty(label: &str) -> Self {
1372        Self::store_unsupported(format!("{label} cannot be empty"))
1373    }
1374
1375    /// Construct the canonical empty migration-step row-op set unsupported error.
1376    pub(crate) fn migration_step_row_ops_required(name: &str) -> Self {
1377        Self::store_unsupported(format!(
1378            "migration step '{name}' must include at least one row op",
1379        ))
1380    }
1381
1382    /// Construct the canonical invalid migration-plan version unsupported error.
1383    pub(crate) fn migration_plan_version_required(id: &str) -> Self {
1384        Self::store_unsupported(format!("migration plan '{id}' version must be > 0",))
1385    }
1386
1387    /// Construct the canonical empty migration-plan steps unsupported error.
1388    pub(crate) fn migration_plan_steps_required(id: &str) -> Self {
1389        Self::store_unsupported(format!(
1390            "migration plan '{id}' must include at least one step",
1391        ))
1392    }
1393
1394    /// Construct the canonical migration cursor out-of-bounds unsupported error.
1395    pub(crate) fn migration_cursor_out_of_bounds(
1396        id: &str,
1397        version: u64,
1398        next_step: usize,
1399        total_steps: usize,
1400    ) -> Self {
1401        Self::store_unsupported(format!(
1402            "migration '{id}@{version}' cursor out of bounds: next_step={next_step} total_steps={total_steps}",
1403        ))
1404    }
1405
1406    /// Construct the canonical max-steps-required migration execution error.
1407    pub(crate) fn migration_execution_requires_max_steps(id: &str) -> Self {
1408        Self::store_unsupported(format!("migration '{id}' execution requires max_steps > 0",))
1409    }
1410
1411    /// Construct the canonical in-progress migration-plan conflict error.
1412    pub(crate) fn migration_in_progress_conflict(
1413        requested_id: &str,
1414        requested_version: u64,
1415        active_id: &str,
1416        active_version: u64,
1417    ) -> Self {
1418        Self::store_unsupported(format!(
1419            "migration '{requested_id}@{requested_version}' cannot execute while migration '{active_id}@{active_version}' is in progress",
1420        ))
1421    }
1422
1423    /// Construct the canonical unsupported persisted entity-tag store error.
1424    pub(crate) fn unsupported_entity_tag_in_data_store(
1425        entity_tag: crate::types::EntityTag,
1426    ) -> Self {
1427        Self::store_unsupported(format!(
1428            "unsupported entity tag in data store: '{}'",
1429            entity_tag.value()
1430        ))
1431    }
1432
1433    /// Construct the canonical configured-vs-registered commit-memory id mismatch error.
1434    pub(crate) fn configured_commit_memory_id_mismatch(
1435        configured_id: u8,
1436        registered_id: u8,
1437    ) -> Self {
1438        Self::store_unsupported(format!(
1439            "configured commit memory id {configured_id} does not match existing commit marker id {registered_id}",
1440        ))
1441    }
1442
1443    /// Construct the canonical occupied commit-memory id unsupported error.
1444    pub(crate) fn commit_memory_id_already_registered(memory_id: u8, label: &str) -> Self {
1445        Self::store_unsupported(format!(
1446            "configured commit memory id {memory_id} is already registered as '{label}'",
1447        ))
1448    }
1449
1450    /// Construct the canonical out-of-range commit-memory id unsupported error.
1451    pub(crate) fn commit_memory_id_outside_reserved_ranges(memory_id: u8) -> Self {
1452        Self::store_unsupported(format!(
1453            "configured commit memory id {memory_id} is outside reserved ranges",
1454        ))
1455    }
1456
1457    /// Construct the canonical commit-memory id registration failure.
1458    pub(crate) fn commit_memory_id_registration_failed(err: impl fmt::Display) -> Self {
1459        Self::store_internal(format!("commit memory id registration failed: {err}"))
1460    }
1461
1462    /// Construct an index-origin unsupported error.
1463    pub(crate) fn index_unsupported(message: impl Into<String>) -> Self {
1464        Self::new(ErrorClass::Unsupported, ErrorOrigin::Index, message.into())
1465    }
1466
1467    /// Construct the canonical index-key component size-limit unsupported error.
1468    pub(crate) fn index_component_exceeds_max_size(
1469        key_item: impl fmt::Display,
1470        len: usize,
1471        max_component_size: usize,
1472    ) -> Self {
1473        Self::index_unsupported(format!(
1474            "index component exceeds max size: key item '{key_item}' -> {len} bytes (limit {max_component_size})",
1475        ))
1476    }
1477
1478    /// Construct the canonical index-entry max-keys unsupported error during commit encoding.
1479    pub(crate) fn index_entry_exceeds_max_keys(
1480        entity_path: &str,
1481        fields: &str,
1482        keys: usize,
1483    ) -> Self {
1484        Self::index_unsupported(format!(
1485            "index entry exceeds max keys: {entity_path} ({fields}) -> {keys} keys",
1486        ))
1487    }
1488
1489    /// Construct the canonical duplicate-key invariant during commit entry encoding.
1490    #[cfg(test)]
1491    pub(crate) fn index_entry_duplicate_keys_unexpected(entity_path: &str, fields: &str) -> Self {
1492        Self::index_invariant(format!(
1493            "index entry unexpectedly contains duplicate keys: {entity_path} ({fields})",
1494        ))
1495    }
1496
1497    /// Construct the canonical index-entry key-encoding unsupported error during commit encoding.
1498    pub(crate) fn index_entry_key_encoding_failed(
1499        entity_path: &str,
1500        fields: &str,
1501        err: impl fmt::Display,
1502    ) -> Self {
1503        Self::index_unsupported(format!(
1504            "index entry key encoding failed: {entity_path} ({fields}) -> {err}",
1505        ))
1506    }
1507
1508    /// Construct a serialize-origin unsupported error.
1509    pub(crate) fn serialize_unsupported(message: impl Into<String>) -> Self {
1510        Self::new(
1511            ErrorClass::Unsupported,
1512            ErrorOrigin::Serialize,
1513            message.into(),
1514        )
1515    }
1516
1517    /// Construct a cursor-origin unsupported error.
1518    pub(crate) fn cursor_unsupported(message: impl Into<String>) -> Self {
1519        Self::new(ErrorClass::Unsupported, ErrorOrigin::Cursor, message.into())
1520    }
1521
1522    /// Construct a serialize-origin incompatible persisted-format error.
1523    pub(crate) fn serialize_incompatible_persisted_format(message: impl Into<String>) -> Self {
1524        Self::new(
1525            ErrorClass::IncompatiblePersistedFormat,
1526            ErrorOrigin::Serialize,
1527            message.into(),
1528        )
1529    }
1530
1531    /// Construct the canonical persisted-payload decode failure mapping for one
1532    /// DB-owned serialized payload boundary.
1533    pub(crate) fn serialize_payload_decode_failed(
1534        source: SerializeError,
1535        payload_label: &'static str,
1536    ) -> Self {
1537        match source {
1538            // DB codec only decodes engine-owned persisted payloads.
1539            // Size-limit breaches indicate persisted bytes violate DB storage policy.
1540            SerializeError::DeserializeSizeLimitExceeded { len, max_bytes } => {
1541                Self::serialize_corruption(format!(
1542                    "{payload_label} decode failed: payload size {len} exceeds limit {max_bytes}"
1543                ))
1544            }
1545            SerializeError::Deserialize(_) => Self::serialize_corruption(format!(
1546                "{payload_label} decode failed: {}",
1547                SerializeErrorKind::Deserialize
1548            )),
1549            SerializeError::Serialize(_) => Self::serialize_corruption(format!(
1550                "{payload_label} decode failed: {}",
1551                SerializeErrorKind::Serialize
1552            )),
1553        }
1554    }
1555
1556    /// Construct a query-origin unsupported error preserving one SQL parser
1557    /// unsupported-feature label in structured error detail.
1558    #[cfg(feature = "sql")]
1559    pub(crate) fn query_unsupported_sql_feature(feature: &'static str) -> Self {
1560        let message = format!(
1561            "SQL query is not executable in this release: unsupported SQL feature: {feature}"
1562        );
1563
1564        Self {
1565            class: ErrorClass::Unsupported,
1566            origin: ErrorOrigin::Query,
1567            message,
1568            detail: Some(ErrorDetail::Query(
1569                QueryErrorDetail::UnsupportedSqlFeature { feature },
1570            )),
1571        }
1572    }
1573
1574    pub fn store_not_found(key: impl Into<String>) -> Self {
1575        let key = key.into();
1576
1577        Self {
1578            class: ErrorClass::NotFound,
1579            origin: ErrorOrigin::Store,
1580            message: format!("data key not found: {key}"),
1581            detail: Some(ErrorDetail::Store(StoreError::NotFound { key })),
1582        }
1583    }
1584
1585    /// Construct a standardized unsupported-entity-path error.
1586    pub fn unsupported_entity_path(path: impl Into<String>) -> Self {
1587        let path = path.into();
1588
1589        Self::new(
1590            ErrorClass::Unsupported,
1591            ErrorOrigin::Store,
1592            format!("unsupported entity path: '{path}'"),
1593        )
1594    }
1595
1596    #[must_use]
1597    pub const fn is_not_found(&self) -> bool {
1598        matches!(
1599            self.detail,
1600            Some(ErrorDetail::Store(StoreError::NotFound { .. }))
1601        )
1602    }
1603
1604    #[must_use]
1605    pub fn display_with_class(&self) -> String {
1606        format!("{}:{}: {}", self.origin, self.class, self.message)
1607    }
1608
1609    /// Construct an index-plan corruption error with a canonical prefix.
1610    #[cold]
1611    #[inline(never)]
1612    pub(crate) fn index_plan_corruption(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1613        let message = message.into();
1614        Self::new(
1615            ErrorClass::Corruption,
1616            origin,
1617            format!("corruption detected ({origin}): {message}"),
1618        )
1619    }
1620
1621    /// Construct an index-plan corruption error for index-origin failures.
1622    #[cold]
1623    #[inline(never)]
1624    pub(crate) fn index_plan_index_corruption(message: impl Into<String>) -> Self {
1625        Self::index_plan_corruption(ErrorOrigin::Index, message)
1626    }
1627
1628    /// Construct an index-plan corruption error for store-origin failures.
1629    #[cold]
1630    #[inline(never)]
1631    pub(crate) fn index_plan_store_corruption(message: impl Into<String>) -> Self {
1632        Self::index_plan_corruption(ErrorOrigin::Store, message)
1633    }
1634
1635    /// Construct an index-plan corruption error for serialize-origin failures.
1636    #[cold]
1637    #[inline(never)]
1638    pub(crate) fn index_plan_serialize_corruption(message: impl Into<String>) -> Self {
1639        Self::index_plan_corruption(ErrorOrigin::Serialize, message)
1640    }
1641
1642    /// Construct an index-plan invariant violation error with a canonical prefix.
1643    #[cfg(test)]
1644    pub(crate) fn index_plan_invariant(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1645        let message = message.into();
1646        Self::new(
1647            ErrorClass::InvariantViolation,
1648            origin,
1649            format!("invariant violation detected ({origin}): {message}"),
1650        )
1651    }
1652
1653    /// Construct an index-plan invariant violation error for store-origin failures.
1654    #[cfg(test)]
1655    pub(crate) fn index_plan_store_invariant(message: impl Into<String>) -> Self {
1656        Self::index_plan_invariant(ErrorOrigin::Store, message)
1657    }
1658
1659    /// Construct an index uniqueness violation conflict error.
1660    pub(crate) fn index_violation(path: &str, index_fields: &[&str]) -> Self {
1661        Self::new(
1662            ErrorClass::Conflict,
1663            ErrorOrigin::Index,
1664            format!(
1665                "index constraint violation: {path} ({})",
1666                index_fields.join(", ")
1667            ),
1668        )
1669    }
1670}
1671
1672///
1673/// ErrorDetail
1674///
1675/// Structured, origin-specific error detail carried by [`InternalError`].
1676/// This enum is intentionally extensible.
1677///
1678
1679#[derive(Debug, ThisError)]
1680pub enum ErrorDetail {
1681    #[error("{0}")]
1682    Store(StoreError),
1683    #[error("{0}")]
1684    Query(QueryErrorDetail),
1685    // Future-proofing:
1686    // #[error("{0}")]
1687    // Index(IndexError),
1688    //
1689    // #[error("{0}")]
1690    // Executor(ExecutorErrorDetail),
1691}
1692
1693///
1694/// StoreError
1695///
1696/// Store-specific structured error detail.
1697/// Never returned directly; always wrapped in [`ErrorDetail::Store`].
1698///
1699
1700#[derive(Debug, ThisError)]
1701pub enum StoreError {
1702    #[error("key not found: {key}")]
1703    NotFound { key: String },
1704
1705    #[error("store corruption: {message}")]
1706    Corrupt { message: String },
1707
1708    #[error("store invariant violation: {message}")]
1709    InvariantViolation { message: String },
1710}
1711
1712///
1713/// QueryErrorDetail
1714///
1715/// Query-origin structured error detail payload.
1716///
1717
1718#[derive(Debug, ThisError)]
1719pub enum QueryErrorDetail {
1720    #[error("unsupported SQL feature: {feature}")]
1721    UnsupportedSqlFeature { feature: &'static str },
1722}
1723
1724///
1725/// ErrorClass
1726/// Internal error taxonomy for runtime classification.
1727/// Not a stable API; may change without notice.
1728///
1729
1730#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1731pub enum ErrorClass {
1732    Corruption,
1733    IncompatiblePersistedFormat,
1734    NotFound,
1735    Internal,
1736    Conflict,
1737    Unsupported,
1738    InvariantViolation,
1739}
1740
1741impl fmt::Display for ErrorClass {
1742    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1743        let label = match self {
1744            Self::Corruption => "corruption",
1745            Self::IncompatiblePersistedFormat => "incompatible_persisted_format",
1746            Self::NotFound => "not_found",
1747            Self::Internal => "internal",
1748            Self::Conflict => "conflict",
1749            Self::Unsupported => "unsupported",
1750            Self::InvariantViolation => "invariant_violation",
1751        };
1752        write!(f, "{label}")
1753    }
1754}
1755
1756///
1757/// ErrorOrigin
1758/// Internal origin taxonomy for runtime classification.
1759/// Not a stable API; may change without notice.
1760///
1761
1762#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1763pub enum ErrorOrigin {
1764    Serialize,
1765    Store,
1766    Index,
1767    Identity,
1768    Query,
1769    Planner,
1770    Cursor,
1771    Recovery,
1772    Response,
1773    Executor,
1774    Interface,
1775}
1776
1777impl fmt::Display for ErrorOrigin {
1778    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1779        let label = match self {
1780            Self::Serialize => "serialize",
1781            Self::Store => "store",
1782            Self::Index => "index",
1783            Self::Identity => "identity",
1784            Self::Query => "query",
1785            Self::Planner => "planner",
1786            Self::Cursor => "cursor",
1787            Self::Recovery => "recovery",
1788            Self::Response => "response",
1789            Self::Executor => "executor",
1790            Self::Interface => "interface",
1791        };
1792        write!(f, "{label}")
1793    }
1794}