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 query-origin invariant violation.
644    #[cold]
645    #[inline(never)]
646    pub(crate) fn query_invariant(message: impl Into<String>) -> Self {
647        Self::new(
648            ErrorClass::InvariantViolation,
649            ErrorOrigin::Query,
650            message.into(),
651        )
652    }
653
654    /// Construct a store-origin invariant violation.
655    pub(crate) fn store_invariant(message: impl Into<String>) -> Self {
656        Self::new(
657            ErrorClass::InvariantViolation,
658            ErrorOrigin::Store,
659            message.into(),
660        )
661    }
662
663    /// Construct the canonical duplicate runtime-hook entity-tag invariant.
664    pub(crate) fn duplicate_runtime_hooks_for_entity_tag(
665        entity_tag: crate::types::EntityTag,
666    ) -> Self {
667        Self::store_invariant(format!(
668            "duplicate runtime hooks for entity tag '{}'",
669            entity_tag.value()
670        ))
671    }
672
673    /// Construct the canonical duplicate runtime-hook entity-path invariant.
674    pub(crate) fn duplicate_runtime_hooks_for_entity_path(entity_path: &str) -> Self {
675        Self::store_invariant(format!(
676            "duplicate runtime hooks for entity path '{entity_path}'"
677        ))
678    }
679
680    /// Construct a store-origin internal error.
681    #[cold]
682    #[inline(never)]
683    pub(crate) fn store_internal(message: impl Into<String>) -> Self {
684        Self::new(ErrorClass::Internal, ErrorOrigin::Store, message.into())
685    }
686
687    /// Construct the canonical unconfigured commit-memory id internal error.
688    pub(crate) fn commit_memory_id_unconfigured() -> Self {
689        Self::store_internal(
690            "commit memory id is not configured; initialize recovery before commit store access",
691        )
692    }
693
694    /// Construct the canonical commit-memory id mismatch internal error.
695    pub(crate) fn commit_memory_id_mismatch(cached_id: u8, configured_id: u8) -> Self {
696        Self::store_internal(format!(
697            "commit memory id mismatch: cached={cached_id}, configured={configured_id}",
698        ))
699    }
700
701    /// Construct the canonical missing rollback-row invariant for delete execution.
702    pub(crate) fn delete_rollback_row_required() -> Self {
703        Self::store_internal("missing raw row for delete rollback")
704    }
705
706    /// Construct the canonical memory-registry initialization failure for commit memory.
707    pub(crate) fn commit_memory_registry_init_failed(err: impl fmt::Display) -> Self {
708        Self::store_internal(format!("memory registry init failed: {err}"))
709    }
710
711    /// Construct the canonical recovery-integrity totals corruption error.
712    pub(crate) fn recovery_integrity_validation_failed(
713        missing_index_entries: u64,
714        divergent_index_entries: u64,
715        orphan_index_references: u64,
716    ) -> Self {
717        Self::store_corruption(format!(
718            "recovery integrity validation failed: missing_index_entries={missing_index_entries} divergent_index_entries={divergent_index_entries} orphan_index_references={orphan_index_references}",
719        ))
720    }
721
722    /// Construct an index-origin internal error.
723    #[cold]
724    #[inline(never)]
725    pub(crate) fn index_internal(message: impl Into<String>) -> Self {
726        Self::new(ErrorClass::Internal, ErrorOrigin::Index, message.into())
727    }
728
729    /// Construct the canonical missing old entity-key internal error for structural index removal.
730    pub(crate) fn structural_index_removal_entity_key_required() -> Self {
731        Self::index_internal("missing old entity key for structural index removal")
732    }
733
734    /// Construct the canonical missing new entity-key internal error for structural index insertion.
735    pub(crate) fn structural_index_insertion_entity_key_required() -> Self {
736        Self::index_internal("missing new entity key for structural index insertion")
737    }
738
739    /// Construct the canonical missing old entity-key internal error for index commit-op removal.
740    pub(crate) fn index_commit_op_old_entity_key_required() -> Self {
741        Self::index_internal("missing old entity key for index removal")
742    }
743
744    /// Construct the canonical missing new entity-key internal error for index commit-op insertion.
745    pub(crate) fn index_commit_op_new_entity_key_required() -> Self {
746        Self::index_internal("missing new entity key for index insertion")
747    }
748
749    /// Construct a query-origin internal error.
750    #[cfg(test)]
751    pub(crate) fn query_internal(message: impl Into<String>) -> Self {
752        Self::new(ErrorClass::Internal, ErrorOrigin::Query, message.into())
753    }
754
755    /// Construct a query-origin unsupported error.
756    #[cold]
757    #[inline(never)]
758    pub(crate) fn query_unsupported(message: impl Into<String>) -> Self {
759        Self::new(ErrorClass::Unsupported, ErrorOrigin::Query, message.into())
760    }
761
762    /// Construct a query-origin numeric overflow error with structured detail.
763    #[cold]
764    #[inline(never)]
765    pub(crate) fn query_numeric_overflow() -> Self {
766        Self {
767            class: ErrorClass::Unsupported,
768            origin: ErrorOrigin::Query,
769            message: "numeric overflow".to_string(),
770            detail: Some(ErrorDetail::Query(QueryErrorDetail::NumericOverflow)),
771        }
772    }
773
774    /// Construct a query-origin non-representable numeric result error with
775    /// structured detail.
776    #[cold]
777    #[inline(never)]
778    pub(crate) fn query_numeric_not_representable() -> Self {
779        Self {
780            class: ErrorClass::Unsupported,
781            origin: ErrorOrigin::Query,
782            message: "numeric result is not representable".to_string(),
783            detail: Some(ErrorDetail::Query(
784                QueryErrorDetail::NumericNotRepresentable,
785            )),
786        }
787    }
788
789    /// Construct a serialize-origin internal error.
790    #[cold]
791    #[inline(never)]
792    pub(crate) fn serialize_internal(message: impl Into<String>) -> Self {
793        Self::new(ErrorClass::Internal, ErrorOrigin::Serialize, message.into())
794    }
795
796    /// Construct the canonical persisted-row encode internal error.
797    pub(crate) fn persisted_row_encode_failed(detail: impl fmt::Display) -> Self {
798        Self::serialize_internal(format!("row encode failed: {detail}"))
799    }
800
801    /// Construct the canonical persisted-row field encode internal error.
802    pub(crate) fn persisted_row_field_encode_failed(
803        field_name: &str,
804        detail: impl fmt::Display,
805    ) -> Self {
806        Self::serialize_internal(format!(
807            "row encode failed for field '{field_name}': {detail}",
808        ))
809    }
810
811    /// Construct the canonical bytes(field) value encode internal error.
812    pub(crate) fn bytes_field_value_encode_failed(detail: impl fmt::Display) -> Self {
813        Self::serialize_internal(format!("bytes(field) value encode failed: {detail}"))
814    }
815
816    /// Construct a store-origin corruption error.
817    #[cold]
818    #[inline(never)]
819    pub(crate) fn store_corruption(message: impl Into<String>) -> Self {
820        Self::new(ErrorClass::Corruption, ErrorOrigin::Store, message.into())
821    }
822
823    /// Construct the canonical multiple-commit-memory-ids corruption error.
824    pub(crate) fn multiple_commit_memory_ids_registered(ids: impl fmt::Debug) -> Self {
825        Self::store_corruption(format!(
826            "multiple commit marker memory ids registered: {ids:?}"
827        ))
828    }
829
830    /// Construct a store-origin commit-marker corruption error.
831    pub(crate) fn commit_corruption(detail: impl fmt::Display) -> Self {
832        Self::store_corruption(format!("commit marker corrupted: {detail}"))
833    }
834
835    /// Construct a store-origin commit-marker component corruption error.
836    pub(crate) fn commit_component_corruption(component: &str, detail: impl fmt::Display) -> Self {
837        Self::store_corruption(format!("commit marker {component} corrupted: {detail}"))
838    }
839
840    /// Construct the canonical commit-marker id generation internal error.
841    pub(crate) fn commit_id_generation_failed(detail: impl fmt::Display) -> Self {
842        Self::store_internal(format!("commit id generation failed: {detail}"))
843    }
844
845    /// Construct the canonical commit-marker payload u32-length-limit error.
846    pub(crate) fn commit_marker_payload_exceeds_u32_length_limit(label: &str, len: usize) -> Self {
847        Self::store_unsupported(format!("{label} exceeds u32 length limit: {len} bytes"))
848    }
849
850    /// Construct the canonical commit-marker component invalid-length corruption error.
851    pub(crate) fn commit_component_length_invalid(
852        component: &str,
853        len: usize,
854        expected: impl fmt::Display,
855    ) -> Self {
856        Self::commit_component_corruption(
857            component,
858            format!("invalid length {len}, expected {expected}"),
859        )
860    }
861
862    /// Construct the canonical commit-marker max-size corruption error.
863    pub(crate) fn commit_marker_exceeds_max_size(size: usize, max_size: u32) -> Self {
864        Self::commit_corruption(format!(
865            "commit marker exceeds max size: {size} bytes (limit {max_size})",
866        ))
867    }
868
869    /// Construct the canonical pre-persist commit-marker max-size unsupported error.
870    #[cfg(test)]
871    pub(crate) fn commit_marker_exceeds_max_size_before_persist(
872        size: usize,
873        max_size: u32,
874    ) -> Self {
875        Self::store_unsupported(format!(
876            "commit marker exceeds max size: {size} bytes (limit {max_size})",
877        ))
878    }
879
880    /// Construct the canonical commit-control slot max-size unsupported error.
881    pub(crate) fn commit_control_slot_exceeds_max_size(size: usize, max_size: u32) -> Self {
882        Self::store_unsupported(format!(
883            "commit control slot exceeds max size: {size} bytes (limit {max_size})",
884        ))
885    }
886
887    /// Construct the canonical commit-control marker-bytes length-limit error.
888    pub(crate) fn commit_control_slot_marker_bytes_exceed_u32_length_limit(size: usize) -> Self {
889        Self::store_unsupported(format!(
890            "commit marker bytes exceed u32 length limit: {size} bytes",
891        ))
892    }
893
894    /// Construct the canonical startup index-rebuild invalid-data-key corruption error.
895    pub(crate) fn startup_index_rebuild_invalid_data_key(
896        store_path: &str,
897        detail: impl fmt::Display,
898    ) -> Self {
899        Self::store_corruption(format!(
900            "startup index rebuild failed: invalid data key in store '{store_path}' ({detail})",
901        ))
902    }
903
904    /// Construct an index-origin corruption error.
905    #[cold]
906    #[inline(never)]
907    pub(crate) fn index_corruption(message: impl Into<String>) -> Self {
908        Self::new(ErrorClass::Corruption, ErrorOrigin::Index, message.into())
909    }
910
911    /// Construct the canonical unique-validation corruption wrapper.
912    pub(crate) fn index_unique_validation_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 structural index-entry corruption wrapper.
923    pub(crate) fn structural_index_entry_corruption(
924        entity_path: &str,
925        fields: &str,
926        detail: impl fmt::Display,
927    ) -> Self {
928        Self::index_plan_index_corruption(format!(
929            "index corrupted: {entity_path} ({fields}) -> {detail}",
930        ))
931    }
932
933    /// Construct the canonical missing new entity-key invariant during unique validation.
934    pub(crate) fn index_unique_validation_entity_key_required() -> Self {
935        Self::index_invariant("missing entity key during unique validation")
936    }
937
938    /// Construct the canonical unique-validation structural row-decode corruption error.
939    pub(crate) fn index_unique_validation_row_deserialize_failed(
940        data_key: impl fmt::Display,
941        source: impl fmt::Display,
942    ) -> Self {
943        Self::index_plan_serialize_corruption(format!(
944            "failed to structurally deserialize row: {data_key} ({source})"
945        ))
946    }
947
948    /// Construct the canonical unique-validation primary-key slot decode corruption error.
949    pub(crate) fn index_unique_validation_primary_key_decode_failed(
950        data_key: impl fmt::Display,
951        source: impl fmt::Display,
952    ) -> Self {
953        Self::index_plan_serialize_corruption(format!(
954            "failed to decode structural primary-key slot: {data_key} ({source})"
955        ))
956    }
957
958    /// Construct the canonical unique-validation stored key rebuild corruption error.
959    pub(crate) fn index_unique_validation_key_rebuild_failed(
960        data_key: impl fmt::Display,
961        entity_path: &str,
962        source: impl fmt::Display,
963    ) -> Self {
964        Self::index_plan_serialize_corruption(format!(
965            "failed to structurally decode unique key row {data_key} for {entity_path}: {source}",
966        ))
967    }
968
969    /// Construct the canonical unique-validation missing-row corruption error.
970    pub(crate) fn index_unique_validation_row_required(data_key: impl fmt::Display) -> Self {
971        Self::index_plan_store_corruption(format!("missing row: {data_key}"))
972    }
973
974    /// Construct the canonical index-only predicate missing-component invariant.
975    pub(crate) fn index_only_predicate_component_required() -> Self {
976        Self::index_invariant("index-only predicate program referenced missing index component")
977    }
978
979    /// Construct the canonical index-scan continuation-envelope invariant.
980    pub(crate) fn index_scan_continuation_anchor_within_envelope_required() -> Self {
981        Self::index_invariant(
982            "index-range continuation anchor is outside the requested range envelope",
983        )
984    }
985
986    /// Construct the canonical index-scan continuation-advancement invariant.
987    pub(crate) fn index_scan_continuation_advancement_required() -> Self {
988        Self::index_invariant("index-range continuation scan did not advance beyond the anchor")
989    }
990
991    /// Construct the canonical index-scan key-decode corruption error.
992    pub(crate) fn index_scan_key_corrupted_during(
993        context: &'static str,
994        err: impl fmt::Display,
995    ) -> Self {
996        Self::index_corruption(format!("index key corrupted during {context}: {err}"))
997    }
998
999    /// Construct the canonical index-scan missing projection-component invariant.
1000    pub(crate) fn index_projection_component_required(
1001        index_name: &str,
1002        component_index: usize,
1003    ) -> Self {
1004        Self::index_invariant(format!(
1005            "index projection referenced missing component: index='{index_name}' component_index={component_index}",
1006        ))
1007    }
1008
1009    /// Construct the canonical unexpected unique index-entry cardinality corruption error.
1010    pub(crate) fn unique_index_entry_single_key_required() -> Self {
1011        Self::index_corruption("unique index entry contains an unexpected number of keys")
1012    }
1013
1014    /// Construct the canonical scan-time index-entry decode corruption error.
1015    pub(crate) fn index_entry_decode_failed(err: impl fmt::Display) -> Self {
1016        Self::index_corruption(err.to_string())
1017    }
1018
1019    /// Construct a serialize-origin corruption error.
1020    pub(crate) fn serialize_corruption(message: impl Into<String>) -> Self {
1021        Self::new(
1022            ErrorClass::Corruption,
1023            ErrorOrigin::Serialize,
1024            message.into(),
1025        )
1026    }
1027
1028    /// Construct the canonical persisted-row decode corruption error.
1029    pub(crate) fn persisted_row_decode_failed(detail: impl fmt::Display) -> Self {
1030        Self::serialize_corruption(format!("row decode: {detail}"))
1031    }
1032
1033    /// Construct the canonical persisted-row field decode corruption error.
1034    pub(crate) fn persisted_row_field_decode_failed(
1035        field_name: &str,
1036        detail: impl fmt::Display,
1037    ) -> Self {
1038        Self::serialize_corruption(format!(
1039            "row decode failed for field '{field_name}': {detail}",
1040        ))
1041    }
1042
1043    /// Construct the canonical persisted-row field-kind decode corruption error.
1044    pub(crate) fn persisted_row_field_kind_decode_failed(
1045        field_name: &str,
1046        field_kind: impl fmt::Debug,
1047        detail: impl fmt::Display,
1048    ) -> Self {
1049        Self::persisted_row_field_decode_failed(
1050            field_name,
1051            format!("kind={field_kind:?}: {detail}"),
1052        )
1053    }
1054
1055    /// Construct the canonical persisted-row scalar-payload length corruption error.
1056    pub(crate) fn persisted_row_field_payload_exact_len_required(
1057        field_name: &str,
1058        payload_kind: &str,
1059        expected_len: usize,
1060    ) -> Self {
1061        let unit = if expected_len == 1 { "byte" } else { "bytes" };
1062
1063        Self::persisted_row_field_decode_failed(
1064            field_name,
1065            format!("{payload_kind} payload must be exactly {expected_len} {unit}"),
1066        )
1067    }
1068
1069    /// Construct the canonical persisted-row scalar-payload empty-body corruption error.
1070    pub(crate) fn persisted_row_field_payload_must_be_empty(
1071        field_name: &str,
1072        payload_kind: &str,
1073    ) -> Self {
1074        Self::persisted_row_field_decode_failed(
1075            field_name,
1076            format!("{payload_kind} payload must be empty"),
1077        )
1078    }
1079
1080    /// Construct the canonical persisted-row scalar-payload invalid-byte corruption error.
1081    pub(crate) fn persisted_row_field_payload_invalid_byte(
1082        field_name: &str,
1083        payload_kind: &str,
1084        value: u8,
1085    ) -> Self {
1086        Self::persisted_row_field_decode_failed(
1087            field_name,
1088            format!("invalid {payload_kind} payload byte {value}"),
1089        )
1090    }
1091
1092    /// Construct the canonical persisted-row scalar-payload non-finite corruption error.
1093    pub(crate) fn persisted_row_field_payload_non_finite(
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 is non-finite"),
1100        )
1101    }
1102
1103    /// Construct the canonical persisted-row scalar-payload out-of-range corruption error.
1104    pub(crate) fn persisted_row_field_payload_out_of_range(
1105        field_name: &str,
1106        payload_kind: &str,
1107    ) -> Self {
1108        Self::persisted_row_field_decode_failed(
1109            field_name,
1110            format!("{payload_kind} payload out of range for target type"),
1111        )
1112    }
1113
1114    /// Construct the canonical persisted-row invalid text payload corruption error.
1115    pub(crate) fn persisted_row_field_text_payload_invalid_utf8(
1116        field_name: &str,
1117        detail: impl fmt::Display,
1118    ) -> Self {
1119        Self::persisted_row_field_decode_failed(
1120            field_name,
1121            format!("invalid UTF-8 text payload ({detail})"),
1122        )
1123    }
1124
1125    /// Construct the canonical persisted-row structural slot-lookup invariant.
1126    pub(crate) fn persisted_row_slot_lookup_out_of_bounds(model_path: &str, slot: usize) -> Self {
1127        Self::index_invariant(format!(
1128            "slot lookup outside model bounds during structural row access: model='{model_path}' slot={slot}",
1129        ))
1130    }
1131
1132    /// Construct the canonical persisted-row structural slot-cache invariant.
1133    pub(crate) fn persisted_row_slot_cache_lookup_out_of_bounds(
1134        model_path: &str,
1135        slot: usize,
1136    ) -> Self {
1137        Self::index_invariant(format!(
1138            "slot cache lookup outside model bounds during structural row access: model='{model_path}' slot={slot}",
1139        ))
1140    }
1141
1142    /// Construct the canonical persisted-row primary-key decode corruption error.
1143    pub(crate) fn persisted_row_primary_key_not_storage_encodable(
1144        data_key: impl fmt::Debug,
1145        detail: impl fmt::Display,
1146    ) -> Self {
1147        Self::persisted_row_decode_failed(format!(
1148            "primary-key value is not storage-key encodable: {data_key:?} ({detail})",
1149        ))
1150    }
1151
1152    /// Construct the canonical persisted-row missing primary-key slot corruption error.
1153    pub(crate) fn persisted_row_primary_key_slot_missing(data_key: impl fmt::Debug) -> Self {
1154        Self::persisted_row_decode_failed(format!(
1155            "missing primary-key slot while validating {data_key:?}",
1156        ))
1157    }
1158
1159    /// Construct the canonical persisted-row key mismatch corruption error.
1160    pub(crate) fn persisted_row_key_mismatch(
1161        expected_key: impl fmt::Debug,
1162        found_key: impl fmt::Debug,
1163    ) -> Self {
1164        Self::store_corruption(format!(
1165            "row key mismatch: expected {expected_key:?}, found {found_key:?}",
1166        ))
1167    }
1168
1169    /// Construct the canonical persisted-row missing declared-field corruption error.
1170    pub(crate) fn persisted_row_declared_field_missing(field_name: &str) -> Self {
1171        Self::persisted_row_decode_failed(format!("missing declared field `{field_name}`"))
1172    }
1173
1174    /// Construct the canonical data-key entity mismatch corruption error.
1175    pub(crate) fn data_key_entity_mismatch(
1176        expected: impl fmt::Display,
1177        found: impl fmt::Display,
1178    ) -> Self {
1179        Self::store_corruption(format!(
1180            "data key entity mismatch: expected {expected}, found {found}",
1181        ))
1182    }
1183
1184    /// Construct the canonical reverse-index ordinal overflow internal error.
1185    pub(crate) fn reverse_index_ordinal_overflow(
1186        source_path: &str,
1187        field_name: &str,
1188        target_path: &str,
1189        detail: impl fmt::Display,
1190    ) -> Self {
1191        Self::index_internal(format!(
1192            "reverse index ordinal overflow: source={source_path} field={field_name} target={target_path} ({detail})",
1193        ))
1194    }
1195
1196    /// Construct the canonical reverse-index entry corruption error.
1197    pub(crate) fn reverse_index_entry_corrupted(
1198        source_path: &str,
1199        field_name: &str,
1200        target_path: &str,
1201        index_key: impl fmt::Debug,
1202        detail: impl fmt::Display,
1203    ) -> Self {
1204        Self::index_corruption(format!(
1205            "reverse index entry corrupted: source={source_path} field={field_name} target={target_path} key={index_key:?} ({detail})",
1206        ))
1207    }
1208
1209    /// Construct the canonical reverse-index entry encode unsupported error.
1210    pub(crate) fn reverse_index_entry_encode_failed(
1211        source_path: &str,
1212        field_name: &str,
1213        target_path: &str,
1214        detail: impl fmt::Display,
1215    ) -> Self {
1216        Self::index_unsupported(format!(
1217            "reverse index entry encoding failed: source={source_path} field={field_name} target={target_path} ({detail})",
1218        ))
1219    }
1220
1221    /// Construct the canonical relation-target store missing internal error.
1222    pub(crate) fn relation_target_store_missing(
1223        source_path: &str,
1224        field_name: &str,
1225        target_path: &str,
1226        store_path: &str,
1227        detail: impl fmt::Display,
1228    ) -> Self {
1229        Self::executor_internal(format!(
1230            "relation target store missing: source={source_path} field={field_name} target={target_path} store={store_path} ({detail})",
1231        ))
1232    }
1233
1234    /// Construct the canonical relation-target key decode corruption error.
1235    pub(crate) fn relation_target_key_decode_failed(
1236        context_label: &str,
1237        source_path: &str,
1238        field_name: &str,
1239        target_path: &str,
1240        detail: impl fmt::Display,
1241    ) -> Self {
1242        Self::identity_corruption(format!(
1243            "{context_label}: source={source_path} field={field_name} target={target_path} ({detail})",
1244        ))
1245    }
1246
1247    /// Construct the canonical relation-target entity mismatch corruption error.
1248    pub(crate) fn relation_target_entity_mismatch(
1249        context_label: &str,
1250        source_path: &str,
1251        field_name: &str,
1252        target_path: &str,
1253        target_entity_name: &str,
1254        expected_tag: impl fmt::Display,
1255        actual_tag: impl fmt::Display,
1256    ) -> Self {
1257        Self::store_corruption(format!(
1258            "{context_label}: source={source_path} field={field_name} target={target_path} expected={target_entity_name} (tag={expected_tag}) actual_tag={actual_tag}",
1259        ))
1260    }
1261
1262    /// Construct the canonical relation-source row decode corruption error.
1263    pub(crate) fn relation_source_row_decode_failed(
1264        source_path: &str,
1265        field_name: &str,
1266        target_path: &str,
1267        detail: impl fmt::Display,
1268    ) -> Self {
1269        Self::serialize_corruption(format!(
1270            "relation source row decode: source={source_path} field={field_name} target={target_path} ({detail})",
1271        ))
1272    }
1273
1274    /// Construct the canonical relation-source unsupported scalar relation-key corruption error.
1275    pub(crate) fn relation_source_row_unsupported_scalar_relation_key(
1276        source_path: &str,
1277        field_name: &str,
1278        target_path: &str,
1279    ) -> Self {
1280        Self::serialize_corruption(format!(
1281            "relation source row decode: unsupported scalar relation key: source={source_path} field={field_name} target={target_path}",
1282        ))
1283    }
1284
1285    /// Construct the canonical invalid strong-relation field-kind corruption error.
1286    pub(crate) fn relation_source_row_invalid_field_kind(field_kind: impl fmt::Debug) -> Self {
1287        Self::serialize_corruption(format!(
1288            "invalid strong relation field kind during structural decode: {field_kind:?}"
1289        ))
1290    }
1291
1292    /// Construct the canonical unsupported strong-relation key-kind corruption error.
1293    pub(crate) fn relation_source_row_unsupported_key_kind(field_kind: impl fmt::Debug) -> Self {
1294        Self::serialize_corruption(format!(
1295            "unsupported strong relation key kind during structural decode: {field_kind:?}"
1296        ))
1297    }
1298
1299    /// Construct the canonical reverse-index relation-target decode invariant failure.
1300    pub(crate) fn reverse_index_relation_target_decode_invariant_violated(
1301        source_path: &str,
1302        field_name: &str,
1303        target_path: &str,
1304    ) -> Self {
1305        Self::executor_internal(format!(
1306            "relation target decode invariant violated while preparing reverse index: source={source_path} field={field_name} target={target_path}",
1307        ))
1308    }
1309
1310    /// Construct the canonical covering-component empty-payload corruption error.
1311    pub(crate) fn bytes_covering_component_payload_empty() -> Self {
1312        Self::index_corruption("index component payload is empty during covering projection decode")
1313    }
1314
1315    /// Construct the canonical covering-component truncated bool corruption error.
1316    pub(crate) fn bytes_covering_bool_payload_truncated() -> Self {
1317        Self::index_corruption("bool covering component payload is truncated")
1318    }
1319
1320    /// Construct the canonical covering-component invalid-length corruption error.
1321    pub(crate) fn bytes_covering_component_payload_invalid_length(payload_kind: &str) -> Self {
1322        Self::index_corruption(format!(
1323            "{payload_kind} covering component payload has invalid length"
1324        ))
1325    }
1326
1327    /// Construct the canonical covering-component invalid-bool corruption error.
1328    pub(crate) fn bytes_covering_bool_payload_invalid_value() -> Self {
1329        Self::index_corruption("bool covering component payload has invalid value")
1330    }
1331
1332    /// Construct the canonical covering-component invalid text terminator corruption error.
1333    pub(crate) fn bytes_covering_text_payload_invalid_terminator() -> Self {
1334        Self::index_corruption("text covering component payload has invalid terminator")
1335    }
1336
1337    /// Construct the canonical covering-component trailing-text corruption error.
1338    pub(crate) fn bytes_covering_text_payload_trailing_bytes() -> Self {
1339        Self::index_corruption("text covering component payload contains trailing bytes")
1340    }
1341
1342    /// Construct the canonical covering-component invalid-UTF-8 text corruption error.
1343    pub(crate) fn bytes_covering_text_payload_invalid_utf8() -> Self {
1344        Self::index_corruption("text covering component payload is not valid UTF-8")
1345    }
1346
1347    /// Construct the canonical covering-component invalid text escape corruption error.
1348    pub(crate) fn bytes_covering_text_payload_invalid_escape_byte() -> Self {
1349        Self::index_corruption("text covering component payload has invalid escape byte")
1350    }
1351
1352    /// Construct the canonical covering-component missing text terminator corruption error.
1353    pub(crate) fn bytes_covering_text_payload_missing_terminator() -> Self {
1354        Self::index_corruption("text covering component payload is missing terminator")
1355    }
1356
1357    /// Construct the canonical missing persisted-field decode error.
1358    #[must_use]
1359    pub fn missing_persisted_slot(field_name: &'static str) -> Self {
1360        Self::serialize_corruption(format!("row decode: missing required field '{field_name}'"))
1361    }
1362
1363    /// Construct an identity-origin corruption error.
1364    pub(crate) fn identity_corruption(message: impl Into<String>) -> Self {
1365        Self::new(
1366            ErrorClass::Corruption,
1367            ErrorOrigin::Identity,
1368            message.into(),
1369        )
1370    }
1371
1372    /// Construct a store-origin unsupported error.
1373    #[cold]
1374    #[inline(never)]
1375    pub(crate) fn store_unsupported(message: impl Into<String>) -> Self {
1376        Self::new(ErrorClass::Unsupported, ErrorOrigin::Store, message.into())
1377    }
1378
1379    /// Construct the canonical unsupported persisted entity-tag store error.
1380    pub(crate) fn unsupported_entity_tag_in_data_store(
1381        entity_tag: crate::types::EntityTag,
1382    ) -> Self {
1383        Self::store_unsupported(format!(
1384            "unsupported entity tag in data store: '{}'",
1385            entity_tag.value()
1386        ))
1387    }
1388
1389    /// Construct the canonical configured-vs-registered commit-memory id mismatch error.
1390    pub(crate) fn configured_commit_memory_id_mismatch(
1391        configured_id: u8,
1392        registered_id: u8,
1393    ) -> Self {
1394        Self::store_unsupported(format!(
1395            "configured commit memory id {configured_id} does not match existing commit marker id {registered_id}",
1396        ))
1397    }
1398
1399    /// Construct the canonical occupied commit-memory id unsupported error.
1400    pub(crate) fn commit_memory_id_already_registered(memory_id: u8, label: &str) -> Self {
1401        Self::store_unsupported(format!(
1402            "configured commit memory id {memory_id} is already registered as '{label}'",
1403        ))
1404    }
1405
1406    /// Construct the canonical out-of-range commit-memory id unsupported error.
1407    pub(crate) fn commit_memory_id_outside_reserved_ranges(memory_id: u8) -> Self {
1408        Self::store_unsupported(format!(
1409            "configured commit memory id {memory_id} is outside reserved ranges",
1410        ))
1411    }
1412
1413    /// Construct the canonical commit-memory id registration failure.
1414    pub(crate) fn commit_memory_id_registration_failed(err: impl fmt::Display) -> Self {
1415        Self::store_internal(format!("commit memory id registration failed: {err}"))
1416    }
1417
1418    /// Construct an index-origin unsupported error.
1419    pub(crate) fn index_unsupported(message: impl Into<String>) -> Self {
1420        Self::new(ErrorClass::Unsupported, ErrorOrigin::Index, message.into())
1421    }
1422
1423    /// Construct the canonical index-key component size-limit unsupported error.
1424    pub(crate) fn index_component_exceeds_max_size(
1425        key_item: impl fmt::Display,
1426        len: usize,
1427        max_component_size: usize,
1428    ) -> Self {
1429        Self::index_unsupported(format!(
1430            "index component exceeds max size: key item '{key_item}' -> {len} bytes (limit {max_component_size})",
1431        ))
1432    }
1433
1434    /// Construct the canonical index-entry max-keys unsupported error during commit encoding.
1435    pub(crate) fn index_entry_exceeds_max_keys(
1436        entity_path: &str,
1437        fields: &str,
1438        keys: usize,
1439    ) -> Self {
1440        Self::index_unsupported(format!(
1441            "index entry exceeds max keys: {entity_path} ({fields}) -> {keys} keys",
1442        ))
1443    }
1444
1445    /// Construct the canonical duplicate-key invariant during commit entry encoding.
1446    #[cfg(test)]
1447    pub(crate) fn index_entry_duplicate_keys_unexpected(entity_path: &str, fields: &str) -> Self {
1448        Self::index_invariant(format!(
1449            "index entry unexpectedly contains duplicate keys: {entity_path} ({fields})",
1450        ))
1451    }
1452
1453    /// Construct the canonical index-entry key-encoding unsupported error during commit encoding.
1454    pub(crate) fn index_entry_key_encoding_failed(
1455        entity_path: &str,
1456        fields: &str,
1457        err: impl fmt::Display,
1458    ) -> Self {
1459        Self::index_unsupported(format!(
1460            "index entry key encoding failed: {entity_path} ({fields}) -> {err}",
1461        ))
1462    }
1463
1464    /// Construct a serialize-origin unsupported error.
1465    pub(crate) fn serialize_unsupported(message: impl Into<String>) -> Self {
1466        Self::new(
1467            ErrorClass::Unsupported,
1468            ErrorOrigin::Serialize,
1469            message.into(),
1470        )
1471    }
1472
1473    /// Construct a cursor-origin unsupported error.
1474    pub(crate) fn cursor_unsupported(message: impl Into<String>) -> Self {
1475        Self::new(ErrorClass::Unsupported, ErrorOrigin::Cursor, message.into())
1476    }
1477
1478    /// Construct a serialize-origin incompatible persisted-format error.
1479    pub(crate) fn serialize_incompatible_persisted_format(message: impl Into<String>) -> Self {
1480        Self::new(
1481            ErrorClass::IncompatiblePersistedFormat,
1482            ErrorOrigin::Serialize,
1483            message.into(),
1484        )
1485    }
1486
1487    /// Construct a query-origin unsupported error preserving one SQL parser
1488    /// unsupported-feature label in structured error detail.
1489    #[cfg(feature = "sql")]
1490    pub(crate) fn query_unsupported_sql_feature(feature: &'static str) -> Self {
1491        let message = format!(
1492            "SQL query is not executable in this release: unsupported SQL feature: {feature}"
1493        );
1494
1495        Self {
1496            class: ErrorClass::Unsupported,
1497            origin: ErrorOrigin::Query,
1498            message,
1499            detail: Some(ErrorDetail::Query(
1500                QueryErrorDetail::UnsupportedSqlFeature { feature },
1501            )),
1502        }
1503    }
1504
1505    pub fn store_not_found(key: impl Into<String>) -> Self {
1506        let key = key.into();
1507
1508        Self {
1509            class: ErrorClass::NotFound,
1510            origin: ErrorOrigin::Store,
1511            message: format!("data key not found: {key}"),
1512            detail: Some(ErrorDetail::Store(StoreError::NotFound { key })),
1513        }
1514    }
1515
1516    /// Construct a standardized unsupported-entity-path error.
1517    pub fn unsupported_entity_path(path: impl Into<String>) -> Self {
1518        let path = path.into();
1519
1520        Self::new(
1521            ErrorClass::Unsupported,
1522            ErrorOrigin::Store,
1523            format!("unsupported entity path: '{path}'"),
1524        )
1525    }
1526
1527    #[must_use]
1528    pub const fn is_not_found(&self) -> bool {
1529        matches!(
1530            self.detail,
1531            Some(ErrorDetail::Store(StoreError::NotFound { .. }))
1532        )
1533    }
1534
1535    #[must_use]
1536    pub fn display_with_class(&self) -> String {
1537        format!("{}:{}: {}", self.origin, self.class, self.message)
1538    }
1539
1540    /// Construct an index-plan corruption error with a canonical prefix.
1541    #[cold]
1542    #[inline(never)]
1543    pub(crate) fn index_plan_corruption(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1544        let message = message.into();
1545        Self::new(
1546            ErrorClass::Corruption,
1547            origin,
1548            format!("corruption detected ({origin}): {message}"),
1549        )
1550    }
1551
1552    /// Construct an index-plan corruption error for index-origin failures.
1553    #[cold]
1554    #[inline(never)]
1555    pub(crate) fn index_plan_index_corruption(message: impl Into<String>) -> Self {
1556        Self::index_plan_corruption(ErrorOrigin::Index, message)
1557    }
1558
1559    /// Construct an index-plan corruption error for store-origin failures.
1560    #[cold]
1561    #[inline(never)]
1562    pub(crate) fn index_plan_store_corruption(message: impl Into<String>) -> Self {
1563        Self::index_plan_corruption(ErrorOrigin::Store, message)
1564    }
1565
1566    /// Construct an index-plan corruption error for serialize-origin failures.
1567    #[cold]
1568    #[inline(never)]
1569    pub(crate) fn index_plan_serialize_corruption(message: impl Into<String>) -> Self {
1570        Self::index_plan_corruption(ErrorOrigin::Serialize, message)
1571    }
1572
1573    /// Construct an index-plan invariant violation error with a canonical prefix.
1574    #[cfg(test)]
1575    pub(crate) fn index_plan_invariant(origin: ErrorOrigin, message: impl Into<String>) -> Self {
1576        let message = message.into();
1577        Self::new(
1578            ErrorClass::InvariantViolation,
1579            origin,
1580            format!("invariant violation detected ({origin}): {message}"),
1581        )
1582    }
1583
1584    /// Construct an index-plan invariant violation error for store-origin failures.
1585    #[cfg(test)]
1586    pub(crate) fn index_plan_store_invariant(message: impl Into<String>) -> Self {
1587        Self::index_plan_invariant(ErrorOrigin::Store, message)
1588    }
1589
1590    /// Construct an index uniqueness violation conflict error.
1591    pub(crate) fn index_violation(path: &str, index_fields: &[&str]) -> Self {
1592        Self::new(
1593            ErrorClass::Conflict,
1594            ErrorOrigin::Index,
1595            format!(
1596                "index constraint violation: {path} ({})",
1597                index_fields.join(", ")
1598            ),
1599        )
1600    }
1601}
1602
1603///
1604/// ErrorDetail
1605///
1606/// Structured, origin-specific error detail carried by [`InternalError`].
1607/// This enum is intentionally extensible.
1608///
1609
1610#[derive(Debug, ThisError)]
1611pub enum ErrorDetail {
1612    #[error("{0}")]
1613    Store(StoreError),
1614    #[error("{0}")]
1615    Query(QueryErrorDetail),
1616    // Future-proofing:
1617    // #[error("{0}")]
1618    // Index(IndexError),
1619    //
1620    // #[error("{0}")]
1621    // Executor(ExecutorErrorDetail),
1622}
1623
1624///
1625/// StoreError
1626///
1627/// Store-specific structured error detail.
1628/// Never returned directly; always wrapped in [`ErrorDetail::Store`].
1629///
1630
1631#[derive(Debug, ThisError)]
1632pub enum StoreError {
1633    #[error("key not found: {key}")]
1634    NotFound { key: String },
1635
1636    #[error("store corruption: {message}")]
1637    Corrupt { message: String },
1638
1639    #[error("store invariant violation: {message}")]
1640    InvariantViolation { message: String },
1641}
1642
1643///
1644/// QueryErrorDetail
1645///
1646/// Query-origin structured error detail payload.
1647///
1648
1649#[derive(Debug, ThisError)]
1650pub enum QueryErrorDetail {
1651    #[error("numeric overflow")]
1652    NumericOverflow,
1653
1654    #[error("numeric result is not representable")]
1655    NumericNotRepresentable,
1656
1657    #[error("unsupported SQL feature: {feature}")]
1658    UnsupportedSqlFeature { feature: &'static str },
1659}
1660
1661///
1662/// ErrorClass
1663/// Internal error taxonomy for runtime classification.
1664/// Not a stable API; may change without notice.
1665///
1666
1667#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1668pub enum ErrorClass {
1669    Corruption,
1670    IncompatiblePersistedFormat,
1671    NotFound,
1672    Internal,
1673    Conflict,
1674    Unsupported,
1675    InvariantViolation,
1676}
1677
1678impl fmt::Display for ErrorClass {
1679    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1680        let label = match self {
1681            Self::Corruption => "corruption",
1682            Self::IncompatiblePersistedFormat => "incompatible_persisted_format",
1683            Self::NotFound => "not_found",
1684            Self::Internal => "internal",
1685            Self::Conflict => "conflict",
1686            Self::Unsupported => "unsupported",
1687            Self::InvariantViolation => "invariant_violation",
1688        };
1689        write!(f, "{label}")
1690    }
1691}
1692
1693///
1694/// ErrorOrigin
1695/// Internal origin taxonomy for runtime classification.
1696/// Not a stable API; may change without notice.
1697///
1698
1699#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1700pub enum ErrorOrigin {
1701    Serialize,
1702    Store,
1703    Index,
1704    Identity,
1705    Query,
1706    Planner,
1707    Cursor,
1708    Recovery,
1709    Response,
1710    Executor,
1711    Interface,
1712}
1713
1714impl fmt::Display for ErrorOrigin {
1715    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1716        let label = match self {
1717            Self::Serialize => "serialize",
1718            Self::Store => "store",
1719            Self::Index => "index",
1720            Self::Identity => "identity",
1721            Self::Query => "query",
1722            Self::Planner => "planner",
1723            Self::Cursor => "cursor",
1724            Self::Recovery => "recovery",
1725            Self::Response => "response",
1726            Self::Executor => "executor",
1727            Self::Interface => "interface",
1728        };
1729        write!(f, "{label}")
1730    }
1731}