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//! This module is the canonical registry for all error code ranges.
23//! Downstream crates (`laminar-sql`, `laminar-db`, etc.) re-export from here.
24
25// ── General / Configuration (LDB-0xxx) ──
26
27/// Invalid configuration value.
28pub const INVALID_CONFIG: &str = "LDB-0001";
29/// Missing required configuration key.
30pub const MISSING_CONFIG: &str = "LDB-0002";
31/// Unresolved config variable (e.g. `${VAR}` placeholder).
32pub const UNRESOLVED_CONFIG_VAR: &str = "LDB-0003";
33/// Database is shut down.
34pub const SHUTDOWN: &str = "LDB-0004";
35/// Invalid operation for the current state.
36pub const INVALID_OPERATION: &str = "LDB-0005";
37/// Schema mismatch between Rust type and SQL definition.
38pub const SCHEMA_MISMATCH: &str = "LDB-0006";
39
40// ── SQL Parsing & Validation (LDB-1xxx) ──
41
42/// Unsupported SQL syntax.
43pub const SQL_UNSUPPORTED: &str = "LDB-1001";
44/// Query planning failed.
45pub const SQL_PLANNING_FAILED: &str = "LDB-1002";
46/// Column not found.
47pub const SQL_COLUMN_NOT_FOUND: &str = "LDB-1100";
48/// Table or source not found.
49pub const SQL_TABLE_NOT_FOUND: &str = "LDB-1101";
50/// Type mismatch.
51pub const SQL_TYPE_MISMATCH: &str = "LDB-1200";
52
53// ── Window / Watermark (LDB-2xxx) ──
54
55/// Watermark required for this operation.
56pub const WATERMARK_REQUIRED: &str = "LDB-2001";
57/// Invalid window specification.
58pub const WINDOW_INVALID: &str = "LDB-2002";
59/// Window size must be positive.
60pub const WINDOW_SIZE_INVALID: &str = "LDB-2003";
61/// Late data rejected by window policy.
62pub const LATE_DATA_REJECTED: &str = "LDB-2004";
63
64// ── Join (LDB-3xxx) ──
65
66/// Join key column not found or invalid.
67pub const JOIN_KEY_MISSING: &str = "LDB-3001";
68/// Time bound required for stream-stream join.
69pub const JOIN_TIME_BOUND_MISSING: &str = "LDB-3002";
70/// Temporal join requires a primary key on the right-side table.
71pub const TEMPORAL_JOIN_NO_PK: &str = "LDB-3003";
72/// Unsupported join type for streaming queries.
73pub const JOIN_TYPE_UNSUPPORTED: &str = "LDB-3004";
74// ── Serialization / State (LDB-4xxx) ──
75
76/// State serialization failed for an operator.
77pub const SERIALIZATION_FAILED: &str = "LDB-4001";
78/// State deserialization failed for an operator.
79pub const DESERIALIZATION_FAILED: &str = "LDB-4002";
80/// JSON parse error (connector config, CDC payload, etc.).
81pub const JSON_PARSE_ERROR: &str = "LDB-4003";
82/// Base64 decode error (inline checkpoint state).
83pub const BASE64_DECODE_ERROR: &str = "LDB-4004";
84/// State store key not found.
85pub const STATE_KEY_MISSING: &str = "LDB-4005";
86/// State corruption detected (checksum mismatch, invalid data).
87pub const STATE_CORRUPTION: &str = "LDB-4006";
88/// A cluster query shape has no vnode-keyed checkpoint and rebalance lifecycle.
89pub const CLUSTER_STATE_LIFECYCLE_UNSUPPORTED: &str = "LDB-4007";
90// ── Connector / I/O (LDB-5xxx) ──
91
92/// Connector failed to establish a connection.
93pub const CONNECTOR_CONNECTION_FAILED: &str = "LDB-5001";
94/// Connector authentication failed.
95pub const CONNECTOR_AUTH_FAILED: &str = "LDB-5002";
96/// Connector read error.
97pub const CONNECTOR_READ_ERROR: &str = "LDB-5003";
98/// Connector write error.
99pub const CONNECTOR_WRITE_ERROR: &str = "LDB-5004";
100/// Connector configuration error.
101pub const CONNECTOR_CONFIG_ERROR: &str = "LDB-5005";
102/// Source not found.
103pub const SOURCE_NOT_FOUND: &str = "LDB-5010";
104/// Sink not found.
105pub const SINK_NOT_FOUND: &str = "LDB-5011";
106/// Source already exists.
107pub const SOURCE_ALREADY_EXISTS: &str = "LDB-5012";
108/// Sink already exists.
109pub const SINK_ALREADY_EXISTS: &str = "LDB-5013";
110/// Connector serde (serialization/deserialization) error.
111pub const CONNECTOR_SERDE_ERROR: &str = "LDB-5020";
112/// Schema inference or compatibility error.
113pub const CONNECTOR_SCHEMA_ERROR: &str = "LDB-5021";
114/// Exactly-once requires all sources to support replay.
115pub const EXACTLY_ONCE_NON_REPLAYABLE: &str = "LDB-5030";
116/// Exactly-once requires all sinks to support exactly-once semantics.
117pub const EXACTLY_ONCE_SINK_UNSUPPORTED: &str = "LDB-5031";
118/// Exactly-once requires checkpointing to be enabled.
119pub const EXACTLY_ONCE_NO_CHECKPOINT: &str = "LDB-5032";
120/// Mixed delivery capabilities — some sources are non-replayable.
121pub const MIXED_DELIVERY_CAPABILITIES: &str = "LDB-5033";
122/// A source requires checkpointing to release upstream progress or resources.
123pub const SOURCE_CHECKPOINT_REQUIRED: &str = "LDB-5034";
124/// The configured exactly-once source/sink protocol is incomplete.
125pub const EXACTLY_ONCE_PROTOCOL_INCOMPLETE: &str = "LDB-5035";
126/// Delivery requires a stronger state/checkpoint durability scope.
127pub const DELIVERY_STATE_DURABILITY_MISMATCH: &str = "LDB-5036";
128/// A replayable source has not passed production exactly-once certification.
129pub const EXACTLY_ONCE_SOURCE_UNCERTIFIED: &str = "LDB-5037";
130
131// ── Checkpoint / Recovery (LDB-6xxx) ──
132
133/// Checkpoint creation failed.
134pub const CHECKPOINT_FAILED: &str = "LDB-6001";
135/// Checkpoint not found.
136pub const CHECKPOINT_NOT_FOUND: &str = "LDB-6002";
137/// Checkpoint recovery failed.
138pub const RECOVERY_FAILED: &str = "LDB-6003";
139/// Sink rollback failed during checkpoint abort.
140pub const SINK_ROLLBACK_FAILED: &str = "LDB-6004";
141/// WAL (write-ahead log) error.
142pub const WAL_ERROR: &str = "LDB-6005";
143/// WAL entry has invalid length (possible corruption).
144pub const WAL_INVALID_LENGTH: &str = "LDB-6006";
145/// WAL checksum mismatch.
146pub const WAL_CHECKSUM_MISMATCH: &str = "LDB-6007";
147/// Checkpoint manifest persistence failed.
148pub const MANIFEST_PERSIST_FAILED: &str = "LDB-6008";
149/// Checkpoint prune (old checkpoint cleanup) failed.
150pub const CHECKPOINT_PRUNE_FAILED: &str = "LDB-6009";
151/// Sidecar state data missing or corrupted.
152pub const SIDECAR_CORRUPTION: &str = "LDB-6010";
153/// Source offset metadata missing during recovery.
154pub const OFFSET_METADATA_MISSING: &str = "LDB-6011";
155/// State durability gate returned false before sink commit. One or more
156/// vnodes had not persisted their partials for the epoch. The coordinator
157/// rolls back sinks and retries on the next checkpoint.
158pub const DURABILITY_GATE_MISS: &str = "LDB-6020";
159/// Sink rollback failed after a durability-gate miss. Sinks may be in an
160/// inconsistent state; recovery uses the exact durable commit decision to resolve.
161pub const DURABILITY_GATE_ROLLBACK_FAILED: &str = "LDB-6021";
162/// State backend returned an error during the durability gate (backend
163/// unreachable, permission denied). Treated as a gate miss; sinks rolled
164/// back and the next checkpoint retries.
165pub const DURABILITY_GATE_BACKEND_ERROR: &str = "LDB-6022";
166/// Sink rollback failed after a durability-gate backend error.
167pub const DURABILITY_GATE_ROLLBACK_ON_ERROR_FAILED: &str = "LDB-6023";
168
169// ── DataFusion / Arrow Interop (LDB-7xxx) ──
170
171/// Query execution failed (`DataFusion` engine error).
172/// Note: the SQL layer uses `LDB-9001` for execution failures visible to users;
173/// `LDB-7001` is for internal `DataFusion` interop issues.
174pub const QUERY_EXECUTION_FAILED: &str = "LDB-7001";
175/// Arrow schema or record batch error.
176pub const ARROW_ERROR: &str = "LDB-7002";
177/// `DataFusion` plan optimization failed.
178pub const PLAN_OPTIMIZATION_FAILED: &str = "LDB-7003";
179
180// ── Internal / Should-Not-Happen (LDB-8xxx) ──
181
182/// Internal error — this is a bug.
183pub const INTERNAL: &str = "LDB-8001";
184/// Pipeline error (start/shutdown lifecycle).
185pub const PIPELINE_ERROR: &str = "LDB-8002";
186/// Materialized view error.
187pub const MATERIALIZED_VIEW_ERROR: &str = "LDB-8003";
188/// Query pipeline error (stream execution context).
189pub const QUERY_PIPELINE_ERROR: &str = "LDB-8004";
190/// No compiled projection or cached plan for pre-aggregation query.
191pub const NO_COMPILED_PROJECTION: &str = "LDB-8050";
192
193// ── Ring 0 Hot Path Errors ──
194
195/// Ring 0 error — no heap allocation, no formatting on construction.
196///
197/// Only formatted when actually displayed (which happens outside Ring 0).
198/// Uses `Copy` and `repr(u16)` for zero-cost error reporting via counters.
199#[derive(Debug, Clone, Copy, PartialEq, Eq)]
200#[repr(u16)]
201pub enum HotPathError {
202    /// Event arrived after watermark — dropped.
203    LateEvent = 0x0001,
204    /// State store key not found.
205    StateKeyMissing = 0x0002,
206    /// Downstream backpressure — event buffered.
207    Backpressure = 0x0003,
208    /// Serialization buffer overflow.
209    SerializationOverflow = 0x0004,
210    /// Record batch schema does not match expected.
211    SchemaMismatch = 0x0005,
212    /// Aggregate state corruption detected.
213    AggregateStateCorruption = 0x0006,
214    /// Queue is full — cannot push event.
215    QueueFull = 0x0007,
216    /// Channel is closed/disconnected.
217    ChannelClosed = 0x0008,
218}
219
220impl HotPathError {
221    /// Returns a static error message. Cost: one match. No allocation.
222    #[must_use]
223    pub const fn message(self) -> &'static str {
224        match self {
225            Self::LateEvent => "Event arrived after watermark; dropped",
226            Self::StateKeyMissing => "State key not found in store",
227            Self::Backpressure => "Downstream backpressure; event buffered",
228            Self::SerializationOverflow => "Serialization buffer capacity exceeded",
229            Self::SchemaMismatch => "Record batch schema does not match expected",
230            Self::AggregateStateCorruption => "Aggregate state checksum mismatch detected",
231            Self::QueueFull => "Queue is full; cannot push event",
232            Self::ChannelClosed => "Channel is closed or disconnected",
233        }
234    }
235
236    /// Numeric code for metrics counters. Zero-cost.
237    #[must_use]
238    pub const fn code(self) -> u16 {
239        self as u16
240    }
241
242    /// Returns the `LDB-NNNN` error code string for this hot path error.
243    #[must_use]
244    pub const fn ldb_code(self) -> &'static str {
245        match self {
246            Self::LateEvent => LATE_DATA_REJECTED,
247            Self::StateKeyMissing => STATE_KEY_MISSING,
248            Self::Backpressure => "LDB-8010",
249            Self::SerializationOverflow => SERIALIZATION_FAILED,
250            Self::SchemaMismatch => SCHEMA_MISMATCH,
251            Self::AggregateStateCorruption => STATE_CORRUPTION,
252            Self::QueueFull => "LDB-8011",
253            Self::ChannelClosed => "LDB-8012",
254        }
255    }
256}
257
258impl std::fmt::Display for HotPathError {
259    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260        write!(f, "[{}] {}", self.ldb_code(), self.message())
261    }
262}
263
264impl std::error::Error for HotPathError {}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[test]
271    fn hot_path_error_is_copy_and_small() {
272        let e = HotPathError::LateEvent;
273        let e2 = e; // Copy
274        assert_eq!(e, e2);
275        assert_eq!(std::mem::size_of::<HotPathError>(), 2);
276    }
277
278    #[test]
279    fn hot_path_error_codes_are_nonzero() {
280        let variants = [
281            HotPathError::LateEvent,
282            HotPathError::StateKeyMissing,
283            HotPathError::Backpressure,
284            HotPathError::SerializationOverflow,
285            HotPathError::SchemaMismatch,
286            HotPathError::AggregateStateCorruption,
287            HotPathError::QueueFull,
288            HotPathError::ChannelClosed,
289        ];
290        for v in &variants {
291            assert!(v.code() > 0, "{v:?} has zero code");
292            assert!(!v.message().is_empty(), "{v:?} has empty message");
293            assert!(
294                v.ldb_code().starts_with("LDB-"),
295                "{v:?} has bad ldb_code: {}",
296                v.ldb_code()
297            );
298        }
299    }
300
301    #[test]
302    fn hot_path_error_display() {
303        let e = HotPathError::LateEvent;
304        let s = e.to_string();
305        assert!(s.starts_with("[LDB-"));
306        assert!(s.contains("watermark"));
307    }
308
309    #[test]
310    fn error_codes_are_stable_strings() {
311        assert_eq!(INVALID_CONFIG, "LDB-0001");
312        assert_eq!(SERIALIZATION_FAILED, "LDB-4001");
313        assert_eq!(EXACTLY_ONCE_SOURCE_UNCERTIFIED, "LDB-5037");
314        assert_eq!(CHECKPOINT_FAILED, "LDB-6001");
315        assert_eq!(INTERNAL, "LDB-8001");
316    }
317}
318
319/// Severity level for warnings (schema inference, recovery, etc.).
320#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
321pub enum WarningSeverity {
322    /// Informational — operation succeeded but with caveats.
323    Info,
324    /// Warning — result may be inaccurate or degraded.
325    Warning,
326    /// Error — operation for this item failed; a fallback was used.
327    Error,
328}