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