Skip to main content

icydb_core/error/
mod.rs

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