Skip to main content

icydb_core/error/
mod.rs

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