Skip to main content

laminar_core/
error_codes.rs

1//! LaminarDB structured error code registry.
2//!
3//! Every error in LaminarDB carries a stable `LDB-NNNN` code that is:
4//! - Present in the error message (grep-able in logs)
5//! - Present in the source code (grep-able in code)
6//! - Stable across versions (codes are never reused)
7//!
8//! # Code Ranges
9//!
10//! | Range | Category |
11//! |-------|----------|
12//! | `LDB-0xxx` | General / configuration |
13//! | `LDB-1xxx` | SQL parsing & validation |
14//! | `LDB-2xxx` | Window / watermark operations |
15//! | `LDB-3xxx` | Join operations |
16//! | `LDB-4xxx` | Serialization / state |
17//! | `LDB-5xxx` | Connector / I/O |
18//! | `LDB-6xxx` | Checkpoint / recovery |
19//! | `LDB-7xxx` | DataFusion / Arrow interop |
20//! | `LDB-8xxx` | Internal / should-not-happen |
21//!
22//! Codes within the `LDB-1xxx` through `LDB-3xxx` ranges are defined in
23//! `laminar-sql::error::codes` (the SQL layer) and are re-exported here
24//! for reference. This module is the canonical registry for all other ranges.
25
26// ── General / Configuration (LDB-0xxx) ──
27
28/// Invalid configuration value.
29pub const INVALID_CONFIG: &str = "LDB-0001";
30/// Missing required configuration key.
31pub const MISSING_CONFIG: &str = "LDB-0002";
32/// Unresolved config variable (e.g. `${VAR}` placeholder).
33pub const UNRESOLVED_CONFIG_VAR: &str = "LDB-0003";
34/// Database is shut down.
35pub const SHUTDOWN: &str = "LDB-0004";
36/// Invalid operation for the current state.
37pub const INVALID_OPERATION: &str = "LDB-0005";
38/// Schema mismatch between Rust type and SQL definition.
39pub const SCHEMA_MISMATCH: &str = "LDB-0006";
40
41// ── SQL Parsing & Validation (LDB-1xxx) ──
42// Canonical definitions are in `laminar_sql::error::codes`.
43// Repeated here for reference only.
44
45/// Unsupported SQL syntax (canonical: `laminar_sql::error::codes::UNSUPPORTED_SQL`).
46pub const SQL_UNSUPPORTED: &str = "LDB-1001";
47/// Query planning failed.
48pub const SQL_PLANNING_FAILED: &str = "LDB-1002";
49/// Column not found.
50pub const SQL_COLUMN_NOT_FOUND: &str = "LDB-1100";
51/// Table or source not found.
52pub const SQL_TABLE_NOT_FOUND: &str = "LDB-1101";
53/// Type mismatch.
54pub const SQL_TYPE_MISMATCH: &str = "LDB-1200";
55
56// ── Window / Watermark (LDB-2xxx) ──
57
58/// Watermark required for this operation.
59pub const WATERMARK_REQUIRED: &str = "LDB-2001";
60/// Invalid window specification.
61pub const WINDOW_INVALID: &str = "LDB-2002";
62/// Window size must be positive.
63pub const WINDOW_SIZE_INVALID: &str = "LDB-2003";
64/// Late data rejected by window policy.
65pub const LATE_DATA_REJECTED: &str = "LDB-2004";
66
67// ── Join (LDB-3xxx) ──
68
69/// Join key column not found or invalid.
70pub const JOIN_KEY_MISSING: &str = "LDB-3001";
71/// Time bound required for stream-stream join.
72pub const JOIN_TIME_BOUND_MISSING: &str = "LDB-3002";
73/// Temporal join requires a primary key on the right-side table.
74pub const TEMPORAL_JOIN_NO_PK: &str = "LDB-3003";
75/// Unsupported join type for streaming queries.
76pub const JOIN_TYPE_UNSUPPORTED: &str = "LDB-3004";
77
78// ── Serialization / State (LDB-4xxx) ──
79
80/// State serialization failed for an operator.
81pub const SERIALIZATION_FAILED: &str = "LDB-4001";
82/// State deserialization failed for an operator.
83pub const DESERIALIZATION_FAILED: &str = "LDB-4002";
84/// JSON parse error (connector config, CDC payload, etc.).
85pub const JSON_PARSE_ERROR: &str = "LDB-4003";
86/// Base64 decode error (inline checkpoint state).
87pub const BASE64_DECODE_ERROR: &str = "LDB-4004";
88/// State store key not found.
89pub const STATE_KEY_MISSING: &str = "LDB-4005";
90/// State corruption detected (checksum mismatch, invalid data).
91pub const STATE_CORRUPTION: &str = "LDB-4006";
92
93// ── Connector / I/O (LDB-5xxx) ──
94
95/// Connector failed to establish a connection.
96pub const CONNECTOR_CONNECTION_FAILED: &str = "LDB-5001";
97/// Connector authentication failed.
98pub const CONNECTOR_AUTH_FAILED: &str = "LDB-5002";
99/// Connector read error.
100pub const CONNECTOR_READ_ERROR: &str = "LDB-5003";
101/// Connector write error.
102pub const CONNECTOR_WRITE_ERROR: &str = "LDB-5004";
103/// Connector configuration error.
104pub const CONNECTOR_CONFIG_ERROR: &str = "LDB-5005";
105/// Source not found.
106pub const SOURCE_NOT_FOUND: &str = "LDB-5010";
107/// Sink not found.
108pub const SINK_NOT_FOUND: &str = "LDB-5011";
109/// Source already exists.
110pub const SOURCE_ALREADY_EXISTS: &str = "LDB-5012";
111/// Sink already exists.
112pub const SINK_ALREADY_EXISTS: &str = "LDB-5013";
113/// Connector serde (serialization/deserialization) error.
114pub const CONNECTOR_SERDE_ERROR: &str = "LDB-5020";
115/// Schema inference or compatibility error.
116pub const CONNECTOR_SCHEMA_ERROR: &str = "LDB-5021";
117
118// ── Checkpoint / Recovery (LDB-6xxx) ──
119
120/// Checkpoint creation failed.
121pub const CHECKPOINT_FAILED: &str = "LDB-6001";
122/// Checkpoint not found.
123pub const CHECKPOINT_NOT_FOUND: &str = "LDB-6002";
124/// Checkpoint recovery failed.
125pub const RECOVERY_FAILED: &str = "LDB-6003";
126/// Sink rollback failed during checkpoint abort.
127pub const SINK_ROLLBACK_FAILED: &str = "LDB-6004";
128/// WAL (write-ahead log) error.
129pub const WAL_ERROR: &str = "LDB-6005";
130/// WAL entry has invalid length (possible corruption).
131pub const WAL_INVALID_LENGTH: &str = "LDB-6006";
132/// WAL checksum mismatch.
133pub const WAL_CHECKSUM_MISMATCH: &str = "LDB-6007";
134/// Checkpoint manifest persistence failed.
135pub const MANIFEST_PERSIST_FAILED: &str = "LDB-6008";
136/// Checkpoint prune (old checkpoint cleanup) failed.
137pub const CHECKPOINT_PRUNE_FAILED: &str = "LDB-6009";
138/// Sidecar state data missing or corrupted.
139pub const SIDECAR_CORRUPTION: &str = "LDB-6010";
140/// Source offset metadata missing during recovery.
141pub const OFFSET_METADATA_MISSING: &str = "LDB-6011";
142
143// ── DataFusion / Arrow Interop (LDB-7xxx) ──
144
145/// Query execution failed (`DataFusion` engine error).
146/// Note: the SQL layer uses `LDB-9001` for execution failures visible to users;
147/// `LDB-7001` is for internal `DataFusion` interop issues.
148pub const QUERY_EXECUTION_FAILED: &str = "LDB-7001";
149/// Arrow schema or record batch error.
150pub const ARROW_ERROR: &str = "LDB-7002";
151/// `DataFusion` plan optimization failed.
152pub const PLAN_OPTIMIZATION_FAILED: &str = "LDB-7003";
153
154// ── Internal / Should-Not-Happen (LDB-8xxx) ──
155
156/// Internal error — this is a bug.
157pub const INTERNAL: &str = "LDB-8001";
158/// Pipeline error (start/shutdown lifecycle).
159pub const PIPELINE_ERROR: &str = "LDB-8002";
160/// Materialized view error.
161pub const MATERIALIZED_VIEW_ERROR: &str = "LDB-8003";
162/// Query pipeline error (stream execution context).
163pub const QUERY_PIPELINE_ERROR: &str = "LDB-8004";
164
165// ── Ring 0 Hot Path Errors ──
166
167/// Ring 0 error — no heap allocation, no formatting on construction.
168///
169/// Only formatted when actually displayed (which happens outside Ring 0).
170/// Uses `Copy` and `repr(u16)` for zero-cost error reporting via counters.
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172#[repr(u16)]
173pub enum HotPathError {
174    /// Event arrived after watermark — dropped.
175    LateEvent = 0x0001,
176    /// State store key not found.
177    StateKeyMissing = 0x0002,
178    /// Downstream backpressure — event buffered.
179    Backpressure = 0x0003,
180    /// Serialization buffer overflow.
181    SerializationOverflow = 0x0004,
182    /// Record batch schema does not match expected.
183    SchemaMismatch = 0x0005,
184    /// Aggregate state corruption detected.
185    AggregateStateCorruption = 0x0006,
186    /// Queue is full — cannot push event.
187    QueueFull = 0x0007,
188    /// Channel is closed/disconnected.
189    ChannelClosed = 0x0008,
190}
191
192impl HotPathError {
193    /// Returns a static error message. Cost: one match. No allocation.
194    #[must_use]
195    pub const fn message(self) -> &'static str {
196        match self {
197            Self::LateEvent => "Event arrived after watermark; dropped",
198            Self::StateKeyMissing => "State key not found in store",
199            Self::Backpressure => "Downstream backpressure; event buffered",
200            Self::SerializationOverflow => "Serialization buffer capacity exceeded",
201            Self::SchemaMismatch => "Record batch schema does not match expected",
202            Self::AggregateStateCorruption => "Aggregate state checksum mismatch detected",
203            Self::QueueFull => "Queue is full; cannot push event",
204            Self::ChannelClosed => "Channel is closed or disconnected",
205        }
206    }
207
208    /// Numeric code for metrics counters. Zero-cost.
209    #[must_use]
210    pub const fn code(self) -> u16 {
211        self as u16
212    }
213
214    /// Returns the `LDB-NNNN` error code string for this hot path error.
215    #[must_use]
216    pub const fn ldb_code(self) -> &'static str {
217        match self {
218            Self::LateEvent => LATE_DATA_REJECTED,
219            Self::StateKeyMissing => STATE_KEY_MISSING,
220            Self::Backpressure => "LDB-8010",
221            Self::SerializationOverflow => SERIALIZATION_FAILED,
222            Self::SchemaMismatch => SCHEMA_MISMATCH,
223            Self::AggregateStateCorruption => STATE_CORRUPTION,
224            Self::QueueFull => "LDB-8011",
225            Self::ChannelClosed => "LDB-8012",
226        }
227    }
228}
229
230impl std::fmt::Display for HotPathError {
231    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232        write!(f, "[{}] {}", self.ldb_code(), self.message())
233    }
234}
235
236impl std::error::Error for HotPathError {}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    #[test]
243    fn hot_path_error_is_copy_and_small() {
244        let e = HotPathError::LateEvent;
245        let e2 = e; // Copy
246        assert_eq!(e, e2);
247        assert_eq!(std::mem::size_of::<HotPathError>(), 2);
248    }
249
250    #[test]
251    fn hot_path_error_codes_are_nonzero() {
252        let variants = [
253            HotPathError::LateEvent,
254            HotPathError::StateKeyMissing,
255            HotPathError::Backpressure,
256            HotPathError::SerializationOverflow,
257            HotPathError::SchemaMismatch,
258            HotPathError::AggregateStateCorruption,
259            HotPathError::QueueFull,
260            HotPathError::ChannelClosed,
261        ];
262        for v in &variants {
263            assert!(v.code() > 0, "{v:?} has zero code");
264            assert!(!v.message().is_empty(), "{v:?} has empty message");
265            assert!(
266                v.ldb_code().starts_with("LDB-"),
267                "{v:?} has bad ldb_code: {}",
268                v.ldb_code()
269            );
270        }
271    }
272
273    #[test]
274    fn hot_path_error_display() {
275        let e = HotPathError::LateEvent;
276        let s = e.to_string();
277        assert!(s.starts_with("[LDB-"));
278        assert!(s.contains("watermark"));
279    }
280
281    #[test]
282    fn error_codes_are_stable_strings() {
283        assert_eq!(INVALID_CONFIG, "LDB-0001");
284        assert_eq!(SERIALIZATION_FAILED, "LDB-4001");
285        assert_eq!(CHECKPOINT_FAILED, "LDB-6001");
286        assert_eq!(INTERNAL, "LDB-8001");
287    }
288}