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    pub fn new(class: ErrorClass, origin: ErrorOrigin, message: impl Into<String>) -> Self {
131        let message = message.into();
132
133        let detail = match (class, origin) {
134            (ErrorClass::Corruption, ErrorOrigin::Store) => {
135                Some(ErrorDetail::Store(StoreError::Corrupt {
136                    message: message.clone(),
137                }))
138            }
139            (ErrorClass::InvariantViolation, ErrorOrigin::Store) => {
140                Some(ErrorDetail::Store(StoreError::InvariantViolation {
141                    message: message.clone(),
142                }))
143            }
144            _ => None,
145        };
146
147        Self {
148            class,
149            origin,
150            message,
151            detail,
152        }
153    }
154
155    /// Return the internal error class taxonomy.
156    #[must_use]
157    pub const fn class(&self) -> ErrorClass {
158        self.class
159    }
160
161    /// Return the internal error origin taxonomy.
162    #[must_use]
163    pub const fn origin(&self) -> ErrorOrigin {
164        self.origin
165    }
166
167    /// Return the rendered internal error message.
168    #[must_use]
169    pub fn message(&self) -> &str {
170        &self.message
171    }
172
173    /// Return the optional structured detail payload.
174    #[must_use]
175    pub const fn detail(&self) -> Option<&ErrorDetail> {
176        self.detail.as_ref()
177    }
178
179    /// Consume and return the rendered internal error message.
180    #[must_use]
181    pub fn into_message(self) -> String {
182        self.message
183    }
184
185    /// Construct an error while preserving an explicit class/origin taxonomy pair.
186    pub(crate) fn classified(
187        class: ErrorClass,
188        origin: ErrorOrigin,
189        message: impl Into<String>,
190    ) -> Self {
191        Self::new(class, origin, message)
192    }
193
194    /// Rebuild this error with a new message while preserving class/origin taxonomy.
195    pub(crate) fn with_message(self, message: impl Into<String>) -> Self {
196        Self::classified(self.class, self.origin, message)
197    }
198
199    /// Rebuild this error with a new origin while preserving class/message.
200    ///
201    /// Origin-scoped detail payloads are intentionally dropped when re-origining.
202    pub(crate) fn with_origin(self, origin: ErrorOrigin) -> Self {
203        Self::classified(self.class, origin, self.message)
204    }
205
206    /// Construct an index-origin invariant violation.
207    pub(crate) fn index_invariant(message: impl Into<String>) -> Self {
208        Self::new(
209            ErrorClass::InvariantViolation,
210            ErrorOrigin::Index,
211            message.into(),
212        )
213    }
214
215    /// Construct the canonical index field-count invariant for key building.
216    pub(crate) fn index_key_field_count_exceeds_max(
217        index_name: &str,
218        field_count: usize,
219        max_fields: usize,
220    ) -> Self {
221        Self::index_invariant(format!(
222            "index '{index_name}' has {field_count} fields (max {max_fields})",
223        ))
224    }
225
226    /// Construct the canonical index-key source-field-missing-on-model invariant.
227    pub(crate) fn index_key_item_field_missing_on_entity_model(field: &str) -> Self {
228        Self::index_invariant(format!(
229            "index key item field missing on entity model: {field}",
230        ))
231    }
232
233    /// Construct the canonical index-key source-field-missing-on-row invariant.
234    pub(crate) fn index_key_item_field_missing_on_lookup_row(field: &str) -> Self {
235        Self::index_invariant(format!(
236            "index key item field missing on lookup row: {field}",
237        ))
238    }
239
240    /// Construct the canonical index-expression source-type mismatch invariant.
241    pub(crate) fn index_expression_source_type_mismatch(
242        index_name: &str,
243        expression: impl fmt::Display,
244        expected: &str,
245        source_label: &str,
246    ) -> Self {
247        Self::index_invariant(format!(
248            "index '{index_name}' expression '{expression}' expected {expected} source value, got {source_label}",
249        ))
250    }
251
252    /// Construct a planner-origin invariant violation with the canonical
253    /// executor-boundary invariant prefix preserved in the message payload.
254    pub(crate) fn planner_executor_invariant(reason: impl Into<String>) -> Self {
255        Self::new(
256            ErrorClass::InvariantViolation,
257            ErrorOrigin::Planner,
258            Self::executor_invariant_message(reason),
259        )
260    }
261
262    /// Construct a query-origin invariant violation with the canonical
263    /// executor-boundary invariant prefix preserved in the message payload.
264    pub(crate) fn query_executor_invariant(reason: impl Into<String>) -> Self {
265        Self::new(
266            ErrorClass::InvariantViolation,
267            ErrorOrigin::Query,
268            Self::executor_invariant_message(reason),
269        )
270    }
271
272    /// Construct a cursor-origin invariant violation with the canonical
273    /// executor-boundary invariant prefix preserved in the message payload.
274    pub(crate) fn cursor_executor_invariant(reason: impl Into<String>) -> Self {
275        Self::new(
276            ErrorClass::InvariantViolation,
277            ErrorOrigin::Cursor,
278            Self::executor_invariant_message(reason),
279        )
280    }
281
282    /// Construct an executor-origin invariant violation.
283    pub(crate) fn executor_invariant(message: impl Into<String>) -> Self {
284        Self::new(
285            ErrorClass::InvariantViolation,
286            ErrorOrigin::Executor,
287            message.into(),
288        )
289    }
290
291    /// Construct an executor-origin internal error.
292    pub(crate) fn executor_internal(message: impl Into<String>) -> Self {
293        Self::new(ErrorClass::Internal, ErrorOrigin::Executor, message.into())
294    }
295
296    /// Construct an executor-origin unsupported error.
297    pub(crate) fn executor_unsupported(message: impl Into<String>) -> Self {
298        Self::new(
299            ErrorClass::Unsupported,
300            ErrorOrigin::Executor,
301            message.into(),
302        )
303    }
304
305    /// Construct an executor-origin save-preflight schema invariant.
306    pub(crate) fn mutation_entity_schema_invalid(
307        entity_path: &str,
308        detail: impl fmt::Display,
309    ) -> Self {
310        Self::executor_invariant(format!("entity schema invalid for {entity_path}: {detail}"))
311    }
312
313    /// Construct an executor-origin save-preflight primary-key missing invariant.
314    pub(crate) fn mutation_entity_primary_key_missing(entity_path: &str, field_name: &str) -> Self {
315        Self::executor_invariant(format!(
316            "entity primary key field missing: {entity_path} field={field_name}",
317        ))
318    }
319
320    /// Construct an executor-origin save-preflight primary-key invalid-value invariant.
321    pub(crate) fn mutation_entity_primary_key_invalid_value(
322        entity_path: &str,
323        field_name: &str,
324        value: &crate::value::Value,
325    ) -> Self {
326        Self::executor_invariant(format!(
327            "entity primary key field has invalid value: {entity_path} field={field_name} value={value:?}",
328        ))
329    }
330
331    /// Construct an executor-origin save-preflight primary-key type mismatch invariant.
332    pub(crate) fn mutation_entity_primary_key_type_mismatch(
333        entity_path: &str,
334        field_name: &str,
335        value: &crate::value::Value,
336    ) -> Self {
337        Self::executor_invariant(format!(
338            "entity primary key field type mismatch: {entity_path} field={field_name} value={value:?}",
339        ))
340    }
341
342    /// Construct an executor-origin save-preflight primary-key identity mismatch invariant.
343    pub(crate) fn mutation_entity_primary_key_mismatch(
344        entity_path: &str,
345        field_name: &str,
346        field_value: &crate::value::Value,
347        identity_key: &crate::value::Value,
348    ) -> Self {
349        Self::executor_invariant(format!(
350            "entity primary key mismatch: {entity_path} field={field_name} field_value={field_value:?} id_key={identity_key:?}",
351        ))
352    }
353
354    /// Construct an executor-origin save-preflight field-missing invariant.
355    pub(crate) fn mutation_entity_field_missing(
356        entity_path: &str,
357        field_name: &str,
358        indexed: bool,
359    ) -> Self {
360        let indexed_note = if indexed { " (indexed)" } else { "" };
361
362        Self::executor_invariant(format!(
363            "entity field missing: {entity_path} field={field_name}{indexed_note}",
364        ))
365    }
366
367    /// Construct an executor-origin save-preflight field-type mismatch invariant.
368    pub(crate) fn mutation_entity_field_type_mismatch(
369        entity_path: &str,
370        field_name: &str,
371        value: &crate::value::Value,
372    ) -> Self {
373        Self::executor_invariant(format!(
374            "entity field type mismatch: {entity_path} field={field_name} value={value:?}",
375        ))
376    }
377
378    /// Construct an executor-origin save-preflight decimal-scale unsupported error.
379    pub(crate) fn mutation_decimal_scale_mismatch(
380        entity_path: &str,
381        field_name: &str,
382        expected_scale: impl fmt::Display,
383        actual_scale: impl fmt::Display,
384    ) -> Self {
385        Self::executor_unsupported(format!(
386            "decimal field scale mismatch: {entity_path} field={field_name} expected_scale={expected_scale} actual_scale={actual_scale}",
387        ))
388    }
389
390    /// Construct an executor-origin save-preflight set-encoding invariant.
391    pub(crate) fn mutation_set_field_list_required(entity_path: &str, field_name: &str) -> Self {
392        Self::executor_invariant(format!(
393            "set field must encode as Value::List: {entity_path} field={field_name}",
394        ))
395    }
396
397    /// Construct an executor-origin save-preflight set-canonicality invariant.
398    pub(crate) fn mutation_set_field_not_canonical(entity_path: &str, field_name: &str) -> Self {
399        Self::executor_invariant(format!(
400            "set field must be strictly ordered and deduplicated: {entity_path} field={field_name}",
401        ))
402    }
403
404    /// Construct an executor-origin save-preflight map-encoding invariant.
405    pub(crate) fn mutation_map_field_map_required(entity_path: &str, field_name: &str) -> Self {
406        Self::executor_invariant(format!(
407            "map field must encode as Value::Map: {entity_path} field={field_name}",
408        ))
409    }
410
411    /// Construct an executor-origin save-preflight map-entry invariant.
412    pub(crate) fn mutation_map_field_entries_invalid(
413        entity_path: &str,
414        field_name: &str,
415        detail: impl fmt::Display,
416    ) -> Self {
417        Self::executor_invariant(format!(
418            "map field entries violate map invariants: {entity_path} field={field_name} ({detail})",
419        ))
420    }
421
422    /// Construct an executor-origin save-preflight map-canonicality invariant.
423    pub(crate) fn mutation_map_field_entries_not_canonical(
424        entity_path: &str,
425        field_name: &str,
426    ) -> Self {
427        Self::executor_invariant(format!(
428            "map field entries are not in canonical deterministic order: {entity_path} field={field_name}",
429        ))
430    }
431
432    /// Construct a query-origin scalar page invariant for missing predicate slots.
433    pub(crate) fn scalar_page_predicate_slots_required() -> Self {
434        Self::query_executor_invariant("post-access filtering requires precompiled predicate slots")
435    }
436
437    /// Construct a query-origin scalar page invariant for ordering before filtering.
438    pub(crate) fn scalar_page_ordering_after_filtering_required() -> Self {
439        Self::query_executor_invariant("ordering must run after filtering")
440    }
441
442    /// Construct a query-origin scalar page invariant for missing order at the cursor boundary.
443    pub(crate) fn scalar_page_cursor_boundary_order_required() -> Self {
444        Self::query_executor_invariant("cursor boundary requires ordering")
445    }
446
447    /// Construct a query-origin scalar page invariant for cursor-before-ordering drift.
448    pub(crate) fn scalar_page_cursor_boundary_after_ordering_required() -> Self {
449        Self::query_executor_invariant("cursor boundary must run after ordering")
450    }
451
452    /// Construct a query-origin scalar page invariant for pagination-before-ordering drift.
453    pub(crate) fn scalar_page_pagination_after_ordering_required() -> Self {
454        Self::query_executor_invariant("pagination must run after ordering")
455    }
456
457    /// Construct a query-origin scalar page invariant for delete-limit-before-ordering drift.
458    pub(crate) fn scalar_page_delete_limit_after_ordering_required() -> Self {
459        Self::query_executor_invariant("delete limit must run after ordering")
460    }
461
462    /// Construct a query-origin load-runtime invariant for scalar-mode payload mismatch.
463    pub(crate) fn load_runtime_scalar_payload_required() -> Self {
464        Self::query_executor_invariant("scalar load mode must carry scalar runtime payload")
465    }
466
467    /// Construct a query-origin load-runtime invariant for grouped-mode payload mismatch.
468    pub(crate) fn load_runtime_grouped_payload_required() -> Self {
469        Self::query_executor_invariant("grouped load mode must carry grouped runtime payload")
470    }
471
472    /// Construct a query-origin load-surface invariant for scalar-page payload mismatch.
473    pub(crate) fn load_runtime_scalar_surface_payload_required() -> Self {
474        Self::query_executor_invariant("scalar page load mode must carry scalar runtime payload")
475    }
476
477    /// Construct a query-origin load-surface invariant for grouped-page payload mismatch.
478    pub(crate) fn load_runtime_grouped_surface_payload_required() -> Self {
479        Self::query_executor_invariant("grouped page load mode must carry grouped runtime payload")
480    }
481
482    /// Construct a query-origin load-entrypoint invariant for non-load plans.
483    pub(crate) fn load_executor_load_plan_required() -> Self {
484        Self::query_executor_invariant("load executor requires load plans")
485    }
486
487    /// Construct an executor-origin delete-entrypoint unsupported grouped-mode error.
488    pub(crate) fn delete_executor_grouped_unsupported() -> Self {
489        Self::executor_unsupported("grouped query execution is not yet enabled in this release")
490    }
491
492    /// Construct a query-origin delete-entrypoint invariant for non-delete plans.
493    pub(crate) fn delete_executor_delete_plan_required() -> Self {
494        Self::query_executor_invariant("delete executor requires delete plans")
495    }
496
497    /// Construct a query-origin aggregate kernel invariant for fold-mode contract drift.
498    pub(crate) fn aggregate_fold_mode_terminal_contract_required() -> Self {
499        Self::query_executor_invariant(
500            "aggregate fold mode must match route fold-mode contract for aggregate terminal",
501        )
502    }
503
504    /// Construct a query-origin fast-stream invariant for missing exact key-count observability.
505    pub(crate) fn fast_stream_exact_key_count_required() -> Self {
506        Self::query_executor_invariant("fast-path stream must expose an exact key-count hint")
507    }
508
509    /// Construct a query-origin fast-stream invariant for route kind/request mismatch.
510    pub(crate) fn fast_stream_route_kind_request_match_required() -> Self {
511        Self::query_executor_invariant("fast-stream route kind/request mismatch")
512    }
513
514    /// Construct a query-origin scan invariant for missing index-prefix executable specs.
515    pub(crate) fn secondary_index_prefix_spec_required() -> Self {
516        Self::query_executor_invariant(
517            "index-prefix executable spec must be materialized for index-prefix plans",
518        )
519    }
520
521    /// Construct a query-origin scan invariant for missing index-range executable specs.
522    pub(crate) fn index_range_limit_spec_required() -> Self {
523        Self::query_executor_invariant(
524            "index-range executable spec must be materialized for index-range plans",
525        )
526    }
527
528    /// Construct a query-origin row-decode invariant for missing primary-key layout slots.
529    pub(crate) fn row_layout_primary_key_slot_required() -> Self {
530        Self::query_executor_invariant("row layout missing primary-key slot")
531    }
532
533    /// Construct an executor-origin mutation unsupported error for duplicate atomic save keys.
534    pub(crate) fn mutation_atomic_save_duplicate_key(
535        entity_path: &str,
536        key: impl fmt::Display,
537    ) -> Self {
538        Self::executor_unsupported(format!(
539            "atomic save batch rejected duplicate key: entity={entity_path} key={key}",
540        ))
541    }
542
543    /// Construct an executor-origin mutation invariant for index-store generation drift.
544    pub(crate) fn mutation_index_store_generation_changed(
545        expected_generation: u64,
546        observed_generation: u64,
547    ) -> Self {
548        Self::executor_invariant(format!(
549            "index store generation changed between preflight and apply: expected {expected_generation}, found {observed_generation}",
550        ))
551    }
552
553    /// Build the canonical executor-invariant message prefix.
554    #[must_use]
555    pub(crate) fn executor_invariant_message(reason: impl Into<String>) -> String {
556        format!("executor invariant violated: {}", reason.into())
557    }
558
559    /// Construct a planner-origin invariant violation.
560    pub(crate) fn planner_invariant(message: impl Into<String>) -> Self {
561        Self::new(
562            ErrorClass::InvariantViolation,
563            ErrorOrigin::Planner,
564            message.into(),
565        )
566    }
567
568    /// Build the canonical invalid-logical-plan message prefix.
569    #[must_use]
570    pub(crate) fn invalid_logical_plan_message(reason: impl Into<String>) -> String {
571        format!("invalid logical plan: {}", reason.into())
572    }
573
574    /// Construct a planner-origin invariant with the canonical invalid-plan prefix.
575    pub(crate) fn query_invalid_logical_plan(reason: impl Into<String>) -> Self {
576        Self::planner_invariant(Self::invalid_logical_plan_message(reason))
577    }
578
579    /// Construct a query-origin invariant violation.
580    pub(crate) fn query_invariant(message: impl Into<String>) -> Self {
581        Self::new(
582            ErrorClass::InvariantViolation,
583            ErrorOrigin::Query,
584            message.into(),
585        )
586    }
587
588    /// Construct a store-origin invariant violation.
589    pub(crate) fn store_invariant(message: impl Into<String>) -> Self {
590        Self::new(
591            ErrorClass::InvariantViolation,
592            ErrorOrigin::Store,
593            message.into(),
594        )
595    }
596
597    /// Construct the canonical duplicate runtime-hook entity-tag invariant.
598    pub(crate) fn duplicate_runtime_hooks_for_entity_tag(
599        entity_tag: crate::types::EntityTag,
600    ) -> Self {
601        Self::store_invariant(format!(
602            "duplicate runtime hooks for entity tag '{}'",
603            entity_tag.value()
604        ))
605    }
606
607    /// Construct the canonical duplicate runtime-hook entity-path invariant.
608    pub(crate) fn duplicate_runtime_hooks_for_entity_path(entity_path: &str) -> Self {
609        Self::store_invariant(format!(
610            "duplicate runtime hooks for entity path '{entity_path}'"
611        ))
612    }
613
614    /// Construct a store-origin internal error.
615    pub(crate) fn store_internal(message: impl Into<String>) -> Self {
616        Self::new(ErrorClass::Internal, ErrorOrigin::Store, message.into())
617    }
618
619    /// Construct the canonical unconfigured commit-memory id internal error.
620    pub(crate) fn commit_memory_id_unconfigured() -> Self {
621        Self::store_internal(
622            "commit memory id is not configured; initialize recovery before commit store access",
623        )
624    }
625
626    /// Construct the canonical commit-memory id mismatch internal error.
627    pub(crate) fn commit_memory_id_mismatch(cached_id: u8, configured_id: u8) -> Self {
628        Self::store_internal(format!(
629            "commit memory id mismatch: cached={cached_id}, configured={configured_id}",
630        ))
631    }
632
633    /// Construct the canonical memory-registry initialization failure for commit memory.
634    pub(crate) fn commit_memory_registry_init_failed(err: impl fmt::Display) -> Self {
635        Self::store_internal(format!("memory registry init failed: {err}"))
636    }
637
638    /// Construct the canonical migration cursor persistence-width internal error.
639    pub(crate) fn migration_next_step_index_u64_required(id: &str, version: u64) -> Self {
640        Self::store_internal(format!(
641            "migration '{id}@{version}' next step index does not fit persisted u64 cursor",
642        ))
643    }
644
645    /// Construct the canonical recovery-integrity totals corruption error.
646    pub(crate) fn recovery_integrity_validation_failed(
647        missing_index_entries: u64,
648        divergent_index_entries: u64,
649        orphan_index_references: u64,
650    ) -> Self {
651        Self::store_corruption(format!(
652            "recovery integrity validation failed: missing_index_entries={missing_index_entries} divergent_index_entries={divergent_index_entries} orphan_index_references={orphan_index_references}",
653        ))
654    }
655
656    /// Construct an index-origin internal error.
657    pub(crate) fn index_internal(message: impl Into<String>) -> Self {
658        Self::new(ErrorClass::Internal, ErrorOrigin::Index, message.into())
659    }
660
661    /// Construct the canonical missing old entity-key internal error for structural index removal.
662    pub(crate) fn structural_index_removal_entity_key_required() -> Self {
663        Self::index_internal("missing old entity key for structural index removal")
664    }
665
666    /// Construct the canonical missing new entity-key internal error for structural index insertion.
667    pub(crate) fn structural_index_insertion_entity_key_required() -> Self {
668        Self::index_internal("missing new entity key for structural index insertion")
669    }
670
671    /// Construct the canonical missing old entity-key internal error for index commit-op removal.
672    pub(crate) fn index_commit_op_old_entity_key_required() -> Self {
673        Self::index_internal("missing old entity key for index removal")
674    }
675
676    /// Construct the canonical missing new entity-key internal error for index commit-op insertion.
677    pub(crate) fn index_commit_op_new_entity_key_required() -> Self {
678        Self::index_internal("missing new entity key for index insertion")
679    }
680
681    /// Construct a query-origin internal error.
682    #[cfg(test)]
683    pub(crate) fn query_internal(message: impl Into<String>) -> Self {
684        Self::new(ErrorClass::Internal, ErrorOrigin::Query, message.into())
685    }
686
687    /// Construct a query-origin unsupported error.
688    pub(crate) fn query_unsupported(message: impl Into<String>) -> Self {
689        Self::new(ErrorClass::Unsupported, ErrorOrigin::Query, message.into())
690    }
691
692    /// Construct a serialize-origin internal error.
693    pub(crate) fn serialize_internal(message: impl Into<String>) -> Self {
694        Self::new(ErrorClass::Internal, ErrorOrigin::Serialize, message.into())
695    }
696
697    /// Construct the canonical persisted-row encode internal error.
698    pub(crate) fn persisted_row_encode_failed(detail: impl fmt::Display) -> Self {
699        Self::serialize_internal(format!("row encode failed: {detail}"))
700    }
701
702    /// Construct the canonical persisted-row field encode internal error.
703    pub(crate) fn persisted_row_field_encode_failed(
704        field_name: &str,
705        detail: impl fmt::Display,
706    ) -> Self {
707        Self::serialize_internal(format!(
708            "row encode failed for field '{field_name}': {detail}",
709        ))
710    }
711
712    /// Construct the canonical bytes(field) value encode internal error.
713    pub(crate) fn bytes_field_value_encode_failed(detail: impl fmt::Display) -> Self {
714        Self::serialize_internal(format!("bytes(field) value encode failed: {detail}"))
715    }
716
717    /// Construct the canonical migration-state serialization failure.
718    pub(crate) fn migration_state_serialize_failed(err: impl fmt::Display) -> Self {
719        Self::serialize_internal(format!("failed to serialize migration state: {err}"))
720    }
721
722    /// Construct a store-origin corruption error.
723    pub(crate) fn store_corruption(message: impl Into<String>) -> Self {
724        Self::new(ErrorClass::Corruption, ErrorOrigin::Store, message.into())
725    }
726
727    /// Construct the canonical multiple-commit-memory-ids corruption error.
728    pub(crate) fn multiple_commit_memory_ids_registered(ids: impl fmt::Debug) -> Self {
729        Self::store_corruption(format!(
730            "multiple commit marker memory ids registered: {ids:?}"
731        ))
732    }
733
734    /// Construct the canonical persisted migration-step index conversion corruption error.
735    pub(crate) fn migration_persisted_step_index_invalid_usize(
736        id: &str,
737        version: u64,
738        step_index: u64,
739    ) -> Self {
740        Self::store_corruption(format!(
741            "migration '{id}@{version}' persisted step index does not fit runtime usize: {step_index}",
742        ))
743    }
744
745    /// Construct the canonical persisted migration-step index bounds corruption error.
746    pub(crate) fn migration_persisted_step_index_out_of_bounds(
747        id: &str,
748        version: u64,
749        step_index: usize,
750        total_steps: usize,
751    ) -> Self {
752        Self::store_corruption(format!(
753            "migration '{id}@{version}' persisted step index out of bounds: {step_index} > {total_steps}",
754        ))
755    }
756
757    /// Construct a store-origin commit-marker corruption error.
758    pub(crate) fn commit_corruption(detail: impl fmt::Display) -> Self {
759        Self::store_corruption(format!("commit marker corrupted: {detail}"))
760    }
761
762    /// Construct a store-origin commit-marker component corruption error.
763    pub(crate) fn commit_component_corruption(component: &str, detail: impl fmt::Display) -> Self {
764        Self::store_corruption(format!("commit marker {component} corrupted: {detail}"))
765    }
766
767    /// Construct the canonical commit-marker id generation internal error.
768    pub(crate) fn commit_id_generation_failed(detail: impl fmt::Display) -> Self {
769        Self::store_internal(format!("commit id generation failed: {detail}"))
770    }
771
772    /// Construct the canonical commit-marker payload u32-length-limit error.
773    pub(crate) fn commit_marker_payload_exceeds_u32_length_limit(label: &str, len: usize) -> Self {
774        Self::store_unsupported(format!("{label} exceeds u32 length limit: {len} bytes"))
775    }
776
777    /// Construct the canonical commit-marker component invalid-length corruption error.
778    pub(crate) fn commit_component_length_invalid(
779        component: &str,
780        len: usize,
781        expected: impl fmt::Display,
782    ) -> Self {
783        Self::commit_component_corruption(
784            component,
785            format!("invalid length {len}, expected {expected}"),
786        )
787    }
788
789    /// Construct the canonical commit-marker max-size corruption error.
790    pub(crate) fn commit_marker_exceeds_max_size(size: usize, max_size: u32) -> Self {
791        Self::commit_corruption(format!(
792            "commit marker exceeds max size: {size} bytes (limit {max_size})",
793        ))
794    }
795
796    /// Construct the canonical pre-persist commit-marker max-size unsupported error.
797    pub(crate) fn commit_marker_exceeds_max_size_before_persist(
798        size: usize,
799        max_size: u32,
800    ) -> Self {
801        Self::store_unsupported(format!(
802            "commit marker exceeds max size: {size} bytes (limit {max_size})",
803        ))
804    }
805
806    /// Construct the canonical commit-control slot max-size unsupported error.
807    pub(crate) fn commit_control_slot_exceeds_max_size(size: usize, max_size: u32) -> Self {
808        Self::store_unsupported(format!(
809            "commit control slot exceeds max size: {size} bytes (limit {max_size})",
810        ))
811    }
812
813    /// Construct the canonical commit-control marker-bytes length-limit error.
814    pub(crate) fn commit_control_slot_marker_bytes_exceed_u32_length_limit(size: usize) -> Self {
815        Self::store_unsupported(format!(
816            "commit marker bytes exceed u32 length limit: {size} bytes",
817        ))
818    }
819
820    /// Construct the canonical commit-control migration-bytes length-limit error.
821    pub(crate) fn commit_control_slot_migration_bytes_exceed_u32_length_limit(size: usize) -> Self {
822        Self::store_unsupported(format!(
823            "commit migration bytes exceed u32 length limit: {size} bytes",
824        ))
825    }
826
827    /// Construct the canonical startup index-rebuild invalid-data-key corruption error.
828    pub(crate) fn startup_index_rebuild_invalid_data_key(
829        store_path: &str,
830        detail: impl fmt::Display,
831    ) -> Self {
832        Self::store_corruption(format!(
833            "startup index rebuild failed: invalid data key in store '{store_path}' ({detail})",
834        ))
835    }
836
837    /// Construct an index-origin corruption error.
838    pub(crate) fn index_corruption(message: impl Into<String>) -> Self {
839        Self::new(ErrorClass::Corruption, ErrorOrigin::Index, message.into())
840    }
841
842    /// Construct the canonical unique-validation corruption wrapper.
843    pub(crate) fn index_unique_validation_corruption(
844        entity_path: &str,
845        fields: &str,
846        detail: impl fmt::Display,
847    ) -> Self {
848        Self::index_plan_index_corruption(format!(
849            "index corrupted: {entity_path} ({fields}) -> {detail}",
850        ))
851    }
852
853    /// Construct the canonical structural index-entry corruption wrapper.
854    pub(crate) fn structural_index_entry_corruption(
855        entity_path: &str,
856        fields: &str,
857        detail: impl fmt::Display,
858    ) -> Self {
859        Self::index_plan_index_corruption(format!(
860            "index corrupted: {entity_path} ({fields}) -> {detail}",
861        ))
862    }
863
864    /// Construct the canonical missing new entity-key invariant during unique validation.
865    pub(crate) fn index_unique_validation_entity_key_required() -> Self {
866        Self::index_invariant("missing entity key during unique validation")
867    }
868
869    /// Construct the canonical missing key-component invariant during unique validation.
870    pub(crate) fn index_unique_validation_key_component_missing(
871        component_index: usize,
872        entity_path: &str,
873        fields: &str,
874    ) -> Self {
875        Self::index_invariant(format!(
876            "index key missing component {component_index} during unique validation: {entity_path} ({fields})",
877        ))
878    }
879
880    /// Construct the canonical missing expected key-component invariant during unique validation.
881    pub(crate) fn index_unique_validation_expected_component_missing(
882        component_index: usize,
883        entity_path: &str,
884        fields: &str,
885    ) -> Self {
886        Self::index_invariant(format!(
887            "index key missing expected component {component_index} during unique validation: {entity_path} ({fields})",
888        ))
889    }
890
891    /// Construct the canonical missing primary-key field invariant during unique validation.
892    pub(crate) fn index_unique_validation_primary_key_field_missing(
893        entity_path: &str,
894        primary_key_name: &str,
895    ) -> Self {
896        Self::index_invariant(format!(
897            "entity primary key field missing during unique validation: {entity_path} field={primary_key_name}",
898        ))
899    }
900
901    /// Construct the canonical unique-validation structural row-decode corruption error.
902    pub(crate) fn index_unique_validation_row_deserialize_failed(
903        data_key: impl fmt::Display,
904        source: impl fmt::Display,
905    ) -> Self {
906        Self::index_plan_serialize_corruption(format!(
907            "failed to structurally deserialize row: {data_key} ({source})"
908        ))
909    }
910
911    /// Construct the canonical unique-validation primary-key slot decode corruption error.
912    pub(crate) fn index_unique_validation_primary_key_decode_failed(
913        data_key: impl fmt::Display,
914        source: impl fmt::Display,
915    ) -> Self {
916        Self::index_plan_serialize_corruption(format!(
917            "failed to decode structural primary-key slot: {data_key} ({source})"
918        ))
919    }
920
921    /// Construct the canonical unique-validation stored key rebuild corruption error.
922    pub(crate) fn index_unique_validation_key_rebuild_failed(
923        data_key: impl fmt::Display,
924        entity_path: &str,
925        source: impl fmt::Display,
926    ) -> Self {
927        Self::index_plan_serialize_corruption(format!(
928            "failed to structurally decode unique key row {data_key} for {entity_path}: {source}",
929        ))
930    }
931
932    /// Construct the canonical unique-validation missing-row corruption error.
933    pub(crate) fn index_unique_validation_row_required(data_key: impl fmt::Display) -> Self {
934        Self::index_plan_store_corruption(format!("missing row: {data_key}"))
935    }
936
937    /// Construct the canonical unique-validation row-key invariant error.
938    pub(crate) fn index_unique_validation_row_key_mismatch(
939        entity_path: &str,
940        fields: &str,
941        detail: impl fmt::Display,
942    ) -> Self {
943        Self::index_plan_store_invariant(format!(
944            "index invariant violated: {entity_path} ({fields}) -> {detail}",
945        ))
946    }
947
948    /// Construct the canonical structural index-predicate parse invariant.
949    pub(crate) fn index_predicate_parse_failed(
950        entity_path: &str,
951        index_name: &str,
952        predicate_sql: &str,
953        err: impl fmt::Display,
954    ) -> Self {
955        Self::index_invariant(format!(
956            "index predicate parse failed: {entity_path} ({index_name}) WHERE {predicate_sql} -> {err}",
957        ))
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 failed: {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-slot-missing invariant.
1129    pub(crate) fn persisted_row_primary_key_field_missing(model_path: &str) -> Self {
1130        Self::index_invariant(format!(
1131            "entity primary key field missing during structural row validation: {model_path}",
1132        ))
1133    }
1134
1135    /// Construct the canonical persisted-row primary-key decode corruption error.
1136    pub(crate) fn persisted_row_primary_key_not_storage_encodable(
1137        data_key: impl fmt::Display,
1138        detail: impl fmt::Display,
1139    ) -> Self {
1140        Self::persisted_row_decode_failed(format!(
1141            "primary-key value is not storage-key encodable: {data_key} ({detail})",
1142        ))
1143    }
1144
1145    /// Construct the canonical persisted-row missing primary-key slot corruption error.
1146    pub(crate) fn persisted_row_primary_key_slot_missing(data_key: impl fmt::Display) -> Self {
1147        Self::persisted_row_decode_failed(format!(
1148            "missing primary-key slot while validating {data_key}",
1149        ))
1150    }
1151
1152    /// Construct the canonical persisted-row key mismatch corruption error.
1153    pub(crate) fn persisted_row_key_mismatch(
1154        expected_key: impl fmt::Display,
1155        found_key: impl fmt::Display,
1156    ) -> Self {
1157        Self::store_corruption(format!(
1158            "row key mismatch: expected {expected_key}, found {found_key}",
1159        ))
1160    }
1161
1162    /// Construct the canonical row-decoder missing-field corruption error.
1163    pub(crate) fn row_decode_declared_field_missing(field_name: &str) -> Self {
1164        Self::persisted_row_decode_failed(format!("missing declared field `{field_name}`"))
1165    }
1166
1167    /// Construct the canonical row-decoder field-decode corruption error.
1168    pub(crate) fn row_decode_field_decode_failed(
1169        field_name: &str,
1170        field_kind: impl fmt::Debug,
1171        detail: impl fmt::Display,
1172    ) -> Self {
1173        Self::serialize_corruption(format!(
1174            "row decode failed for field '{field_name}' kind={field_kind:?}: {detail}",
1175        ))
1176    }
1177
1178    /// Construct the canonical row-decoder missing primary-key slot corruption error.
1179    pub(crate) fn row_decode_primary_key_slot_missing() -> Self {
1180        Self::persisted_row_decode_failed("missing primary-key slot value")
1181    }
1182
1183    /// Construct the canonical row-decoder primary-key encoding corruption error.
1184    pub(crate) fn row_decode_primary_key_not_storage_encodable(detail: impl fmt::Display) -> Self {
1185        Self::persisted_row_decode_failed(format!(
1186            "primary-key value is not storage-key encodable: {detail}",
1187        ))
1188    }
1189
1190    /// Construct the canonical row-decoder key-mismatch corruption error.
1191    pub(crate) fn row_decode_key_mismatch(
1192        expected_key: impl fmt::Display,
1193        found_key: impl fmt::Display,
1194    ) -> Self {
1195        Self::persisted_row_key_mismatch(expected_key, found_key)
1196    }
1197
1198    /// Construct the canonical data-key entity mismatch corruption error.
1199    pub(crate) fn data_key_entity_mismatch(
1200        expected: impl fmt::Display,
1201        found: impl fmt::Display,
1202    ) -> Self {
1203        Self::store_corruption(format!(
1204            "data key entity mismatch: expected {expected}, found {found}",
1205        ))
1206    }
1207
1208    /// Construct the canonical data-key primary-key decode corruption error.
1209    pub(crate) fn data_key_primary_key_decode_failed(value: impl fmt::Debug) -> Self {
1210        Self::store_corruption(format!("data key primary key decode failed: {value:?}",))
1211    }
1212
1213    /// Construct the canonical reverse-index ordinal overflow internal error.
1214    pub(crate) fn reverse_index_ordinal_overflow(
1215        source_path: &str,
1216        field_name: &str,
1217        target_path: &str,
1218        detail: impl fmt::Display,
1219    ) -> Self {
1220        Self::index_internal(format!(
1221            "reverse index ordinal overflow: source={source_path} field={field_name} target={target_path} ({detail})",
1222        ))
1223    }
1224
1225    /// Construct the canonical reverse-index entry corruption error.
1226    pub(crate) fn reverse_index_entry_corrupted(
1227        source_path: &str,
1228        field_name: &str,
1229        target_path: &str,
1230        index_key: impl fmt::Debug,
1231        detail: impl fmt::Display,
1232    ) -> Self {
1233        Self::index_corruption(format!(
1234            "reverse index entry corrupted: source={source_path} field={field_name} target={target_path} key={index_key:?} ({detail})",
1235        ))
1236    }
1237
1238    /// Construct the canonical reverse-index entry encode unsupported error.
1239    pub(crate) fn reverse_index_entry_encode_failed(
1240        source_path: &str,
1241        field_name: &str,
1242        target_path: &str,
1243        detail: impl fmt::Display,
1244    ) -> Self {
1245        Self::index_unsupported(format!(
1246            "reverse index entry encoding failed: source={source_path} field={field_name} target={target_path} ({detail})",
1247        ))
1248    }
1249
1250    /// Construct the canonical relation-target store missing internal error.
1251    pub(crate) fn relation_target_store_missing(
1252        source_path: &str,
1253        field_name: &str,
1254        target_path: &str,
1255        store_path: &str,
1256        detail: impl fmt::Display,
1257    ) -> Self {
1258        Self::executor_internal(format!(
1259            "relation target store missing: source={source_path} field={field_name} target={target_path} store={store_path} ({detail})",
1260        ))
1261    }
1262
1263    /// Construct the canonical relation-target key decode corruption error.
1264    pub(crate) fn relation_target_key_decode_failed(
1265        context_label: &str,
1266        source_path: &str,
1267        field_name: &str,
1268        target_path: &str,
1269        detail: impl fmt::Display,
1270    ) -> Self {
1271        Self::identity_corruption(format!(
1272            "{context_label}: source={source_path} field={field_name} target={target_path} ({detail})",
1273        ))
1274    }
1275
1276    /// Construct the canonical relation-target entity mismatch corruption error.
1277    pub(crate) fn relation_target_entity_mismatch(
1278        context_label: &str,
1279        source_path: &str,
1280        field_name: &str,
1281        target_path: &str,
1282        target_entity_name: &str,
1283        expected_tag: impl fmt::Display,
1284        actual_tag: impl fmt::Display,
1285    ) -> Self {
1286        Self::store_corruption(format!(
1287            "{context_label}: source={source_path} field={field_name} target={target_path} expected={target_entity_name} (tag={expected_tag}) actual_tag={actual_tag}",
1288        ))
1289    }
1290
1291    /// Construct the canonical relation-source row missing-field corruption error.
1292    pub(crate) fn relation_source_row_missing_field(
1293        source_path: &str,
1294        field_name: &str,
1295        target_path: &str,
1296    ) -> Self {
1297        Self::serialize_corruption(format!(
1298            "relation source row decode failed: missing field: source={source_path} field={field_name} target={target_path}",
1299        ))
1300    }
1301
1302    /// Construct the canonical relation-source row decode corruption error.
1303    pub(crate) fn relation_source_row_decode_failed(
1304        source_path: &str,
1305        field_name: &str,
1306        target_path: &str,
1307        detail: impl fmt::Display,
1308    ) -> Self {
1309        Self::serialize_corruption(format!(
1310            "relation source row decode failed: source={source_path} field={field_name} target={target_path} ({detail})",
1311        ))
1312    }
1313
1314    /// Construct the canonical relation-source unsupported scalar relation-key corruption error.
1315    pub(crate) fn relation_source_row_unsupported_scalar_relation_key(
1316        source_path: &str,
1317        field_name: &str,
1318        target_path: &str,
1319    ) -> Self {
1320        Self::serialize_corruption(format!(
1321            "relation source row decode failed: unsupported scalar relation key: source={source_path} field={field_name} target={target_path}",
1322        ))
1323    }
1324
1325    /// Construct the canonical invalid strong-relation field-kind corruption error.
1326    pub(crate) fn relation_source_row_invalid_field_kind(field_kind: impl fmt::Debug) -> Self {
1327        Self::serialize_corruption(format!(
1328            "invalid strong relation field kind during structural decode: {field_kind:?}"
1329        ))
1330    }
1331
1332    /// Construct the canonical unsupported strong-relation key-kind corruption error.
1333    pub(crate) fn relation_source_row_unsupported_key_kind(field_kind: impl fmt::Debug) -> Self {
1334        Self::serialize_corruption(format!(
1335            "unsupported strong relation key kind during structural decode: {field_kind:?}"
1336        ))
1337    }
1338
1339    /// Construct the canonical reverse-index relation-target decode invariant failure.
1340    pub(crate) fn reverse_index_relation_target_decode_invariant_violated(
1341        source_path: &str,
1342        field_name: &str,
1343        target_path: &str,
1344    ) -> Self {
1345        Self::executor_internal(format!(
1346            "relation target decode invariant violated while preparing reverse index: source={source_path} field={field_name} target={target_path}",
1347        ))
1348    }
1349
1350    /// Construct the canonical covering-component empty-payload corruption error.
1351    pub(crate) fn bytes_covering_component_payload_empty() -> Self {
1352        Self::index_corruption("index component payload is empty during covering projection decode")
1353    }
1354
1355    /// Construct the canonical covering-component truncated bool corruption error.
1356    pub(crate) fn bytes_covering_bool_payload_truncated() -> Self {
1357        Self::index_corruption("bool covering component payload is truncated")
1358    }
1359
1360    /// Construct the canonical covering-component invalid-length corruption error.
1361    pub(crate) fn bytes_covering_component_payload_invalid_length(payload_kind: &str) -> Self {
1362        Self::index_corruption(format!(
1363            "{payload_kind} covering component payload has invalid length"
1364        ))
1365    }
1366
1367    /// Construct the canonical covering-component invalid-bool corruption error.
1368    pub(crate) fn bytes_covering_bool_payload_invalid_value() -> Self {
1369        Self::index_corruption("bool covering component payload has invalid value")
1370    }
1371
1372    /// Construct the canonical covering-component invalid text terminator corruption error.
1373    pub(crate) fn bytes_covering_text_payload_invalid_terminator() -> Self {
1374        Self::index_corruption("text covering component payload has invalid terminator")
1375    }
1376
1377    /// Construct the canonical covering-component trailing-text corruption error.
1378    pub(crate) fn bytes_covering_text_payload_trailing_bytes() -> Self {
1379        Self::index_corruption("text covering component payload contains trailing bytes")
1380    }
1381
1382    /// Construct the canonical covering-component invalid-UTF-8 text corruption error.
1383    pub(crate) fn bytes_covering_text_payload_invalid_utf8() -> Self {
1384        Self::index_corruption("text covering component payload is not valid UTF-8")
1385    }
1386
1387    /// Construct the canonical covering-component invalid text escape corruption error.
1388    pub(crate) fn bytes_covering_text_payload_invalid_escape_byte() -> Self {
1389        Self::index_corruption("text covering component payload has invalid escape byte")
1390    }
1391
1392    /// Construct the canonical covering-component missing text terminator corruption error.
1393    pub(crate) fn bytes_covering_text_payload_missing_terminator() -> Self {
1394        Self::index_corruption("text covering component payload is missing terminator")
1395    }
1396
1397    /// Construct the canonical missing persisted-field decode error.
1398    #[must_use]
1399    pub fn missing_persisted_slot(field_name: &'static str) -> Self {
1400        Self::serialize_corruption(format!(
1401            "row decode failed: missing required field '{field_name}'",
1402        ))
1403    }
1404
1405    /// Construct an identity-origin corruption error.
1406    pub(crate) fn identity_corruption(message: impl Into<String>) -> Self {
1407        Self::new(
1408            ErrorClass::Corruption,
1409            ErrorOrigin::Identity,
1410            message.into(),
1411        )
1412    }
1413
1414    /// Construct a store-origin unsupported error.
1415    pub(crate) fn store_unsupported(message: impl Into<String>) -> Self {
1416        Self::new(ErrorClass::Unsupported, ErrorOrigin::Store, message.into())
1417    }
1418
1419    /// Construct the canonical empty migration label unsupported error.
1420    pub(crate) fn migration_label_empty(label: &str) -> Self {
1421        Self::store_unsupported(format!("{label} cannot be empty"))
1422    }
1423
1424    /// Construct the canonical empty migration-step row-op set unsupported error.
1425    pub(crate) fn migration_step_row_ops_required(name: &str) -> Self {
1426        Self::store_unsupported(format!(
1427            "migration step '{name}' must include at least one row op",
1428        ))
1429    }
1430
1431    /// Construct the canonical invalid migration-plan version unsupported error.
1432    pub(crate) fn migration_plan_version_required(id: &str) -> Self {
1433        Self::store_unsupported(format!("migration plan '{id}' version must be > 0",))
1434    }
1435
1436    /// Construct the canonical empty migration-plan steps unsupported error.
1437    pub(crate) fn migration_plan_steps_required(id: &str) -> Self {
1438        Self::store_unsupported(format!(
1439            "migration plan '{id}' must include at least one step",
1440        ))
1441    }
1442
1443    /// Construct the canonical migration cursor out-of-bounds unsupported error.
1444    pub(crate) fn migration_cursor_out_of_bounds(
1445        id: &str,
1446        version: u64,
1447        next_step: usize,
1448        total_steps: usize,
1449    ) -> Self {
1450        Self::store_unsupported(format!(
1451            "migration '{id}@{version}' cursor out of bounds: next_step={next_step} total_steps={total_steps}",
1452        ))
1453    }
1454
1455    /// Construct the canonical max-steps-required migration execution error.
1456    pub(crate) fn migration_execution_requires_max_steps(id: &str) -> Self {
1457        Self::store_unsupported(format!("migration '{id}' execution requires max_steps > 0",))
1458    }
1459
1460    /// Construct the canonical in-progress migration-plan conflict error.
1461    pub(crate) fn migration_in_progress_conflict(
1462        requested_id: &str,
1463        requested_version: u64,
1464        active_id: &str,
1465        active_version: u64,
1466    ) -> Self {
1467        Self::store_unsupported(format!(
1468            "migration '{requested_id}@{requested_version}' cannot execute while migration '{active_id}@{active_version}' is in progress",
1469        ))
1470    }
1471
1472    /// Construct the canonical unsupported persisted entity-tag store error.
1473    pub(crate) fn unsupported_entity_tag_in_data_store(
1474        entity_tag: crate::types::EntityTag,
1475    ) -> Self {
1476        Self::store_unsupported(format!(
1477            "unsupported entity tag in data store: '{}'",
1478            entity_tag.value()
1479        ))
1480    }
1481
1482    /// Construct the canonical configured-vs-registered commit-memory id mismatch error.
1483    pub(crate) fn configured_commit_memory_id_mismatch(
1484        configured_id: u8,
1485        registered_id: u8,
1486    ) -> Self {
1487        Self::store_unsupported(format!(
1488            "configured commit memory id {configured_id} does not match existing commit marker id {registered_id}",
1489        ))
1490    }
1491
1492    /// Construct the canonical occupied commit-memory id unsupported error.
1493    pub(crate) fn commit_memory_id_already_registered(memory_id: u8, label: &str) -> Self {
1494        Self::store_unsupported(format!(
1495            "configured commit memory id {memory_id} is already registered as '{label}'",
1496        ))
1497    }
1498
1499    /// Construct the canonical out-of-range commit-memory id unsupported error.
1500    pub(crate) fn commit_memory_id_outside_reserved_ranges(memory_id: u8) -> Self {
1501        Self::store_unsupported(format!(
1502            "configured commit memory id {memory_id} is outside reserved ranges",
1503        ))
1504    }
1505
1506    /// Construct the canonical commit-memory id registration failure.
1507    pub(crate) fn commit_memory_id_registration_failed(err: impl fmt::Display) -> Self {
1508        Self::store_internal(format!("commit memory id registration failed: {err}"))
1509    }
1510
1511    /// Construct an index-origin unsupported error.
1512    pub(crate) fn index_unsupported(message: impl Into<String>) -> Self {
1513        Self::new(ErrorClass::Unsupported, ErrorOrigin::Index, message.into())
1514    }
1515
1516    /// Construct the canonical index-key component size-limit unsupported error.
1517    pub(crate) fn index_component_exceeds_max_size(
1518        key_item: impl fmt::Display,
1519        len: usize,
1520        max_component_size: usize,
1521    ) -> Self {
1522        Self::index_unsupported(format!(
1523            "index component exceeds max size: key item '{key_item}' -> {len} bytes (limit {max_component_size})",
1524        ))
1525    }
1526
1527    /// Construct the canonical index-entry max-keys unsupported error during commit encoding.
1528    pub(crate) fn index_entry_exceeds_max_keys(
1529        entity_path: &str,
1530        fields: &str,
1531        keys: usize,
1532    ) -> Self {
1533        Self::index_unsupported(format!(
1534            "index entry exceeds max keys: {entity_path} ({fields}) -> {keys} keys",
1535        ))
1536    }
1537
1538    /// Construct the canonical duplicate-key invariant during commit entry encoding.
1539    pub(crate) fn index_entry_duplicate_keys_unexpected(entity_path: &str, fields: &str) -> Self {
1540        Self::index_invariant(format!(
1541            "index entry unexpectedly contains duplicate keys: {entity_path} ({fields})",
1542        ))
1543    }
1544
1545    /// Construct the canonical index-entry key-encoding unsupported error during commit encoding.
1546    pub(crate) fn index_entry_key_encoding_failed(
1547        entity_path: &str,
1548        fields: &str,
1549        err: impl fmt::Display,
1550    ) -> Self {
1551        Self::index_unsupported(format!(
1552            "index entry key encoding failed: {entity_path} ({fields}) -> {err}",
1553        ))
1554    }
1555
1556    /// Construct a serialize-origin unsupported error.
1557    pub(crate) fn serialize_unsupported(message: impl Into<String>) -> Self {
1558        Self::new(
1559            ErrorClass::Unsupported,
1560            ErrorOrigin::Serialize,
1561            message.into(),
1562        )
1563    }
1564
1565    /// Construct a cursor-origin unsupported error.
1566    pub(crate) fn cursor_unsupported(message: impl Into<String>) -> Self {
1567        Self::new(ErrorClass::Unsupported, ErrorOrigin::Cursor, message.into())
1568    }
1569
1570    /// Construct a serialize-origin incompatible persisted-format error.
1571    pub(crate) fn serialize_incompatible_persisted_format(message: impl Into<String>) -> Self {
1572        Self::new(
1573            ErrorClass::IncompatiblePersistedFormat,
1574            ErrorOrigin::Serialize,
1575            message.into(),
1576        )
1577    }
1578
1579    /// Construct the canonical persisted-payload decode failure mapping for one
1580    /// DB-owned serialized payload boundary.
1581    pub(crate) fn serialize_payload_decode_failed(
1582        source: SerializeError,
1583        payload_label: &'static str,
1584    ) -> Self {
1585        match source {
1586            // DB codec only decodes engine-owned persisted payloads.
1587            // Size-limit breaches indicate persisted bytes violate DB storage policy.
1588            SerializeError::DeserializeSizeLimitExceeded { len, max_bytes } => {
1589                Self::serialize_corruption(format!(
1590                    "{payload_label} decode failed: payload size {len} exceeds limit {max_bytes}"
1591                ))
1592            }
1593            SerializeError::Deserialize(_) => Self::serialize_corruption(format!(
1594                "{payload_label} decode failed: {}",
1595                SerializeErrorKind::Deserialize
1596            )),
1597            SerializeError::Serialize(_) => Self::serialize_corruption(format!(
1598                "{payload_label} decode failed: {}",
1599                SerializeErrorKind::Serialize
1600            )),
1601        }
1602    }
1603
1604    /// Construct a query-origin unsupported error preserving one SQL parser
1605    /// unsupported-feature label in structured error detail.
1606    #[cfg(feature = "sql")]
1607    pub(crate) fn query_unsupported_sql_feature(feature: &'static str) -> Self {
1608        let message = format!(
1609            "SQL query is not executable in this release: unsupported SQL feature: {feature}"
1610        );
1611
1612        Self {
1613            class: ErrorClass::Unsupported,
1614            origin: ErrorOrigin::Query,
1615            message,
1616            detail: Some(ErrorDetail::Query(
1617                QueryErrorDetail::UnsupportedSqlFeature { feature },
1618            )),
1619        }
1620    }
1621
1622    pub fn store_not_found(key: impl Into<String>) -> Self {
1623        let key = key.into();
1624
1625        Self {
1626            class: ErrorClass::NotFound,
1627            origin: ErrorOrigin::Store,
1628            message: format!("data key not found: {key}"),
1629            detail: Some(ErrorDetail::Store(StoreError::NotFound { key })),
1630        }
1631    }
1632
1633    /// Construct a standardized unsupported-entity-path error.
1634    pub fn unsupported_entity_path(path: impl Into<String>) -> Self {
1635        let path = path.into();
1636
1637        Self::new(
1638            ErrorClass::Unsupported,
1639            ErrorOrigin::Store,
1640            format!("unsupported entity path: '{path}'"),
1641        )
1642    }
1643
1644    #[must_use]
1645    pub const fn is_not_found(&self) -> bool {
1646        matches!(
1647            self.detail,
1648            Some(ErrorDetail::Store(StoreError::NotFound { .. }))
1649        )
1650    }
1651
1652    #[must_use]
1653    pub fn display_with_class(&self) -> String {
1654        format!("{}:{}: {}", self.origin, self.class, self.message)
1655    }
1656
1657    /// Construct an index-plan corruption error with a canonical prefix.
1658    pub(crate) fn index_plan_corruption(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1659        let message = message.into();
1660        Self::new(
1661            ErrorClass::Corruption,
1662            origin,
1663            format!("corruption detected ({origin}): {message}"),
1664        )
1665    }
1666
1667    /// Construct an index-plan corruption error for index-origin failures.
1668    pub(crate) fn index_plan_index_corruption(message: impl Into<String>) -> Self {
1669        Self::index_plan_corruption(ErrorOrigin::Index, message)
1670    }
1671
1672    /// Construct an index-plan corruption error for store-origin failures.
1673    pub(crate) fn index_plan_store_corruption(message: impl Into<String>) -> Self {
1674        Self::index_plan_corruption(ErrorOrigin::Store, message)
1675    }
1676
1677    /// Construct an index-plan corruption error for serialize-origin failures.
1678    pub(crate) fn index_plan_serialize_corruption(message: impl Into<String>) -> Self {
1679        Self::index_plan_corruption(ErrorOrigin::Serialize, message)
1680    }
1681
1682    /// Construct an index-plan invariant violation error with a canonical prefix.
1683    pub(crate) fn index_plan_invariant(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1684        let message = message.into();
1685        Self::new(
1686            ErrorClass::InvariantViolation,
1687            origin,
1688            format!("invariant violation detected ({origin}): {message}"),
1689        )
1690    }
1691
1692    /// Construct an index-plan invariant violation error for store-origin failures.
1693    pub(crate) fn index_plan_store_invariant(message: impl Into<String>) -> Self {
1694        Self::index_plan_invariant(ErrorOrigin::Store, message)
1695    }
1696
1697    /// Construct an index uniqueness violation conflict error.
1698    pub(crate) fn index_violation(path: &str, index_fields: &[&str]) -> Self {
1699        Self::new(
1700            ErrorClass::Conflict,
1701            ErrorOrigin::Index,
1702            format!(
1703                "index constraint violation: {path} ({})",
1704                index_fields.join(", ")
1705            ),
1706        )
1707    }
1708}
1709
1710///
1711/// ErrorDetail
1712///
1713/// Structured, origin-specific error detail carried by [`InternalError`].
1714/// This enum is intentionally extensible.
1715///
1716
1717#[derive(Debug, ThisError)]
1718pub enum ErrorDetail {
1719    #[error("{0}")]
1720    Store(StoreError),
1721    #[error("{0}")]
1722    Query(QueryErrorDetail),
1723    // Future-proofing:
1724    // #[error("{0}")]
1725    // Index(IndexError),
1726    //
1727    // #[error("{0}")]
1728    // Executor(ExecutorErrorDetail),
1729}
1730
1731///
1732/// StoreError
1733///
1734/// Store-specific structured error detail.
1735/// Never returned directly; always wrapped in [`ErrorDetail::Store`].
1736///
1737
1738#[derive(Debug, ThisError)]
1739pub enum StoreError {
1740    #[error("key not found: {key}")]
1741    NotFound { key: String },
1742
1743    #[error("store corruption: {message}")]
1744    Corrupt { message: String },
1745
1746    #[error("store invariant violation: {message}")]
1747    InvariantViolation { message: String },
1748}
1749
1750///
1751/// QueryErrorDetail
1752///
1753/// Query-origin structured error detail payload.
1754///
1755
1756#[derive(Debug, ThisError)]
1757pub enum QueryErrorDetail {
1758    #[error("unsupported SQL feature: {feature}")]
1759    UnsupportedSqlFeature { feature: &'static str },
1760}
1761
1762///
1763/// ErrorClass
1764/// Internal error taxonomy for runtime classification.
1765/// Not a stable API; may change without notice.
1766///
1767
1768#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1769pub enum ErrorClass {
1770    Corruption,
1771    IncompatiblePersistedFormat,
1772    NotFound,
1773    Internal,
1774    Conflict,
1775    Unsupported,
1776    InvariantViolation,
1777}
1778
1779impl fmt::Display for ErrorClass {
1780    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1781        let label = match self {
1782            Self::Corruption => "corruption",
1783            Self::IncompatiblePersistedFormat => "incompatible_persisted_format",
1784            Self::NotFound => "not_found",
1785            Self::Internal => "internal",
1786            Self::Conflict => "conflict",
1787            Self::Unsupported => "unsupported",
1788            Self::InvariantViolation => "invariant_violation",
1789        };
1790        write!(f, "{label}")
1791    }
1792}
1793
1794///
1795/// ErrorOrigin
1796/// Internal origin taxonomy for runtime classification.
1797/// Not a stable API; may change without notice.
1798///
1799
1800#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1801pub enum ErrorOrigin {
1802    Serialize,
1803    Store,
1804    Index,
1805    Identity,
1806    Query,
1807    Planner,
1808    Cursor,
1809    Recovery,
1810    Response,
1811    Executor,
1812    Interface,
1813}
1814
1815impl fmt::Display for ErrorOrigin {
1816    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1817        let label = match self {
1818            Self::Serialize => "serialize",
1819            Self::Store => "store",
1820            Self::Index => "index",
1821            Self::Identity => "identity",
1822            Self::Query => "query",
1823            Self::Planner => "planner",
1824            Self::Cursor => "cursor",
1825            Self::Recovery => "recovery",
1826            Self::Response => "response",
1827            Self::Executor => "executor",
1828            Self::Interface => "interface",
1829        };
1830        write!(f, "{label}")
1831    }
1832}