Skip to main content

qql_core/
error.rs

1use alloc::borrow::Cow;
2use alloc::boxed::Box;
3use alloc::vec::Vec;
4use core::fmt;
5
6/// Source-code span as UTF-8 byte offsets into the query text.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9pub struct Span {
10    /// Inclusive start byte offset.
11    pub start: usize,
12    /// Exclusive end byte offset.
13    pub end: usize,
14}
15
16impl Span {
17    /// Create a span from explicit byte offsets.
18    pub const fn new(start: usize, end: usize) -> Self {
19        Self { start, end }
20    }
21
22    /// Zero-length span at a single byte position.
23    pub const fn point(position: usize) -> Self {
24        Self::new(position, position)
25    }
26}
27
28/// Broad category of error origin within the QQL pipeline.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30#[cfg_attr(feature = "serde", derive(serde::Serialize))]
31pub enum ErrorKind {
32    /// Lexer-level error (invalid token, unexpected character).
33    Lex,
34    /// Parser-level error (syntax error, unexpected token).
35    Parse,
36    /// Semantic validation error (invalid configuration, type mismatch).
37    Validation,
38    /// Execution-layer error (embedding failure, invariant violation).
39    Execution,
40    /// Transport-layer error (HTTP/gRPC connectivity, timeout).
41    Transport,
42    /// Qdrant backend error (non-success response, malformed response).
43    Backend,
44}
45
46/// A key-value metadata field attached to a [`QqlError`] for structured context.
47///
48/// Use [`QqlError::with_field`] or the convenience builders
49/// ([`QqlError::with_collection`], [`QqlError::with_status`], etc.) to attach
50/// machine-readable context that clients can inspect without parsing the
51/// human-readable message string.
52#[derive(Debug, Clone, PartialEq, Eq)]
53#[cfg_attr(feature = "serde", derive(serde::Serialize))]
54pub struct ErrorField {
55    /// Field name, e.g. `collection` or `status_code`.
56    pub key: Cow<'static, str>,
57    /// Field value as a string.
58    pub value: Cow<'static, str>,
59}
60
61impl ErrorField {
62    /// Build an `ErrorField` from anything convertible into `Cow<'static, str>`.
63    pub fn new(key: impl Into<Cow<'static, str>>, value: impl Into<Cow<'static, str>>) -> Self {
64        Self {
65            key: key.into(),
66            value: value.into(),
67        }
68    }
69}
70
71/// Unified error type for the entire QQL pipeline.
72///
73/// Every error carries:
74/// - a broad [`ErrorKind`] category,
75/// - a machine-readable `code` (e.g. `QQL-EDGE-COLLECTION-NOT-FOUND`),
76/// - a human-readable `message`,
77/// - an optional source-code [`Span`],
78/// - optional structured [`ErrorField`]s for machine-readable context, and
79/// - an optional causal `source` error for chaining.
80#[derive(Debug, Clone, PartialEq, Eq)]
81#[cfg_attr(feature = "serde", derive(serde::Serialize))]
82pub struct QqlError {
83    /// Broad origin category within the pipeline.
84    pub kind: ErrorKind,
85    /// Machine-readable error code, e.g. `QQL-PARSE-SYNTAX`.
86    pub code: Cow<'static, str>,
87    /// Human-readable description of the failure.
88    pub message: Cow<'static, str>,
89    /// Optional source span in the original query text.
90    pub span: Option<Span>,
91    /// Structured key-value metadata providing machine-readable context
92    /// (e.g. `collection`, `status_code`, `field_name`, `url`).
93    pub fields: Vec<ErrorField>,
94    /// Causal error that led to this one (error chaining).
95    #[cfg_attr(feature = "serde", serde(skip))]
96    pub source: Option<Box<QqlError>>,
97}
98
99impl QqlError {
100    /// Build an error with an explicit kind, code, message, and optional span.
101    pub fn new(
102        kind: ErrorKind,
103        code: impl Into<Cow<'static, str>>,
104        message: impl Into<Cow<'static, str>>,
105        span: Option<Span>,
106    ) -> Self {
107        Self {
108            kind,
109            code: code.into(),
110            message: message.into(),
111            span,
112            fields: Vec::new(),
113            source: None,
114        }
115    }
116
117    // ── Named constructors (keep existing API) ──────────────────────
118
119    /// Create an error with `ErrorKind::Lex` and the given source span.
120    pub fn lex(
121        code: impl Into<Cow<'static, str>>,
122        message: impl Into<Cow<'static, str>>,
123        span: Span,
124    ) -> Self {
125        Self::new(ErrorKind::Lex, code, message, Some(span))
126    }
127
128    /// Create an error with `ErrorKind::Parse` and the given source span.
129    pub fn parse(
130        code: impl Into<Cow<'static, str>>,
131        message: impl Into<Cow<'static, str>>,
132        span: Span,
133    ) -> Self {
134        Self::new(ErrorKind::Parse, code, message, Some(span))
135    }
136
137    /// Create an error with `ErrorKind::Validation` and an optional span.
138    pub fn validation(
139        code: impl Into<Cow<'static, str>>,
140        message: impl Into<Cow<'static, str>>,
141        span: Option<Span>,
142    ) -> Self {
143        Self::new(ErrorKind::Validation, code, message, span)
144    }
145
146    /// Create an error with `ErrorKind::Execution` and an optional span.
147    pub fn execution(
148        code: impl Into<Cow<'static, str>>,
149        message: impl Into<Cow<'static, str>>,
150        span: Option<Span>,
151    ) -> Self {
152        Self::new(ErrorKind::Execution, code, message, span)
153    }
154
155    /// Create an error with `ErrorKind::Transport` and an optional span.
156    pub fn transport(
157        code: impl Into<Cow<'static, str>>,
158        message: impl Into<Cow<'static, str>>,
159        span: Option<Span>,
160    ) -> Self {
161        Self::new(ErrorKind::Transport, code, message, span)
162    }
163
164    /// Create an error with `ErrorKind::Backend` and an optional span.
165    pub fn backend(
166        code: impl Into<Cow<'static, str>>,
167        message: impl Into<Cow<'static, str>>,
168        span: Option<Span>,
169    ) -> Self {
170        Self::new(ErrorKind::Backend, code, message, span)
171    }
172
173    // ── Builder API ─────────────────────────────────────────────────
174
175    /// Attach a structured key-value metadata field.
176    ///
177    /// ```
178    /// # use qql_core::error::QqlError;
179    /// let err = QqlError::backend("QQL-BACKEND", "unexpected status", None)
180    ///     .with_field("status_code", "404")
181    ///     .with_field("collection", "my_collection");
182    /// assert_eq!(err.field("status_code"), Some("404"));
183    /// assert_eq!(err.field("collection"), Some("my_collection"));
184    /// ```
185    pub fn with_field(
186        mut self,
187        key: impl Into<Cow<'static, str>>,
188        value: impl Into<Cow<'static, str>>,
189    ) -> Self {
190        self.fields.push(ErrorField::new(key, value));
191        self
192    }
193
194    /// Shorthand for `.with_field("collection", name)`.
195    pub fn with_collection(self, name: impl Into<Cow<'static, str>>) -> Self {
196        self.with_field("collection", name)
197    }
198
199    /// Shorthand for `.with_field("status_code", code)`.
200    pub fn with_status(self, code: u16) -> Self {
201        self.with_field("status_code", alloc::format!("{code}"))
202    }
203
204    /// Shorthand for `.with_field("url", url)`.
205    pub fn with_url(self, url: impl Into<Cow<'static, str>>) -> Self {
206        self.with_field("url", url)
207    }
208
209    /// Shorthand for `.with_field("field_name", name)`.
210    pub fn with_field_name(self, name: impl Into<Cow<'static, str>>) -> Self {
211        self.with_field("field_name", name)
212    }
213
214    /// Shorthand for `.with_field("index_name", name)`.
215    pub fn with_index_name(self, name: impl Into<Cow<'static, str>>) -> Self {
216        self.with_field("index_name", name)
217    }
218
219    /// Shorthand for `.with_field("vector_name", name)`.
220    pub fn with_vector_name(self, name: impl Into<Cow<'static, str>>) -> Self {
221        self.with_field("vector_name", name)
222    }
223
224    /// Shorthand for `.with_field("model", name)`.
225    pub fn with_model(self, name: impl Into<Cow<'static, str>>) -> Self {
226        self.with_field("model", name)
227    }
228
229    /// Attach an optional source-code span.
230    pub fn with_span(mut self, span: Span) -> Self {
231        self.span = Some(span);
232        self
233    }
234
235    /// Chain a causal error.
236    ///
237    /// The `source` error will be displayed when the outer error is printed
238    /// and is accessible via [`std::error::Error::source`].
239    pub fn caused_by(mut self, source: QqlError) -> Self {
240        self.source = Some(Box::new(source));
241        self
242    }
243
244    /// Look up the first value for a given metadata key, case-insensitive.
245    pub fn field(&self, key: &str) -> Option<&str> {
246        self.fields
247            .iter()
248            .find(|f| f.key.eq_ignore_ascii_case(key))
249            .map(|f| f.value.as_ref())
250    }
251}
252
253/// Backend failure class shared by the CLI doctor, the WASM transport, and the
254/// migrator's retry policy — one table instead of per-surface substring
255/// heuristics.
256#[derive(Debug, Clone, Copy, PartialEq, Eq)]
257pub enum BackendClass {
258    /// Connection refusal, DNS failure, or timeout.
259    Unreachable,
260    /// Authentication / authorization failure.
261    Auth,
262    /// The target collection does not exist.
263    CollectionNotFound,
264    /// A search index is missing or not ready yet.
265    IndexNotReady,
266    /// Vector dimension mismatch.
267    DimensionMismatch,
268    /// Any other backend or HTTP failure.
269    Http,
270}
271
272impl BackendClass {
273    /// Classify an HTTP status plus response body/message.
274    pub fn from_http(status: u16, message: &str) -> Self {
275        let lower = message.to_ascii_lowercase();
276        if status == 401
277            || status == 403
278            || lower.contains("unauthorized")
279            || lower.contains("forbidden")
280            || lower.contains("api key")
281            || lower.contains("bearer")
282        {
283            Self::Auth
284        } else if status == 404 || lower.contains("not found") {
285            Self::CollectionNotFound
286        } else if (lower.contains("index")
287            && (lower.contains("not exist")
288                || lower.contains("appropriate")
289                || lower.contains("not ready")
290                || lower.contains("missing")
291                || lower.contains("indexing")
292                || lower.contains("failed")))
293            || lower.contains("no appropriate index")
294        {
295            Self::IndexNotReady
296        } else if lower.contains("dimension")
297            || lower.contains("vector size")
298            || lower.contains("dimensions")
299        {
300            Self::DimensionMismatch
301        } else {
302            Self::Http
303        }
304    }
305
306    /// Classify from an already-coded error (CLI doctor output).
307    pub fn from_code(code: &str, message: &str) -> Self {
308        if code == "QQL-TRANSPORT"
309            || (code == "QQL-BACKEND-JSON" && message.contains("request id"))
310            || message.contains("connection refused")
311            || message.contains("Connection refused")
312            || message.contains("dns error")
313            || message.contains("failed to lookup address")
314        {
315            Self::Unreachable
316        } else if code == "QQL-BACKEND-AUTH" {
317            Self::Auth
318        } else {
319            Self::Http
320        }
321    }
322
323    /// Machine-readable `QQL-BACKEND-*` code for this class.
324    pub fn code(self) -> &'static str {
325        match self {
326            Self::Unreachable => "QQL-TRANSPORT",
327            Self::Auth => "QQL-BACKEND-AUTH",
328            Self::CollectionNotFound => "QQL-BACKEND-COLLECTION-NOT-FOUND",
329            Self::IndexNotReady => "QQL-BACKEND-INDEX-NOT-READY",
330            Self::DimensionMismatch => "QQL-BACKEND-DIMENSION-MISMATCH",
331            Self::Http => "QQL-BACKEND-HTTP",
332        }
333    }
334}
335
336/// HTTP statuses a retry can plausibly fix (rate limits, transient 5xx).
337pub fn is_retryable_status(status: u16) -> bool {
338    matches!(status, 408 | 425 | 429 | 500 | 502 | 503 | 504)
339}
340
341/// Whether a typed error is worth retrying: transport failures or a
342/// retryable HTTP status recorded on the error.
343pub fn is_retryable(err: &QqlError) -> bool {
344    err.kind == ErrorKind::Transport
345        || err
346            .field("status_code")
347            .and_then(|s| s.parse::<u16>().ok())
348            .is_some_and(is_retryable_status)
349}
350
351/// Message-level retry fallback for errors that did not survive as
352/// [`QqlError`] (e.g. executor report messages).
353pub fn is_retryable_message(message: &str) -> bool {
354    let lower = message.to_ascii_lowercase();
355    lower.contains("429")
356        || lower.contains("too many requests")
357        || lower.contains("service unavailable")
358        || lower.contains("timed out")
359        || lower.contains("timeout")
360        || lower.contains("connection reset")
361        || lower.contains("connection refused")
362        || lower.contains("temporarily unavailable")
363}
364
365impl fmt::Display for QqlError {
366    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367        write!(f, "[{}] {}", self.code, self.message)?;
368        if let Some(span) = self.span {
369            write!(f, " at {}..{}", span.start, span.end)?;
370        }
371        // Print structured fields when not empty
372        if !self.fields.is_empty() {
373            write!(f, " {{")?;
374            for (i, field) in self.fields.iter().enumerate() {
375                if i > 0 {
376                    write!(f, ", ")?;
377                }
378                write!(f, "{}: {}", field.key, field.value)?;
379            }
380            write!(f, "}}")?;
381        }
382        // Print causal chain
383        if let Some(ref source) = self.source {
384            write!(f, "\n  caused by: {source}")?;
385        }
386        Ok(())
387    }
388}
389
390impl core::error::Error for QqlError {
391    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
392        self.source
393            .as_ref()
394            .map(|s| s.as_ref() as &(dyn core::error::Error + 'static))
395    }
396}
397
398#[cfg(test)]
399mod tests {
400    use super::*;
401
402    #[test]
403    fn test_core_error_impl() {
404        let err = QqlError::parse("QQL-PARSE-SYNTAX", "unexpected token", Span::point(0));
405        let dyn_err: &dyn core::error::Error = &err;
406        assert!(dyn_err.source().is_none());
407        assert!(!dyn_err.to_string().is_empty());
408    }
409
410    #[test]
411    fn backend_class_from_http_covers_every_code() {
412        assert_eq!(BackendClass::from_http(401, "").code(), "QQL-BACKEND-AUTH");
413        assert_eq!(BackendClass::from_http(403, "").code(), "QQL-BACKEND-AUTH");
414        assert_eq!(
415            BackendClass::from_http(400, "invalid api key").code(),
416            "QQL-BACKEND-AUTH"
417        );
418        assert_eq!(
419            BackendClass::from_http(404, "").code(),
420            "QQL-BACKEND-COLLECTION-NOT-FOUND"
421        );
422        assert_eq!(
423            BackendClass::from_http(500, "collection 'docs' not found").code(),
424            "QQL-BACKEND-COLLECTION-NOT-FOUND"
425        );
426        assert_eq!(
427            BackendClass::from_http(400, "vector size mismatch: expected 128, got 256").code(),
428            "QQL-BACKEND-DIMENSION-MISMATCH"
429        );
430        assert_eq!(
431            BackendClass::from_http(400, "no appropriate index for field").code(),
432            "QQL-BACKEND-INDEX-NOT-READY"
433        );
434        assert_eq!(
435            BackendClass::from_http(500, "internal server error").code(),
436            "QQL-BACKEND-HTTP"
437        );
438    }
439
440    #[test]
441    fn backend_class_from_code_classifies_transport_and_auth() {
442        assert_eq!(
443            BackendClass::from_code("QQL-TRANSPORT", "connection refused"),
444            BackendClass::Unreachable
445        );
446        assert_eq!(
447            BackendClass::from_code("QQL-BACKEND-AUTH", "forbidden"),
448            BackendClass::Auth
449        );
450        assert_eq!(
451            BackendClass::from_code("QQL-BACKEND-HTTP", "boom"),
452            BackendClass::Http
453        );
454    }
455
456    #[test]
457    fn retry_helpers_cover_transport_and_transient_statuses() {
458        assert!(is_retryable(&QqlError::transport(
459            "QQL-TRANSPORT",
460            "reset",
461            None
462        )));
463        assert!(is_retryable(
464            &QqlError::backend("QQL-BACKEND-HTTP", "too many requests", None).with_status(429)
465        ));
466        assert!(!is_retryable(
467            &QqlError::backend("QQL-BACKEND-AUTH", "forbidden", None).with_status(403)
468        ));
469        assert!(!is_retryable(
470            &QqlError::backend("QQL-BACKEND-COLLECTION-NOT-FOUND", "missing", None)
471                .with_status(404)
472        ));
473        assert!(is_retryable_message("HTTP 503 Service Unavailable"));
474        assert!(!is_retryable_message("vector size mismatch"));
475    }
476}