Skip to main content

icydb_core/error/
mod.rs

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