Skip to main content

icydb_core/error/
mod.rs

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