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