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 sparse structural patch required-field invariant.
382    pub(crate) fn mutation_structural_patch_required_field_missing(
383        entity_path: &str,
384        field_name: &str,
385    ) -> Self {
386        Self::executor_invariant(format!(
387            "structural patch missing required field: {entity_path} field={field_name}",
388        ))
389    }
390
391    /// Construct an executor-origin save-preflight field-type mismatch invariant.
392    pub(crate) fn mutation_entity_field_type_mismatch(
393        entity_path: &str,
394        field_name: &str,
395        value: &crate::value::Value,
396    ) -> Self {
397        Self::executor_invariant(format!(
398            "entity field type mismatch: {entity_path} field={field_name} value={value:?}",
399        ))
400    }
401
402    /// Construct an executor-origin generated-field authored-write rejection.
403    pub(crate) fn mutation_generated_field_explicit(entity_path: &str, field_name: &str) -> Self {
404        Self::executor_unsupported(format!(
405            "generated field may not be explicitly written: {entity_path} field={field_name}",
406        ))
407    }
408
409    /// Construct an executor-origin typed create omission rejection.
410    pub(crate) fn mutation_create_missing_authored_fields(
411        entity_path: &str,
412        field_names: &str,
413    ) -> Self {
414        Self::executor_unsupported(format!(
415            "create requires explicit values for authorable fields {field_names}: {entity_path}",
416        ))
417    }
418
419    /// Construct an executor-origin mutation result invariant.
420    ///
421    /// This constructor lands ahead of the public structural mutation surface,
422    /// so the library target may not route through it until that caller exists.
423    pub(crate) fn mutation_structural_after_image_invalid(
424        entity_path: &str,
425        data_key: impl fmt::Display,
426        detail: impl AsRef<str>,
427    ) -> Self {
428        Self::executor_invariant(format!(
429            "mutation result is invalid: {entity_path} key={data_key} ({})",
430            detail.as_ref(),
431        ))
432    }
433
434    /// Construct an executor-origin mutation unknown-field invariant.
435    pub(crate) fn mutation_structural_field_unknown(entity_path: &str, field_name: &str) -> Self {
436        Self::executor_invariant(format!(
437            "mutation field not found: {entity_path} field={field_name}",
438        ))
439    }
440
441    /// Construct an executor-origin save-preflight decimal-scale unsupported error.
442    pub(crate) fn mutation_decimal_scale_mismatch(
443        entity_path: &str,
444        field_name: &str,
445        expected_scale: impl fmt::Display,
446        actual_scale: impl fmt::Display,
447    ) -> Self {
448        Self::executor_unsupported(format!(
449            "decimal field scale mismatch: {entity_path} field={field_name} expected_scale={expected_scale} actual_scale={actual_scale}",
450        ))
451    }
452
453    /// Construct an executor-origin save-preflight text-length unsupported error.
454    pub(crate) fn mutation_text_max_len_exceeded(
455        entity_path: &str,
456        field_name: &str,
457        max_len: impl fmt::Display,
458        actual_len: impl fmt::Display,
459    ) -> Self {
460        Self::executor_unsupported(format!(
461            "text length exceeds max_len: {entity_path} field={field_name} max_len={max_len} actual_len={actual_len}",
462        ))
463    }
464
465    /// Construct an executor-origin save-preflight set-encoding invariant.
466    pub(crate) fn mutation_set_field_list_required(entity_path: &str, field_name: &str) -> Self {
467        Self::executor_invariant(format!(
468            "set field must encode as Value::List: {entity_path} field={field_name}",
469        ))
470    }
471
472    /// Construct an executor-origin save-preflight set-canonicality invariant.
473    pub(crate) fn mutation_set_field_not_canonical(entity_path: &str, field_name: &str) -> Self {
474        Self::executor_invariant(format!(
475            "set field must be strictly ordered and deduplicated: {entity_path} field={field_name}",
476        ))
477    }
478
479    /// Construct an executor-origin save-preflight map-encoding invariant.
480    pub(crate) fn mutation_map_field_map_required(entity_path: &str, field_name: &str) -> Self {
481        Self::executor_invariant(format!(
482            "map field must encode as Value::Map: {entity_path} field={field_name}",
483        ))
484    }
485
486    /// Construct an executor-origin save-preflight map-entry invariant.
487    pub(crate) fn mutation_map_field_entries_invalid(
488        entity_path: &str,
489        field_name: &str,
490        detail: impl fmt::Display,
491    ) -> Self {
492        Self::executor_invariant(format!(
493            "map field entries violate map invariants: {entity_path} field={field_name} ({detail})",
494        ))
495    }
496
497    /// Construct an executor-origin save-preflight map-canonicality invariant.
498    pub(crate) fn mutation_map_field_entries_not_canonical(
499        entity_path: &str,
500        field_name: &str,
501    ) -> Self {
502        Self::executor_invariant(format!(
503            "map field entries are not in canonical deterministic order: {entity_path} field={field_name}",
504        ))
505    }
506
507    /// Construct a query-origin scalar page invariant for ordering before filtering.
508    pub(crate) fn scalar_page_ordering_after_filtering_required() -> Self {
509        Self::query_executor_invariant("ordering must run after filtering")
510    }
511
512    /// Construct a query-origin scalar page invariant for missing order at the cursor boundary.
513    pub(crate) fn scalar_page_cursor_boundary_order_required() -> Self {
514        Self::query_executor_invariant("cursor boundary requires ordering")
515    }
516
517    /// Construct a query-origin scalar page invariant for cursor-before-ordering drift.
518    pub(crate) fn scalar_page_cursor_boundary_after_ordering_required() -> Self {
519        Self::query_executor_invariant("cursor boundary must run after ordering")
520    }
521
522    /// Construct a query-origin scalar page invariant for pagination-before-ordering drift.
523    pub(crate) fn scalar_page_pagination_after_ordering_required() -> Self {
524        Self::query_executor_invariant("pagination must run after ordering")
525    }
526
527    /// Construct a query-origin scalar page invariant for delete-limit-before-ordering drift.
528    pub(crate) fn scalar_page_delete_limit_after_ordering_required() -> Self {
529        Self::query_executor_invariant("delete limit must run after ordering")
530    }
531
532    /// Construct a query-origin load-runtime invariant for scalar-mode payload mismatch.
533    pub(crate) fn load_runtime_scalar_payload_required() -> Self {
534        Self::query_executor_invariant("scalar load mode must carry scalar runtime payload")
535    }
536
537    /// Construct a query-origin load-runtime invariant for grouped-mode payload mismatch.
538    pub(crate) fn load_runtime_grouped_payload_required() -> Self {
539        Self::query_executor_invariant("grouped load mode must carry grouped runtime payload")
540    }
541
542    /// Construct a query-origin load-surface invariant for scalar-page payload mismatch.
543    pub(crate) fn load_runtime_scalar_surface_payload_required() -> Self {
544        Self::query_executor_invariant("scalar page load mode must carry scalar runtime payload")
545    }
546
547    /// Construct a query-origin load-surface invariant for grouped-page payload mismatch.
548    pub(crate) fn load_runtime_grouped_surface_payload_required() -> Self {
549        Self::query_executor_invariant("grouped page load mode must carry grouped runtime payload")
550    }
551
552    /// Construct a query-origin load-entrypoint invariant for non-load plans.
553    pub(crate) fn load_executor_load_plan_required() -> Self {
554        Self::query_executor_invariant("load executor requires load plans")
555    }
556
557    /// Construct an executor-origin delete-entrypoint unsupported grouped-mode error.
558    pub(crate) fn delete_executor_grouped_unsupported() -> Self {
559        Self::executor_unsupported("grouped query execution is not yet enabled in this release")
560    }
561
562    /// Construct a query-origin delete-entrypoint invariant for non-delete plans.
563    pub(crate) fn delete_executor_delete_plan_required() -> Self {
564        Self::query_executor_invariant("delete executor requires delete plans")
565    }
566
567    /// Construct a query-origin aggregate kernel invariant for fold-mode contract drift.
568    pub(crate) fn aggregate_fold_mode_terminal_contract_required() -> Self {
569        Self::query_executor_invariant(
570            "aggregate fold mode must match route fold-mode contract for aggregate terminal",
571        )
572    }
573
574    /// Construct a query-origin fast-stream invariant for route kind/request mismatch.
575    pub(crate) fn fast_stream_route_kind_request_match_required() -> Self {
576        Self::query_executor_invariant("fast-stream route kind/request mismatch")
577    }
578
579    /// Construct a query-origin scan invariant for missing index-prefix executable specs.
580    pub(crate) fn secondary_index_prefix_spec_required() -> Self {
581        Self::query_executor_invariant(
582            "index-prefix executable spec must be materialized for index-prefix plans",
583        )
584    }
585
586    /// Construct a query-origin scan invariant for missing index-range executable specs.
587    pub(crate) fn index_range_limit_spec_required() -> Self {
588        Self::query_executor_invariant(
589            "index-range executable spec must be materialized for index-range plans",
590        )
591    }
592
593    /// Construct an executor-origin mutation unsupported error for duplicate atomic save keys.
594    pub(crate) fn mutation_atomic_save_duplicate_key(
595        entity_path: &str,
596        key: impl fmt::Display,
597    ) -> Self {
598        Self::executor_unsupported(format!(
599            "atomic save batch rejected duplicate key: entity={entity_path} key={key}",
600        ))
601    }
602
603    /// Construct an executor-origin mutation invariant for index-store generation drift.
604    pub(crate) fn mutation_index_store_generation_changed(
605        expected_generation: u64,
606        observed_generation: u64,
607    ) -> Self {
608        Self::executor_invariant(format!(
609            "index store generation changed between preflight and apply: expected {expected_generation}, found {observed_generation}",
610        ))
611    }
612
613    /// Build the canonical executor-invariant message prefix.
614    #[must_use]
615    #[cold]
616    #[inline(never)]
617    pub(crate) fn executor_invariant_message(reason: impl Into<String>) -> String {
618        format!("executor invariant violated: {}", reason.into())
619    }
620
621    /// Construct a planner-origin invariant violation.
622    #[cold]
623    #[inline(never)]
624    pub(crate) fn planner_invariant(message: impl Into<String>) -> Self {
625        Self::new(
626            ErrorClass::InvariantViolation,
627            ErrorOrigin::Planner,
628            message.into(),
629        )
630    }
631
632    /// Build the canonical invalid-logical-plan message prefix.
633    #[must_use]
634    pub(crate) fn invalid_logical_plan_message(reason: impl Into<String>) -> String {
635        format!("invalid logical plan: {}", reason.into())
636    }
637
638    /// Construct a planner-origin invariant with the canonical invalid-plan prefix.
639    pub(crate) fn query_invalid_logical_plan(reason: impl Into<String>) -> Self {
640        Self::planner_invariant(Self::invalid_logical_plan_message(reason))
641    }
642
643    /// Construct a store-origin invariant violation.
644    pub(crate) fn store_invariant(message: impl Into<String>) -> Self {
645        Self::new(
646            ErrorClass::InvariantViolation,
647            ErrorOrigin::Store,
648            message.into(),
649        )
650    }
651
652    /// Construct the canonical duplicate runtime-hook entity-tag invariant.
653    pub(crate) fn duplicate_runtime_hooks_for_entity_tag(
654        entity_tag: crate::types::EntityTag,
655    ) -> Self {
656        Self::store_invariant(format!(
657            "duplicate runtime hooks for entity tag '{}'",
658            entity_tag.value()
659        ))
660    }
661
662    /// Construct the canonical duplicate runtime-hook entity-path invariant.
663    pub(crate) fn duplicate_runtime_hooks_for_entity_path(entity_path: &str) -> Self {
664        Self::store_invariant(format!(
665            "duplicate runtime hooks for entity path '{entity_path}'"
666        ))
667    }
668
669    /// Construct a store-origin internal error.
670    #[cold]
671    #[inline(never)]
672    pub(crate) fn store_internal(message: impl Into<String>) -> Self {
673        Self::new(ErrorClass::Internal, ErrorOrigin::Store, message.into())
674    }
675
676    /// Construct the canonical unconfigured commit-memory id internal error.
677    pub(crate) fn commit_memory_id_unconfigured() -> Self {
678        Self::store_internal(
679            "commit memory id is not configured; initialize recovery before commit store access",
680        )
681    }
682
683    /// Construct the canonical commit-memory id mismatch internal error.
684    pub(crate) fn commit_memory_id_mismatch(cached_id: u8, configured_id: u8) -> Self {
685        Self::store_internal(format!(
686            "commit memory id mismatch: cached={cached_id}, configured={configured_id}",
687        ))
688    }
689
690    /// Construct the canonical missing rollback-row invariant for delete execution.
691    pub(crate) fn delete_rollback_row_required() -> Self {
692        Self::store_internal("missing raw row for delete rollback")
693    }
694
695    /// Construct the canonical memory-registry initialization failure for commit memory.
696    pub(crate) fn commit_memory_registry_init_failed(err: impl fmt::Display) -> Self {
697        Self::store_internal(format!("memory registry init failed: {err}"))
698    }
699
700    /// Construct the canonical recovery-integrity totals corruption error.
701    pub(crate) fn recovery_integrity_validation_failed(
702        missing_index_entries: u64,
703        divergent_index_entries: u64,
704        orphan_index_references: u64,
705    ) -> Self {
706        Self::store_corruption(format!(
707            "recovery integrity validation failed: missing_index_entries={missing_index_entries} divergent_index_entries={divergent_index_entries} orphan_index_references={orphan_index_references}",
708        ))
709    }
710
711    /// Construct an index-origin internal error.
712    #[cold]
713    #[inline(never)]
714    pub(crate) fn index_internal(message: impl Into<String>) -> Self {
715        Self::new(ErrorClass::Internal, ErrorOrigin::Index, message.into())
716    }
717
718    /// Construct the canonical missing old entity-key internal error for structural index removal.
719    pub(crate) fn structural_index_removal_entity_key_required() -> Self {
720        Self::index_internal("missing old entity key for structural index removal")
721    }
722
723    /// Construct the canonical missing new entity-key internal error for structural index insertion.
724    pub(crate) fn structural_index_insertion_entity_key_required() -> Self {
725        Self::index_internal("missing new entity key for structural index insertion")
726    }
727
728    /// Construct the canonical missing old entity-key internal error for index commit-op removal.
729    pub(crate) fn index_commit_op_old_entity_key_required() -> Self {
730        Self::index_internal("missing old entity key for index removal")
731    }
732
733    /// Construct the canonical missing new entity-key internal error for index commit-op insertion.
734    pub(crate) fn index_commit_op_new_entity_key_required() -> Self {
735        Self::index_internal("missing new entity key for index insertion")
736    }
737
738    /// Construct a query-origin internal error.
739    #[cfg(test)]
740    pub(crate) fn query_internal(message: impl Into<String>) -> Self {
741        Self::new(ErrorClass::Internal, ErrorOrigin::Query, message.into())
742    }
743
744    /// Construct a query-origin unsupported error.
745    #[cold]
746    #[inline(never)]
747    pub(crate) fn query_unsupported(message: impl Into<String>) -> Self {
748        Self::new(ErrorClass::Unsupported, ErrorOrigin::Query, message.into())
749    }
750
751    /// Construct a query-origin numeric overflow error with structured detail.
752    #[cold]
753    #[inline(never)]
754    pub(crate) fn query_numeric_overflow() -> Self {
755        Self {
756            class: ErrorClass::Unsupported,
757            origin: ErrorOrigin::Query,
758            message: "numeric overflow".to_string(),
759            detail: Some(ErrorDetail::Query(QueryErrorDetail::NumericOverflow)),
760        }
761    }
762
763    /// Construct a query-origin non-representable numeric result error with
764    /// structured detail.
765    #[cold]
766    #[inline(never)]
767    pub(crate) fn query_numeric_not_representable() -> Self {
768        Self {
769            class: ErrorClass::Unsupported,
770            origin: ErrorOrigin::Query,
771            message: "numeric result is not representable".to_string(),
772            detail: Some(ErrorDetail::Query(
773                QueryErrorDetail::NumericNotRepresentable,
774            )),
775        }
776    }
777
778    /// Construct a serialize-origin internal error.
779    #[cold]
780    #[inline(never)]
781    pub(crate) fn serialize_internal(message: impl Into<String>) -> Self {
782        Self::new(ErrorClass::Internal, ErrorOrigin::Serialize, message.into())
783    }
784
785    /// Construct the canonical persisted-row encode internal error.
786    pub(crate) fn persisted_row_encode_failed(detail: impl fmt::Display) -> Self {
787        Self::serialize_internal(format!("row encode failed: {detail}"))
788    }
789
790    /// Construct the canonical persisted-row field encode internal error.
791    pub(crate) fn persisted_row_field_encode_failed(
792        field_name: &str,
793        detail: impl fmt::Display,
794    ) -> Self {
795        Self::serialize_internal(format!(
796            "row encode failed for field '{field_name}': {detail}",
797        ))
798    }
799
800    /// Construct the canonical bytes(field) value encode internal error.
801    pub(crate) fn bytes_field_value_encode_failed(detail: impl fmt::Display) -> Self {
802        Self::serialize_internal(format!("bytes(field) value encode failed: {detail}"))
803    }
804
805    /// Construct a store-origin corruption error.
806    #[cold]
807    #[inline(never)]
808    pub(crate) fn store_corruption(message: impl Into<String>) -> Self {
809        Self::new(ErrorClass::Corruption, ErrorOrigin::Store, message.into())
810    }
811
812    /// Construct the canonical multiple-commit-memory-ids corruption error.
813    pub(crate) fn multiple_commit_memory_ids_registered(ids: impl fmt::Debug) -> Self {
814        Self::store_corruption(format!(
815            "multiple commit marker memory ids registered: {ids:?}"
816        ))
817    }
818
819    /// Construct a store-origin commit-marker corruption error.
820    pub(crate) fn commit_corruption(detail: impl fmt::Display) -> Self {
821        Self::store_corruption(format!("commit marker corrupted: {detail}"))
822    }
823
824    /// Construct a store-origin commit-marker component corruption error.
825    pub(crate) fn commit_component_corruption(component: &str, detail: impl fmt::Display) -> Self {
826        Self::store_corruption(format!("commit marker {component} corrupted: {detail}"))
827    }
828
829    /// Construct the canonical commit-marker id generation internal error.
830    pub(crate) fn commit_id_generation_failed(detail: impl fmt::Display) -> Self {
831        Self::store_internal(format!("commit id generation failed: {detail}"))
832    }
833
834    /// Construct the canonical commit-marker payload u32-length-limit error.
835    pub(crate) fn commit_marker_payload_exceeds_u32_length_limit(label: &str, len: usize) -> Self {
836        Self::store_unsupported(format!("{label} exceeds u32 length limit: {len} bytes"))
837    }
838
839    /// Construct the canonical commit-marker component invalid-length corruption error.
840    pub(crate) fn commit_component_length_invalid(
841        component: &str,
842        len: usize,
843        expected: impl fmt::Display,
844    ) -> Self {
845        Self::commit_component_corruption(
846            component,
847            format!("invalid length {len}, expected {expected}"),
848        )
849    }
850
851    /// Construct the canonical commit-marker max-size corruption error.
852    pub(crate) fn commit_marker_exceeds_max_size(size: usize, max_size: u32) -> Self {
853        Self::commit_corruption(format!(
854            "commit marker exceeds max size: {size} bytes (limit {max_size})",
855        ))
856    }
857
858    /// Construct the canonical pre-persist commit-marker max-size unsupported error.
859    #[cfg(test)]
860    pub(crate) fn commit_marker_exceeds_max_size_before_persist(
861        size: usize,
862        max_size: u32,
863    ) -> Self {
864        Self::store_unsupported(format!(
865            "commit marker exceeds max size: {size} bytes (limit {max_size})",
866        ))
867    }
868
869    /// Construct the canonical commit-control slot max-size unsupported error.
870    pub(crate) fn commit_control_slot_exceeds_max_size(size: usize, max_size: u32) -> Self {
871        Self::store_unsupported(format!(
872            "commit control slot exceeds max size: {size} bytes (limit {max_size})",
873        ))
874    }
875
876    /// Construct the canonical commit-control marker-bytes length-limit error.
877    pub(crate) fn commit_control_slot_marker_bytes_exceed_u32_length_limit(size: usize) -> Self {
878        Self::store_unsupported(format!(
879            "commit marker bytes exceed u32 length limit: {size} bytes",
880        ))
881    }
882
883    /// Construct the canonical startup index-rebuild invalid-data-key corruption error.
884    pub(crate) fn startup_index_rebuild_invalid_data_key(
885        store_path: &str,
886        detail: impl fmt::Display,
887    ) -> Self {
888        Self::store_corruption(format!(
889            "startup index rebuild failed: invalid data key in store '{store_path}' ({detail})",
890        ))
891    }
892
893    /// Construct an index-origin corruption error.
894    #[cold]
895    #[inline(never)]
896    pub(crate) fn index_corruption(message: impl Into<String>) -> Self {
897        Self::new(ErrorClass::Corruption, ErrorOrigin::Index, message.into())
898    }
899
900    /// Construct the canonical unique-validation corruption wrapper.
901    pub(crate) fn index_unique_validation_corruption(
902        entity_path: &str,
903        fields: &str,
904        detail: impl fmt::Display,
905    ) -> Self {
906        Self::index_plan_index_corruption(format!(
907            "index corrupted: {entity_path} ({fields}) -> {detail}",
908        ))
909    }
910
911    /// Construct the canonical structural index-entry corruption wrapper.
912    pub(crate) fn structural_index_entry_corruption(
913        entity_path: &str,
914        fields: &str,
915        detail: impl fmt::Display,
916    ) -> Self {
917        Self::index_plan_index_corruption(format!(
918            "index corrupted: {entity_path} ({fields}) -> {detail}",
919        ))
920    }
921
922    /// Construct the canonical missing new entity-key invariant during unique validation.
923    pub(crate) fn index_unique_validation_entity_key_required() -> Self {
924        Self::index_invariant("missing entity key during unique validation")
925    }
926
927    /// Construct the canonical unique-validation structural row-decode corruption error.
928    pub(crate) fn index_unique_validation_row_deserialize_failed(
929        data_key: impl fmt::Display,
930        source: impl fmt::Display,
931    ) -> Self {
932        Self::index_plan_serialize_corruption(format!(
933            "failed to structurally deserialize row: {data_key} ({source})"
934        ))
935    }
936
937    /// Construct the canonical unique-validation primary-key slot decode corruption error.
938    pub(crate) fn index_unique_validation_primary_key_decode_failed(
939        data_key: impl fmt::Display,
940        source: impl fmt::Display,
941    ) -> Self {
942        Self::index_plan_serialize_corruption(format!(
943            "failed to decode structural primary-key slot: {data_key} ({source})"
944        ))
945    }
946
947    /// Construct the canonical unique-validation stored key rebuild corruption error.
948    pub(crate) fn index_unique_validation_key_rebuild_failed(
949        data_key: impl fmt::Display,
950        entity_path: &str,
951        source: impl fmt::Display,
952    ) -> Self {
953        Self::index_plan_serialize_corruption(format!(
954            "failed to structurally decode unique key row {data_key} for {entity_path}: {source}",
955        ))
956    }
957
958    /// Construct the canonical unique-validation missing-row corruption error.
959    pub(crate) fn index_unique_validation_row_required(data_key: impl fmt::Display) -> Self {
960        Self::index_plan_store_corruption(format!("missing row: {data_key}"))
961    }
962
963    /// Construct the canonical index-only predicate missing-component invariant.
964    pub(crate) fn index_only_predicate_component_required() -> Self {
965        Self::index_invariant("index-only predicate program referenced missing index component")
966    }
967
968    /// Construct the canonical index-scan continuation-envelope invariant.
969    pub(crate) fn index_scan_continuation_anchor_within_envelope_required() -> Self {
970        Self::index_invariant(
971            "index-range continuation anchor is outside the requested range envelope",
972        )
973    }
974
975    /// Construct the canonical index-scan continuation-advancement invariant.
976    pub(crate) fn index_scan_continuation_advancement_required() -> Self {
977        Self::index_invariant("index-range continuation scan did not advance beyond the anchor")
978    }
979
980    /// Construct the canonical index-scan key-decode corruption error.
981    pub(crate) fn index_scan_key_corrupted_during(
982        context: &'static str,
983        err: impl fmt::Display,
984    ) -> Self {
985        Self::index_corruption(format!("index key corrupted during {context}: {err}"))
986    }
987
988    /// Construct the canonical index-scan missing projection-component invariant.
989    pub(crate) fn index_projection_component_required(
990        index_name: &str,
991        component_index: usize,
992    ) -> Self {
993        Self::index_invariant(format!(
994            "index projection referenced missing component: index='{index_name}' component_index={component_index}",
995        ))
996    }
997
998    /// Construct the canonical unexpected unique index-entry cardinality corruption error.
999    pub(crate) fn unique_index_entry_single_key_required() -> Self {
1000        Self::index_corruption("unique index entry contains an unexpected number of keys")
1001    }
1002
1003    /// Construct the canonical scan-time index-entry decode corruption error.
1004    pub(crate) fn index_entry_decode_failed(err: impl fmt::Display) -> Self {
1005        Self::index_corruption(err.to_string())
1006    }
1007
1008    /// Construct a serialize-origin corruption error.
1009    pub(crate) fn serialize_corruption(message: impl Into<String>) -> Self {
1010        Self::new(
1011            ErrorClass::Corruption,
1012            ErrorOrigin::Serialize,
1013            message.into(),
1014        )
1015    }
1016
1017    /// Construct the canonical persisted-row decode corruption error.
1018    pub(crate) fn persisted_row_decode_failed(detail: impl fmt::Display) -> Self {
1019        Self::serialize_corruption(format!("row decode: {detail}"))
1020    }
1021
1022    /// Construct the canonical persisted-row field decode corruption error.
1023    pub(crate) fn persisted_row_field_decode_failed(
1024        field_name: &str,
1025        detail: impl fmt::Display,
1026    ) -> Self {
1027        Self::serialize_corruption(format!(
1028            "row decode failed for field '{field_name}': {detail}",
1029        ))
1030    }
1031
1032    /// Construct the canonical persisted-row field-kind decode corruption error.
1033    pub(crate) fn persisted_row_field_kind_decode_failed(
1034        field_name: &str,
1035        field_kind: impl fmt::Debug,
1036        detail: impl fmt::Display,
1037    ) -> Self {
1038        Self::persisted_row_field_decode_failed(
1039            field_name,
1040            format!("kind={field_kind:?}: {detail}"),
1041        )
1042    }
1043
1044    /// Construct the canonical persisted-row scalar-payload length corruption error.
1045    pub(crate) fn persisted_row_field_payload_exact_len_required(
1046        field_name: &str,
1047        payload_kind: &str,
1048        expected_len: usize,
1049    ) -> Self {
1050        let unit = if expected_len == 1 { "byte" } else { "bytes" };
1051
1052        Self::persisted_row_field_decode_failed(
1053            field_name,
1054            format!("{payload_kind} payload must be exactly {expected_len} {unit}"),
1055        )
1056    }
1057
1058    /// Construct the canonical persisted-row scalar-payload empty-body corruption error.
1059    pub(crate) fn persisted_row_field_payload_must_be_empty(
1060        field_name: &str,
1061        payload_kind: &str,
1062    ) -> Self {
1063        Self::persisted_row_field_decode_failed(
1064            field_name,
1065            format!("{payload_kind} payload must be empty"),
1066        )
1067    }
1068
1069    /// Construct the canonical persisted-row scalar-payload invalid-byte corruption error.
1070    pub(crate) fn persisted_row_field_payload_invalid_byte(
1071        field_name: &str,
1072        payload_kind: &str,
1073        value: u8,
1074    ) -> Self {
1075        Self::persisted_row_field_decode_failed(
1076            field_name,
1077            format!("invalid {payload_kind} payload byte {value}"),
1078        )
1079    }
1080
1081    /// Construct the canonical persisted-row scalar-payload non-finite corruption error.
1082    pub(crate) fn persisted_row_field_payload_non_finite(
1083        field_name: &str,
1084        payload_kind: &str,
1085    ) -> Self {
1086        Self::persisted_row_field_decode_failed(
1087            field_name,
1088            format!("{payload_kind} payload is non-finite"),
1089        )
1090    }
1091
1092    /// Construct the canonical persisted-row scalar-payload out-of-range corruption error.
1093    pub(crate) fn persisted_row_field_payload_out_of_range(
1094        field_name: &str,
1095        payload_kind: &str,
1096    ) -> Self {
1097        Self::persisted_row_field_decode_failed(
1098            field_name,
1099            format!("{payload_kind} payload out of range for target type"),
1100        )
1101    }
1102
1103    /// Construct the canonical persisted-row invalid text payload corruption error.
1104    pub(crate) fn persisted_row_field_text_payload_invalid_utf8(
1105        field_name: &str,
1106        detail: impl fmt::Display,
1107    ) -> Self {
1108        Self::persisted_row_field_decode_failed(
1109            field_name,
1110            format!("invalid UTF-8 text payload ({detail})"),
1111        )
1112    }
1113
1114    /// Construct the canonical persisted-row structural slot-lookup invariant.
1115    pub(crate) fn persisted_row_slot_lookup_out_of_bounds(model_path: &str, slot: usize) -> Self {
1116        Self::index_invariant(format!(
1117            "slot lookup outside model bounds during structural row access: model='{model_path}' slot={slot}",
1118        ))
1119    }
1120
1121    /// Construct the canonical persisted-row structural slot-cache invariant.
1122    pub(crate) fn persisted_row_slot_cache_lookup_out_of_bounds(
1123        model_path: &str,
1124        slot: usize,
1125    ) -> Self {
1126        Self::index_invariant(format!(
1127            "slot cache lookup outside model bounds during structural row access: model='{model_path}' slot={slot}",
1128        ))
1129    }
1130
1131    /// Construct the canonical persisted-row primary-key decode corruption error.
1132    pub(crate) fn persisted_row_primary_key_not_storage_encodable(
1133        data_key: impl fmt::Debug,
1134        detail: impl fmt::Display,
1135    ) -> Self {
1136        Self::persisted_row_decode_failed(format!(
1137            "primary-key value is not storage-key encodable: {data_key:?} ({detail})",
1138        ))
1139    }
1140
1141    /// Construct the canonical persisted-row missing primary-key slot corruption error.
1142    pub(crate) fn persisted_row_primary_key_slot_missing(data_key: impl fmt::Debug) -> Self {
1143        Self::persisted_row_decode_failed(format!(
1144            "missing primary-key slot while validating {data_key:?}",
1145        ))
1146    }
1147
1148    /// Construct the canonical persisted-row key mismatch corruption error.
1149    pub(crate) fn persisted_row_key_mismatch(
1150        expected_key: impl fmt::Debug,
1151        found_key: impl fmt::Debug,
1152    ) -> Self {
1153        Self::store_corruption(format!(
1154            "row key mismatch: expected {expected_key:?}, found {found_key:?}",
1155        ))
1156    }
1157
1158    /// Construct the canonical persisted-row missing declared-field corruption error.
1159    pub(crate) fn persisted_row_declared_field_missing(field_name: &str) -> Self {
1160        Self::persisted_row_decode_failed(format!("missing declared field `{field_name}`"))
1161    }
1162
1163    /// Construct the canonical data-key entity mismatch corruption error.
1164    pub(crate) fn data_key_entity_mismatch(
1165        expected: impl fmt::Display,
1166        found: impl fmt::Display,
1167    ) -> Self {
1168        Self::store_corruption(format!(
1169            "data key entity mismatch: expected {expected}, found {found}",
1170        ))
1171    }
1172
1173    /// Construct the canonical reverse-index ordinal overflow internal error.
1174    pub(crate) fn reverse_index_ordinal_overflow(
1175        source_path: &str,
1176        field_name: &str,
1177        target_path: &str,
1178        detail: impl fmt::Display,
1179    ) -> Self {
1180        Self::index_internal(format!(
1181            "reverse index ordinal overflow: source={source_path} field={field_name} target={target_path} ({detail})",
1182        ))
1183    }
1184
1185    /// Construct the canonical reverse-index entry corruption error.
1186    pub(crate) fn reverse_index_entry_corrupted(
1187        source_path: &str,
1188        field_name: &str,
1189        target_path: &str,
1190        index_key: impl fmt::Debug,
1191        detail: impl fmt::Display,
1192    ) -> Self {
1193        Self::index_corruption(format!(
1194            "reverse index entry corrupted: source={source_path} field={field_name} target={target_path} key={index_key:?} ({detail})",
1195        ))
1196    }
1197
1198    /// Construct the canonical reverse-index entry encode unsupported error.
1199    pub(crate) fn reverse_index_entry_encode_failed(
1200        source_path: &str,
1201        field_name: &str,
1202        target_path: &str,
1203        detail: impl fmt::Display,
1204    ) -> Self {
1205        Self::index_unsupported(format!(
1206            "reverse index entry encoding failed: source={source_path} field={field_name} target={target_path} ({detail})",
1207        ))
1208    }
1209
1210    /// Construct the canonical relation-target store missing internal error.
1211    pub(crate) fn relation_target_store_missing(
1212        source_path: &str,
1213        field_name: &str,
1214        target_path: &str,
1215        store_path: &str,
1216        detail: impl fmt::Display,
1217    ) -> Self {
1218        Self::executor_internal(format!(
1219            "relation target store missing: source={source_path} field={field_name} target={target_path} store={store_path} ({detail})",
1220        ))
1221    }
1222
1223    /// Construct the canonical relation-target key decode corruption error.
1224    pub(crate) fn relation_target_key_decode_failed(
1225        context_label: &str,
1226        source_path: &str,
1227        field_name: &str,
1228        target_path: &str,
1229        detail: impl fmt::Display,
1230    ) -> Self {
1231        Self::identity_corruption(format!(
1232            "{context_label}: source={source_path} field={field_name} target={target_path} ({detail})",
1233        ))
1234    }
1235
1236    /// Construct the canonical relation-target entity mismatch corruption error.
1237    pub(crate) fn relation_target_entity_mismatch(
1238        context_label: &str,
1239        source_path: &str,
1240        field_name: &str,
1241        target_path: &str,
1242        target_entity_name: &str,
1243        expected_tag: impl fmt::Display,
1244        actual_tag: impl fmt::Display,
1245    ) -> Self {
1246        Self::store_corruption(format!(
1247            "{context_label}: source={source_path} field={field_name} target={target_path} expected={target_entity_name} (tag={expected_tag}) actual_tag={actual_tag}",
1248        ))
1249    }
1250
1251    /// Construct the canonical relation-source row decode corruption error.
1252    pub(crate) fn relation_source_row_decode_failed(
1253        source_path: &str,
1254        field_name: &str,
1255        target_path: &str,
1256        detail: impl fmt::Display,
1257    ) -> Self {
1258        Self::serialize_corruption(format!(
1259            "relation source row decode: source={source_path} field={field_name} target={target_path} ({detail})",
1260        ))
1261    }
1262
1263    /// Construct the canonical relation-source unsupported scalar relation-key corruption error.
1264    pub(crate) fn relation_source_row_unsupported_scalar_relation_key(
1265        source_path: &str,
1266        field_name: &str,
1267        target_path: &str,
1268    ) -> Self {
1269        Self::serialize_corruption(format!(
1270            "relation source row decode: unsupported scalar relation key: source={source_path} field={field_name} target={target_path}",
1271        ))
1272    }
1273
1274    /// Construct the canonical invalid strong-relation field-kind corruption error.
1275    pub(crate) fn relation_source_row_invalid_field_kind(field_kind: impl fmt::Debug) -> Self {
1276        Self::serialize_corruption(format!(
1277            "invalid strong relation field kind during structural decode: {field_kind:?}"
1278        ))
1279    }
1280
1281    /// Construct the canonical unsupported strong-relation key-kind corruption error.
1282    pub(crate) fn relation_source_row_unsupported_key_kind(field_kind: impl fmt::Debug) -> Self {
1283        Self::serialize_corruption(format!(
1284            "unsupported strong relation key kind during structural decode: {field_kind:?}"
1285        ))
1286    }
1287
1288    /// Construct the canonical reverse-index relation-target decode invariant failure.
1289    pub(crate) fn reverse_index_relation_target_decode_invariant_violated(
1290        source_path: &str,
1291        field_name: &str,
1292        target_path: &str,
1293    ) -> Self {
1294        Self::executor_internal(format!(
1295            "relation target decode invariant violated while preparing reverse index: source={source_path} field={field_name} target={target_path}",
1296        ))
1297    }
1298
1299    /// Construct the canonical covering-component empty-payload corruption error.
1300    pub(crate) fn bytes_covering_component_payload_empty() -> Self {
1301        Self::index_corruption("index component payload is empty during covering projection decode")
1302    }
1303
1304    /// Construct the canonical covering-component truncated bool corruption error.
1305    pub(crate) fn bytes_covering_bool_payload_truncated() -> Self {
1306        Self::index_corruption("bool covering component payload is truncated")
1307    }
1308
1309    /// Construct the canonical covering-component invalid-length corruption error.
1310    pub(crate) fn bytes_covering_component_payload_invalid_length(payload_kind: &str) -> Self {
1311        Self::index_corruption(format!(
1312            "{payload_kind} covering component payload has invalid length"
1313        ))
1314    }
1315
1316    /// Construct the canonical covering-component invalid-bool corruption error.
1317    pub(crate) fn bytes_covering_bool_payload_invalid_value() -> Self {
1318        Self::index_corruption("bool covering component payload has invalid value")
1319    }
1320
1321    /// Construct the canonical covering-component invalid text terminator corruption error.
1322    pub(crate) fn bytes_covering_text_payload_invalid_terminator() -> Self {
1323        Self::index_corruption("text covering component payload has invalid terminator")
1324    }
1325
1326    /// Construct the canonical covering-component trailing-text corruption error.
1327    pub(crate) fn bytes_covering_text_payload_trailing_bytes() -> Self {
1328        Self::index_corruption("text covering component payload contains trailing bytes")
1329    }
1330
1331    /// Construct the canonical covering-component invalid-UTF-8 text corruption error.
1332    pub(crate) fn bytes_covering_text_payload_invalid_utf8() -> Self {
1333        Self::index_corruption("text covering component payload is not valid UTF-8")
1334    }
1335
1336    /// Construct the canonical covering-component invalid text escape corruption error.
1337    pub(crate) fn bytes_covering_text_payload_invalid_escape_byte() -> Self {
1338        Self::index_corruption("text covering component payload has invalid escape byte")
1339    }
1340
1341    /// Construct the canonical covering-component missing text terminator corruption error.
1342    pub(crate) fn bytes_covering_text_payload_missing_terminator() -> Self {
1343        Self::index_corruption("text covering component payload is missing terminator")
1344    }
1345
1346    /// Construct the canonical missing persisted-field decode error.
1347    #[must_use]
1348    pub fn missing_persisted_slot(field_name: &'static str) -> Self {
1349        Self::serialize_corruption(format!("row decode: missing required field '{field_name}'"))
1350    }
1351
1352    /// Construct an identity-origin corruption error.
1353    pub(crate) fn identity_corruption(message: impl Into<String>) -> Self {
1354        Self::new(
1355            ErrorClass::Corruption,
1356            ErrorOrigin::Identity,
1357            message.into(),
1358        )
1359    }
1360
1361    /// Construct a store-origin unsupported error.
1362    #[cold]
1363    #[inline(never)]
1364    pub(crate) fn store_unsupported(message: impl Into<String>) -> Self {
1365        Self::new(ErrorClass::Unsupported, ErrorOrigin::Store, message.into())
1366    }
1367
1368    /// Construct the canonical unsupported persisted entity-tag store error.
1369    pub(crate) fn unsupported_entity_tag_in_data_store(
1370        entity_tag: crate::types::EntityTag,
1371    ) -> Self {
1372        Self::store_unsupported(format!(
1373            "unsupported entity tag in data store: '{}'",
1374            entity_tag.value()
1375        ))
1376    }
1377
1378    /// Construct the canonical configured-vs-registered commit-memory id mismatch error.
1379    pub(crate) fn configured_commit_memory_id_mismatch(
1380        configured_id: u8,
1381        registered_id: u8,
1382    ) -> Self {
1383        Self::store_unsupported(format!(
1384            "configured commit memory id {configured_id} does not match existing commit marker id {registered_id}",
1385        ))
1386    }
1387
1388    /// Construct the canonical occupied commit-memory id unsupported error.
1389    pub(crate) fn commit_memory_id_already_registered(memory_id: u8, label: &str) -> Self {
1390        Self::store_unsupported(format!(
1391            "configured commit memory id {memory_id} is already registered as '{label}'",
1392        ))
1393    }
1394
1395    /// Construct the canonical out-of-range commit-memory id unsupported error.
1396    pub(crate) fn commit_memory_id_outside_reserved_ranges(memory_id: u8) -> Self {
1397        Self::store_unsupported(format!(
1398            "configured commit memory id {memory_id} is outside reserved ranges",
1399        ))
1400    }
1401
1402    /// Construct the canonical commit-memory id registration failure.
1403    pub(crate) fn commit_memory_id_registration_failed(err: impl fmt::Display) -> Self {
1404        Self::store_internal(format!("commit memory id registration failed: {err}"))
1405    }
1406
1407    /// Construct an index-origin unsupported error.
1408    pub(crate) fn index_unsupported(message: impl Into<String>) -> Self {
1409        Self::new(ErrorClass::Unsupported, ErrorOrigin::Index, message.into())
1410    }
1411
1412    /// Construct the canonical index-key component size-limit unsupported error.
1413    pub(crate) fn index_component_exceeds_max_size(
1414        key_item: impl fmt::Display,
1415        len: usize,
1416        max_component_size: usize,
1417    ) -> Self {
1418        Self::index_unsupported(format!(
1419            "index component exceeds max size: key item '{key_item}' -> {len} bytes (limit {max_component_size})",
1420        ))
1421    }
1422
1423    /// Construct the canonical index-entry max-keys unsupported error during commit encoding.
1424    pub(crate) fn index_entry_exceeds_max_keys(
1425        entity_path: &str,
1426        fields: &str,
1427        keys: usize,
1428    ) -> Self {
1429        Self::index_unsupported(format!(
1430            "index entry exceeds max keys: {entity_path} ({fields}) -> {keys} keys",
1431        ))
1432    }
1433
1434    /// Construct the canonical duplicate-key invariant during commit entry encoding.
1435    #[cfg(test)]
1436    pub(crate) fn index_entry_duplicate_keys_unexpected(entity_path: &str, fields: &str) -> Self {
1437        Self::index_invariant(format!(
1438            "index entry unexpectedly contains duplicate keys: {entity_path} ({fields})",
1439        ))
1440    }
1441
1442    /// Construct the canonical index-entry key-encoding unsupported error during commit encoding.
1443    pub(crate) fn index_entry_key_encoding_failed(
1444        entity_path: &str,
1445        fields: &str,
1446        err: impl fmt::Display,
1447    ) -> Self {
1448        Self::index_unsupported(format!(
1449            "index entry key encoding failed: {entity_path} ({fields}) -> {err}",
1450        ))
1451    }
1452
1453    /// Construct a serialize-origin unsupported error.
1454    pub(crate) fn serialize_unsupported(message: impl Into<String>) -> Self {
1455        Self::new(
1456            ErrorClass::Unsupported,
1457            ErrorOrigin::Serialize,
1458            message.into(),
1459        )
1460    }
1461
1462    /// Construct a cursor-origin unsupported error.
1463    pub(crate) fn cursor_unsupported(message: impl Into<String>) -> Self {
1464        Self::new(ErrorClass::Unsupported, ErrorOrigin::Cursor, message.into())
1465    }
1466
1467    /// Construct a serialize-origin incompatible persisted-format error.
1468    pub(crate) fn serialize_incompatible_persisted_format(message: impl Into<String>) -> Self {
1469        Self::new(
1470            ErrorClass::IncompatiblePersistedFormat,
1471            ErrorOrigin::Serialize,
1472            message.into(),
1473        )
1474    }
1475
1476    /// Construct a query-origin unsupported error preserving one SQL parser
1477    /// unsupported-feature label in structured error detail.
1478    #[cfg(feature = "sql")]
1479    pub(crate) fn query_unsupported_sql_feature(feature: &'static str) -> Self {
1480        let message = format!(
1481            "SQL query is not executable in this release: unsupported SQL feature: {feature}"
1482        );
1483
1484        Self {
1485            class: ErrorClass::Unsupported,
1486            origin: ErrorOrigin::Query,
1487            message,
1488            detail: Some(ErrorDetail::Query(
1489                QueryErrorDetail::UnsupportedSqlFeature { feature },
1490            )),
1491        }
1492    }
1493
1494    pub fn store_not_found(key: impl Into<String>) -> Self {
1495        let key = key.into();
1496
1497        Self {
1498            class: ErrorClass::NotFound,
1499            origin: ErrorOrigin::Store,
1500            message: format!("data key not found: {key}"),
1501            detail: Some(ErrorDetail::Store(StoreError::NotFound { key })),
1502        }
1503    }
1504
1505    /// Construct a standardized unsupported-entity-path error.
1506    pub fn unsupported_entity_path(path: impl Into<String>) -> Self {
1507        let path = path.into();
1508
1509        Self::new(
1510            ErrorClass::Unsupported,
1511            ErrorOrigin::Store,
1512            format!("unsupported entity path: '{path}'"),
1513        )
1514    }
1515
1516    #[must_use]
1517    pub const fn is_not_found(&self) -> bool {
1518        matches!(
1519            self.detail,
1520            Some(ErrorDetail::Store(StoreError::NotFound { .. }))
1521        )
1522    }
1523
1524    #[must_use]
1525    pub fn display_with_class(&self) -> String {
1526        format!("{}:{}: {}", self.origin, self.class, self.message)
1527    }
1528
1529    /// Construct an index-plan corruption error with a canonical prefix.
1530    #[cold]
1531    #[inline(never)]
1532    pub(crate) fn index_plan_corruption(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1533        let message = message.into();
1534        Self::new(
1535            ErrorClass::Corruption,
1536            origin,
1537            format!("corruption detected ({origin}): {message}"),
1538        )
1539    }
1540
1541    /// Construct an index-plan corruption error for index-origin failures.
1542    #[cold]
1543    #[inline(never)]
1544    pub(crate) fn index_plan_index_corruption(message: impl Into<String>) -> Self {
1545        Self::index_plan_corruption(ErrorOrigin::Index, message)
1546    }
1547
1548    /// Construct an index-plan corruption error for store-origin failures.
1549    #[cold]
1550    #[inline(never)]
1551    pub(crate) fn index_plan_store_corruption(message: impl Into<String>) -> Self {
1552        Self::index_plan_corruption(ErrorOrigin::Store, message)
1553    }
1554
1555    /// Construct an index-plan corruption error for serialize-origin failures.
1556    #[cold]
1557    #[inline(never)]
1558    pub(crate) fn index_plan_serialize_corruption(message: impl Into<String>) -> Self {
1559        Self::index_plan_corruption(ErrorOrigin::Serialize, message)
1560    }
1561
1562    /// Construct an index-plan invariant violation error with a canonical prefix.
1563    #[cfg(test)]
1564    pub(crate) fn index_plan_invariant(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1565        let message = message.into();
1566        Self::new(
1567            ErrorClass::InvariantViolation,
1568            origin,
1569            format!("invariant violation detected ({origin}): {message}"),
1570        )
1571    }
1572
1573    /// Construct an index-plan invariant violation error for store-origin failures.
1574    #[cfg(test)]
1575    pub(crate) fn index_plan_store_invariant(message: impl Into<String>) -> Self {
1576        Self::index_plan_invariant(ErrorOrigin::Store, message)
1577    }
1578
1579    /// Construct an index uniqueness violation conflict error.
1580    pub(crate) fn index_violation(path: &str, index_fields: &[&str]) -> Self {
1581        Self::new(
1582            ErrorClass::Conflict,
1583            ErrorOrigin::Index,
1584            format!(
1585                "index constraint violation: {path} ({})",
1586                index_fields.join(", ")
1587            ),
1588        )
1589    }
1590}
1591
1592///
1593/// ErrorDetail
1594///
1595/// Structured, origin-specific error detail carried by [`InternalError`].
1596/// This enum is intentionally extensible.
1597///
1598
1599#[derive(Debug, ThisError)]
1600pub enum ErrorDetail {
1601    #[error("{0}")]
1602    Store(StoreError),
1603    #[error("{0}")]
1604    Query(QueryErrorDetail),
1605    // Future-proofing:
1606    // #[error("{0}")]
1607    // Index(IndexError),
1608    //
1609    // #[error("{0}")]
1610    // Executor(ExecutorErrorDetail),
1611}
1612
1613///
1614/// StoreError
1615///
1616/// Store-specific structured error detail.
1617/// Never returned directly; always wrapped in [`ErrorDetail::Store`].
1618///
1619
1620#[derive(Debug, ThisError)]
1621pub enum StoreError {
1622    #[error("key not found: {key}")]
1623    NotFound { key: String },
1624
1625    #[error("store corruption: {message}")]
1626    Corrupt { message: String },
1627
1628    #[error("store invariant violation: {message}")]
1629    InvariantViolation { message: String },
1630}
1631
1632///
1633/// QueryErrorDetail
1634///
1635/// Query-origin structured error detail payload.
1636///
1637
1638#[derive(Debug, ThisError)]
1639pub enum QueryErrorDetail {
1640    #[error("numeric overflow")]
1641    NumericOverflow,
1642
1643    #[error("numeric result is not representable")]
1644    NumericNotRepresentable,
1645
1646    #[error("unsupported SQL feature: {feature}")]
1647    UnsupportedSqlFeature { feature: &'static str },
1648}
1649
1650///
1651/// ErrorClass
1652/// Internal error taxonomy for runtime classification.
1653/// Not a stable API; may change without notice.
1654///
1655
1656#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1657pub enum ErrorClass {
1658    Corruption,
1659    IncompatiblePersistedFormat,
1660    NotFound,
1661    Internal,
1662    Conflict,
1663    Unsupported,
1664    InvariantViolation,
1665}
1666
1667impl fmt::Display for ErrorClass {
1668    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1669        let label = match self {
1670            Self::Corruption => "corruption",
1671            Self::IncompatiblePersistedFormat => "incompatible_persisted_format",
1672            Self::NotFound => "not_found",
1673            Self::Internal => "internal",
1674            Self::Conflict => "conflict",
1675            Self::Unsupported => "unsupported",
1676            Self::InvariantViolation => "invariant_violation",
1677        };
1678        write!(f, "{label}")
1679    }
1680}
1681
1682///
1683/// ErrorOrigin
1684/// Internal origin taxonomy for runtime classification.
1685/// Not a stable API; may change without notice.
1686///
1687
1688#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1689pub enum ErrorOrigin {
1690    Serialize,
1691    Store,
1692    Index,
1693    Identity,
1694    Query,
1695    Planner,
1696    Cursor,
1697    Recovery,
1698    Response,
1699    Executor,
1700    Interface,
1701}
1702
1703impl fmt::Display for ErrorOrigin {
1704    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1705        let label = match self {
1706            Self::Serialize => "serialize",
1707            Self::Store => "store",
1708            Self::Index => "index",
1709            Self::Identity => "identity",
1710            Self::Query => "query",
1711            Self::Planner => "planner",
1712            Self::Cursor => "cursor",
1713            Self::Recovery => "recovery",
1714            Self::Response => "response",
1715            Self::Executor => "executor",
1716            Self::Interface => "interface",
1717        };
1718        write!(f, "{label}")
1719    }
1720}