Skip to main content

icydb_core/error/
mod.rs

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