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