Skip to main content

vlorql_core/errors/
mod.rs

1//! Structured, machine-readable errors for the VlorQl core.
2//!
3//! Every error keeps both a typed error kind and a JSON `details` payload. The
4//! typed kind is useful to Rust callers, while the payload allows callers to
5//! preserve additional context without parsing an error string.
6
7mod kinds;
8
9use serde::{Deserialize, Serialize};
10use serde_json::{json, Value};
11use thiserror::Error;
12
13pub use kinds::{
14    CompilationErrorKind, ConfigErrorKind, LlmErrorKind, PolicyErrorKind, SchemaErrorKind,
15    ValidationErrorKind,
16};
17
18/// The response shape exposed by API and LLM-facing layers.
19///
20/// # Examples
21///
22/// ```
23/// use vlorql_core::errors::ErrorResponse;
24/// use serde_json::json;
25///
26/// let response = ErrorResponse {
27///     code: "V001".to_owned(),
28///     message: "validation error".to_owned(),
29///     details: json!({"field": "from"}),
30///     suggestion: Some("add a from clause".to_owned()),
31/// };
32/// assert_eq!(response.code, "V001");
33/// ```
34#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
35pub struct ErrorResponse {
36    /// Stable machine-readable error code.
37    pub code: String,
38    /// Human-readable description of the error.
39    pub message: String,
40    /// Structured context associated with the error.
41    pub details: Value,
42    /// Optional guidance that can be used to repair the request.
43    pub suggestion: Option<String>,
44}
45
46/// A structured error from the VlorQl core.
47///
48/// Every variant carries a structured error kind and a JSON `details`
49/// payload so callers can branch on the specific failure without
50/// parsing the error message.
51///
52/// # Examples
53///
54/// ```
55/// use vlorql_core::errors::{VlorQLError, ValidationErrorKind};
56/// use serde_json::json;
57///
58/// let err = VlorQLError::validation(
59///     ValidationErrorKind::InvalidJson,
60///     json!({"response": "not json"}),
61/// );
62/// assert_eq!(err.error_code(), "V001");
63/// assert!(err.is_retryable());
64/// ```
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Error)]
66pub enum VlorQLError {
67    /// The query plan failed structural or semantic validation.
68    #[error("validation error: {kind}")]
69    Validation {
70        /// The typed validation failure.
71        kind: ValidationErrorKind,
72        /// Structured context (table/column names, expected types, …).
73        details: Value,
74    },
75    /// The query plan violates an access-control policy.
76    #[error("policy violation: {kind}")]
77    Policy {
78        /// The typed policy violation.
79        kind: PolicyErrorKind,
80        /// Structured context (table/column names, reason, …).
81        details: Value,
82    },
83    /// The validated plan could not be compiled into SQL.
84    #[error("compilation error: {kind}")]
85    Compilation {
86        /// The typed compilation failure.
87        kind: CompilationErrorKind,
88        /// Structured context (offending feature, placeholder index, …).
89        details: Value,
90    },
91    /// The schema cannot satisfy the query plan.
92    #[error("schema error: {kind}")]
93    Schema {
94        /// The typed schema failure.
95        kind: SchemaErrorKind,
96        /// Structured context (missing table/column, available alternatives, …).
97        details: Value,
98    },
99    /// An LLM provider failed or returned an unusable response.
100    #[error("LLM error: {kind}")]
101    Llm {
102        /// The typed LLM failure.
103        kind: LlmErrorKind,
104        /// Structured context (HTTP status, body fragment, …).
105        details: Value,
106    },
107    /// VlorQl is not configured sufficiently to perform the operation.
108    #[error("configuration error: {kind}")]
109    Config {
110        /// The typed configuration failure.
111        kind: ConfigErrorKind,
112        /// Structured context (missing field, offending value, …).
113        details: Value,
114    },
115}
116
117impl VlorQLError {
118    /// Creates a validation error from any serializable details value.
119    pub fn validation<T: Serialize>(kind: ValidationErrorKind, details: T) -> Self {
120        Self::Validation {
121            kind,
122            details: details_to_value(details),
123        }
124    }
125
126    /// Creates a policy error from any serializable details value.
127    pub fn policy<T: Serialize>(kind: PolicyErrorKind, details: T) -> Self {
128        Self::Policy {
129            kind,
130            details: details_to_value(details),
131        }
132    }
133
134    /// Creates a compilation error from any serializable details value.
135    pub fn compilation<T: Serialize>(kind: CompilationErrorKind, details: T) -> Self {
136        Self::Compilation {
137            kind,
138            details: details_to_value(details),
139        }
140    }
141
142    /// Creates a schema error from any serializable details value.
143    pub fn schema<T: Serialize>(kind: SchemaErrorKind, details: T) -> Self {
144        Self::Schema {
145            kind,
146            details: details_to_value(details),
147        }
148    }
149
150    /// Creates an LLM error from any serializable details value.
151    pub fn llm<T: Serialize>(kind: LlmErrorKind, details: T) -> Self {
152        Self::Llm {
153            kind,
154            details: details_to_value(details),
155        }
156    }
157
158    /// Creates a configuration error from any serializable details value.
159    pub fn config<T: Serialize>(kind: ConfigErrorKind, details: T) -> Self {
160        Self::Config {
161            kind,
162            details: details_to_value(details),
163        }
164    }
165
166    /// Returns a stable code for this error category and kind.
167    pub fn error_code(&self) -> &'static str {
168        match self {
169            Self::Validation { kind, .. } => match kind {
170                ValidationErrorKind::InvalidJson => "V001",
171                ValidationErrorKind::MissingField { .. } => "V002",
172                ValidationErrorKind::InvalidTable { .. } => "V003",
173                ValidationErrorKind::InvalidColumn { .. } => "V004",
174                ValidationErrorKind::InvalidFunction { .. } => "V005",
175                ValidationErrorKind::TypeMismatch { .. } => "V006",
176                ValidationErrorKind::DialectFeatureDisabled { .. } => "V007",
177                ValidationErrorKind::TooManyJoins { .. } => "V008",
178                ValidationErrorKind::AggregationMismatch { .. } => "V009",
179                ValidationErrorKind::MultipleErrors { .. } => "V010",
180            },
181            Self::Policy { kind, .. } => match kind {
182                PolicyErrorKind::TableDenied { .. } => "P001",
183                PolicyErrorKind::ColumnDenied { .. } => "P002",
184            },
185            Self::Compilation { kind, .. } => match kind {
186                CompilationErrorKind::UnsupportedDialectFeature { .. } => "C001",
187                CompilationErrorKind::InvalidPlaceholder { .. } => "C002",
188            },
189            Self::Schema { kind, .. } => match kind {
190                SchemaErrorKind::TableNotFound { .. } => "S001",
191                SchemaErrorKind::ColumnNotFound { .. } => "S002",
192            },
193            Self::Llm { kind, .. } => match kind {
194                LlmErrorKind::ApiError { .. } => "L001",
195                LlmErrorKind::Timeout => "L002",
196                LlmErrorKind::ParseError { .. } => "L003",
197            },
198            Self::Config { kind, .. } => match kind {
199                ConfigErrorKind::MissingLlmClient => "G001",
200                ConfigErrorKind::MissingSchema => "G002",
201                ConfigErrorKind::InvalidDialect { .. } => "G003",
202                ConfigErrorKind::MissingApiKey { .. } => "G004",
203                ConfigErrorKind::EmptyModel => "G005",
204                ConfigErrorKind::ConfigFileError { .. } => "G006",
205            },
206        }
207    }
208
209    /// Converts this error into a machine-readable response with repair guidance.
210    pub fn to_error_response(&self) -> ErrorResponse {
211        // Record the error in the current span context so it can be
212        // correlated with the request's trace_id in the tracing backend.
213        tracing::error!(
214            error.code = %self.error_code(),
215            error.message = %self,
216            "Error response generated for {}",
217            self.error_code(),
218        );
219        ErrorResponse {
220            code: self.error_code().to_owned(),
221            message: self.to_string(),
222            details: self.details().clone(),
223            suggestion: self.suggestion(),
224        }
225    }
226
227    /// Returns whether asking the LLM to produce a corrected request can help.
228    pub fn is_retryable(&self) -> bool {
229        match self {
230            Self::Validation { kind, .. } => matches!(
231                kind,
232                ValidationErrorKind::InvalidJson
233                    | ValidationErrorKind::MissingField { .. }
234                    | ValidationErrorKind::InvalidTable { .. }
235                    | ValidationErrorKind::InvalidColumn { .. }
236                    | ValidationErrorKind::InvalidFunction { .. }
237                    | ValidationErrorKind::TypeMismatch { .. }
238            ),
239            Self::Llm { .. } => true,
240            _ => false,
241        }
242    }
243
244    /// Returns the structured details payload.
245    pub fn details(&self) -> &Value {
246        match self {
247            Self::Validation { details, .. }
248            | Self::Policy { details, .. }
249            | Self::Compilation { details, .. }
250            | Self::Schema { details, .. }
251            | Self::Llm { details, .. }
252            | Self::Config { details, .. } => details,
253        }
254    }
255
256    /// Returns the typed error category without exposing the JSON details.
257    pub fn kind_name(&self) -> &'static str {
258        match self {
259            Self::Validation { .. } => "validation",
260            Self::Policy { .. } => "policy",
261            Self::Compilation { .. } => "compilation",
262            Self::Schema { .. } => "schema",
263            Self::Llm { .. } => "llm",
264            Self::Config { .. } => "config",
265        }
266    }
267
268    fn suggestion(&self) -> Option<String> {
269        match self {
270            Self::Validation { kind, .. } => match kind {
271                ValidationErrorKind::InvalidJson => {
272                    Some("Return a JSON object matching the query plan schema.".to_owned())
273                }
274                ValidationErrorKind::MissingField { field } => {
275                    Some(format!("Add the required field `{field}` to the query plan."))
276                }
277                ValidationErrorKind::InvalidTable {
278                    table,
279                    available_tables,
280                } => available_values_suggestion(
281                    format!("Replace table `{table}` with an available table"),
282                    available_tables,
283                ),
284                ValidationErrorKind::InvalidColumn {
285                    table,
286                    column,
287                    available_columns,
288                } => available_values_suggestion(
289                    format!("Replace column `{table}.{column}` with an available column"),
290                    available_columns,
291                ),
292                ValidationErrorKind::InvalidFunction {
293                    function,
294                    allowed_functions,
295                } => available_values_suggestion(
296                    format!("Replace function `{function}` with an allowed function"),
297                    allowed_functions,
298                ),
299                ValidationErrorKind::TypeMismatch {
300                    expected,
301                    found,
302                    expr,
303                } => Some(format!(
304                    "Change `{expr}` from type `{found}` to the expected type `{expected}`."
305                )),
306                ValidationErrorKind::DialectFeatureDisabled { feature } => Some(format!(
307                    "Remove `{feature}` or select a dialect profile that enables it."
308                )),
309                ValidationErrorKind::TooManyJoins { actual, max } => Some(format!(
310                    "Reduce the query from {actual} joins to at most {max} joins."
311                )),
312                ValidationErrorKind::AggregationMismatch { message } => Some(format!(
313                    "Adjust the selected and grouped expressions to satisfy aggregation rules: {message}"
314                )),
315                ValidationErrorKind::MultipleErrors { .. } => Some(
316                    "Fix each listed validation error and resubmit.".to_owned(),
317                ),
318            },
319            Self::Policy { .. } => {
320                Some("Request the required access or remove the unauthorized resource.".to_owned())
321            }
322            Self::Compilation { .. } => {
323                Some("Use only features supported by the selected SQL dialect compiler.".to_owned())
324            }
325            Self::Schema { .. } => {
326                Some("Refresh the schema snapshot and reference an existing table or column.".to_owned())
327            }
328            Self::Llm { kind, .. } => match kind {
329                LlmErrorKind::ApiError { status, .. } if *status == 401 || *status == 403 => {
330                    Some("Check the LLM provider credentials and permissions.".to_owned())
331                }
332                LlmErrorKind::ApiError { .. } => {
333                    Some("Retry the LLM request with backoff, then inspect the provider status.".to_owned())
334                }
335                LlmErrorKind::Timeout => {
336                    Some("Retry the LLM request or increase the request timeout.".to_owned())
337                }
338                LlmErrorKind::ParseError { .. } => {
339                    Some("Return only a JSON query plan matching the requested schema.".to_owned())
340                }
341            },
342            Self::Config { .. } => None,
343        }
344    }
345}
346
347/// A convenient constructor namespace for validation errors.
348#[derive(Debug, Clone, Copy, Default)]
349pub struct ValidationError;
350
351impl ValidationError {
352    /// Builds a [`VlorQLError::Validation`] value.
353    pub fn error<T: Serialize>(kind: ValidationErrorKind, details: T) -> VlorQLError {
354        VlorQLError::validation(kind, details)
355    }
356}
357
358/// A convenient constructor namespace for policy errors.
359#[derive(Debug, Clone, Copy, Default)]
360pub struct PolicyError;
361
362/// A convenient constructor namespace for compilation errors.
363#[derive(Debug, Clone, Copy, Default)]
364pub struct CompilationError;
365
366/// A convenient constructor namespace for schema errors.
367#[derive(Debug, Clone, Copy, Default)]
368pub struct SchemaError;
369
370/// A convenient constructor namespace for LLM errors.
371#[derive(Debug, Clone, Copy, Default)]
372pub struct LlmError;
373
374/// A convenient constructor namespace for configuration errors.
375#[derive(Debug, Clone, Copy, Default)]
376pub struct ConfigError;
377
378/// A collection of validation errors returned after validating a whole request.
379///
380/// Use [`ValidationErrors::validate`] to convert an iterator of
381/// [`VlorQLError`] into `Result<(), Self>`. The vector can be
382/// inspected via [`ValidationErrors::as_slice`].
383///
384/// # Examples
385///
386/// ```
387/// use vlorql_core::errors::{VlorQLError, ValidationErrorKind, ValidationErrors};
388/// use serde_json::json;
389///
390/// let errors = ValidationErrors::new(vec![
391///     VlorQLError::validation(
392///         ValidationErrorKind::InvalidJson,
393///         json!({"response": "bad"}),
394///     ),
395/// ]);
396/// assert_eq!(errors.len(), 1);
397/// assert!(!errors.is_empty());
398/// ```
399#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
400pub struct ValidationErrors(
401    /// The individual errors collected by the validation pipeline.
402    pub Vec<VlorQLError>,
403);
404
405impl std::fmt::Display for ValidationErrors {
406    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407        match self.0.len() {
408            0 => formatter.write_str("no validation errors"),
409            1 => {
410                let error = &self.0[0];
411                write!(
412                    formatter,
413                    "{} validation error: {}",
414                    error.error_code(),
415                    error
416                )
417            }
418            count => {
419                writeln!(
420                    formatter,
421                    "{count} validation errors occurred (codes: {}):",
422                    self.0
423                        .iter()
424                        .map(VlorQLError::error_code)
425                        .collect::<Vec<_>>()
426                        .join(", ")
427                )?;
428                for (index, error) in self.0.iter().enumerate() {
429                    writeln!(formatter, "  [{index}] {}: {error}", error.error_code())?;
430                }
431                Ok(())
432            }
433        }
434    }
435}
436
437impl std::error::Error for ValidationErrors {
438    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
439        None
440    }
441}
442
443impl ValidationErrors {
444    /// Creates an error collection from an iterator.
445    pub fn new<I>(errors: I) -> Self
446    where
447        I: IntoIterator<Item = VlorQLError>,
448    {
449        Self(errors.into_iter().collect())
450    }
451
452    /// Validates a collection of errors, returning `Ok(())` when there are none.
453    pub fn validate<I>(errors: I) -> Result<(), Self>
454    where
455        I: IntoIterator<Item = VlorQLError>,
456    {
457        let errors = Self::new(errors);
458        if errors.0.is_empty() {
459            Ok(())
460        } else {
461            Err(errors)
462        }
463    }
464
465    /// Returns the number of collected errors.
466    pub fn len(&self) -> usize {
467        self.0.len()
468    }
469
470    /// Returns whether no validation errors were collected.
471    pub fn is_empty(&self) -> bool {
472        self.0.is_empty()
473    }
474
475    /// Returns the collected errors as a slice.
476    pub fn as_slice(&self) -> &[VlorQLError] {
477        &self.0
478    }
479
480    /// Consumes the collection and returns its errors.
481    pub fn into_inner(self) -> Vec<VlorQLError> {
482        self.0
483    }
484}
485
486impl From<Vec<VlorQLError>> for ValidationErrors {
487    fn from(errors: Vec<VlorQLError>) -> Self {
488        Self(errors)
489    }
490}
491
492/// Returns `Ok(())` when the iterator contains no errors, or aggregates all errors.
493pub fn validate<I>(errors: I) -> Result<(), ValidationErrors>
494where
495    I: IntoIterator<Item = VlorQLError>,
496{
497    ValidationErrors::validate(errors)
498}
499
500fn details_to_value<T: Serialize>(details: T) -> Value {
501    serde_json::to_value(details).unwrap_or_else(|error| {
502        json!({
503            "serialization_error": error.to_string(),
504        })
505    })
506}
507
508fn available_values_suggestion(prefix: String, values: &[String]) -> Option<String> {
509    if values.is_empty() {
510        Some(format!("{prefix}; no alternatives are available."))
511    } else {
512        Some(format!("{prefix}: {}.", values.join(", ")))
513    }
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519    use serde_json::json;
520    use std::error::Error;
521
522    #[test]
523    fn validation_error_serializes_with_context() {
524        let error = VlorQLError::validation(
525            ValidationErrorKind::InvalidColumn {
526                table: "users".to_owned(),
527                column: "emali".to_owned(),
528                available_columns: vec!["email".to_owned(), "id".to_owned()],
529            },
530            json!({"path": ["select", 0]}),
531        );
532
533        let serialized = serde_json::to_value(&error).expect("error should serialize");
534        assert_eq!(
535            serialized["Validation"]["kind"]["invalid_column"]["table"],
536            "users"
537        );
538        assert_eq!(serialized["Validation"]["details"]["path"][0], "select");
539    }
540
541    #[test]
542    fn error_code_and_response_include_repair_guidance() {
543        let error = VlorQLError::validation(
544            ValidationErrorKind::InvalidTable {
545                table: "usrers".to_owned(),
546                available_tables: vec!["users".to_owned()],
547            },
548            json!({"source": "llm"}),
549        );
550
551        let response = error.to_error_response();
552        assert_eq!(error.error_code(), "V003");
553        assert_eq!(response.code, "V003");
554        assert!(response.message.contains("usrers"));
555        assert_eq!(response.details["source"], "llm");
556        assert!(response
557            .suggestion
558            .as_deref()
559            .is_some_and(|suggestion| suggestion.contains("users")));
560    }
561
562    #[test]
563    fn all_error_categories_have_unique_codes() {
564        let errors = [
565            VlorQLError::validation(ValidationErrorKind::InvalidJson, json!({})),
566            VlorQLError::policy(
567                PolicyErrorKind::TableDenied {
568                    table: "secrets".to_owned(),
569                },
570                json!({}),
571            ),
572            VlorQLError::compilation(
573                CompilationErrorKind::InvalidPlaceholder { index: 0 },
574                json!({}),
575            ),
576            VlorQLError::schema(
577                SchemaErrorKind::TableNotFound {
578                    table: "users".to_owned(),
579                },
580                json!({}),
581            ),
582            VlorQLError::llm(LlmErrorKind::Timeout, json!({})),
583            VlorQLError::config(ConfigErrorKind::MissingSchema, json!({})),
584        ];
585        let codes: std::collections::HashSet<_> =
586            errors.iter().map(VlorQLError::error_code).collect();
587        assert_eq!(codes.len(), errors.len());
588    }
589
590    #[test]
591    fn retryability_distinguishes_recoverable_and_configuration_errors() {
592        let validation = VlorQLError::validation(
593            ValidationErrorKind::MissingField {
594                field: "from".to_owned(),
595            },
596            json!({}),
597        );
598        let llm = VlorQLError::llm(
599            LlmErrorKind::ParseError {
600                details: "bad JSON".to_owned(),
601            },
602            json!({}),
603        );
604        let policy = VlorQLError::policy(
605            PolicyErrorKind::ColumnDenied {
606                table: "users".to_owned(),
607                column: "password_hash".to_owned(),
608            },
609            json!({}),
610        );
611        let config = VlorQLError::config(
612            ConfigErrorKind::InvalidDialect {
613                dialect: "unknown".to_owned(),
614            },
615            json!({}),
616        );
617
618        assert!(validation.is_retryable());
619        assert!(llm.is_retryable());
620        assert!(!policy.is_retryable());
621        assert!(!config.is_retryable());
622    }
623
624    #[test]
625    fn validation_errors_aggregate_and_implement_error() {
626        let errors = vec![
627            VlorQLError::validation(ValidationErrorKind::InvalidJson, json!({})),
628            VlorQLError::validation(
629                ValidationErrorKind::MissingField {
630                    field: "select".to_owned(),
631                },
632                json!({}),
633            ),
634        ];
635        let aggregated = ValidationErrors::from(errors);
636
637        assert_eq!(aggregated.len(), 2);
638        assert!(!aggregated.is_empty());
639        let rendered = aggregated.to_string();
640        assert!(rendered.contains("2 validation errors occurred"));
641        assert!(rendered.contains("V001"));
642        assert!(rendered.contains("V002"));
643        assert!(rendered.contains("[0]"));
644        assert!(rendered.contains("[1]"));
645        assert!(rendered.contains("the LLM response is not valid JSON"));
646        assert!(rendered.contains("required field `select` is missing"));
647        assert!(aggregated.source().is_none());
648        assert!(ValidationErrors::validate(Vec::<VlorQLError>::new()).is_ok());
649        assert!(ValidationErrors::validate(aggregated.as_slice().iter().cloned()).is_err());
650    }
651
652    // -----------------------------------------------------------------
653    // Exhaustive coverage of every error kind, asserting that
654    // (a) construction works, (b) error_code() returns the expected
655    // string, and (c) to_error_response() exposes the right fields.
656    // -----------------------------------------------------------------
657
658    fn assert_code_and_suggestion(
659        error: &VlorQLError,
660        expected_code: &str,
661        expected_suggestion: Option<&str>,
662    ) {
663        assert_eq!(error.error_code(), expected_code, "code for {error:?}");
664        let response = error.to_error_response();
665        assert_eq!(response.code, expected_code, "response code for {error:?}");
666        assert!(!response.message.is_empty(), "message for {error:?}");
667        match expected_suggestion {
668            Some(suggestion) => assert_eq!(
669                response.suggestion.as_deref(),
670                Some(suggestion),
671                "suggestion for {error:?}"
672            ),
673            None => assert!(
674                response.suggestion.is_none(),
675                "expected no suggestion for {error:?}, got {:?}",
676                response.suggestion
677            ),
678        }
679        // The details payload must round-trip through serde.
680        serde_json::to_value(&response).expect("response should serialize");
681    }
682
683    #[test]
684    fn every_validation_error_kind_has_a_distinct_code_and_useful_suggestion() {
685        assert_code_and_suggestion(
686            &VlorQLError::validation(ValidationErrorKind::InvalidJson, json!({})),
687            "V001",
688            Some("Return a JSON object matching the query plan schema."),
689        );
690        assert_code_and_suggestion(
691            &VlorQLError::validation(
692                ValidationErrorKind::MissingField {
693                    field: "from".to_owned(),
694                },
695                json!({}),
696            ),
697            "V002",
698            Some("Add the required field `from` to the query plan."),
699        );
700        assert_code_and_suggestion(
701            &VlorQLError::validation(
702                ValidationErrorKind::InvalidColumn {
703                    table: "users".to_owned(),
704                    column: "emali".to_owned(),
705                    available_columns: vec!["email".to_owned(), "id".to_owned()],
706                },
707                json!({}),
708            ),
709            "V004",
710            Some("Replace column `users.emali` with an available column: email, id."),
711        );
712        assert_code_and_suggestion(
713            &VlorQLError::validation(
714                ValidationErrorKind::InvalidFunction {
715                    function: "load_extension".to_owned(),
716                    allowed_functions: vec!["count".to_owned()],
717                },
718                json!({}),
719            ),
720            "V005",
721            Some("Replace function `load_extension` with an allowed function: count."),
722        );
723        assert_code_and_suggestion(
724            &VlorQLError::validation(
725                ValidationErrorKind::TypeMismatch {
726                    expected: "int".to_owned(),
727                    found: "string".to_owned(),
728                    expr: "users.id".to_owned(),
729                },
730                json!({}),
731            ),
732            "V006",
733            Some("Change `users.id` from type `string` to the expected type `int`."),
734        );
735        assert_code_and_suggestion(
736            &VlorQLError::validation(
737                ValidationErrorKind::DialectFeatureDisabled {
738                    feature: "cte".to_owned(),
739                },
740                json!({}),
741            ),
742            "V007",
743            Some("Remove `cte` or select a dialect profile that enables it."),
744        );
745        assert_code_and_suggestion(
746            &VlorQLError::validation(
747                ValidationErrorKind::TooManyJoins { actual: 5, max: 2 },
748                json!({}),
749            ),
750            "V008",
751            Some("Reduce the query from 5 joins to at most 2 joins."),
752        );
753        assert_code_and_suggestion(
754            &VlorQLError::validation(
755                ValidationErrorKind::AggregationMismatch {
756                    message: "mixed aggregation".to_owned(),
757                },
758                json!({}),
759            ),
760            "V009",
761            Some(
762                "Adjust the selected and grouped expressions to satisfy aggregation rules: \
763                 mixed aggregation",
764            ),
765        );
766
767        // `InvalidTable` with no available alternatives gets a slightly
768        // different suggestion.
769        let isolated = VlorQLError::validation(
770            ValidationErrorKind::InvalidTable {
771                table: "missing".to_owned(),
772                available_tables: vec![],
773            },
774            json!({}),
775        );
776        let response = isolated.to_error_response();
777        assert_eq!(response.code, "V003");
778        assert!(
779            response
780                .suggestion
781                .as_deref()
782                .is_some_and(|s| s.contains("no alternatives")),
783            "got {:?}",
784            response.suggestion
785        );
786    }
787
788    #[test]
789    fn every_policy_error_kind_has_a_distinct_code() {
790        let shared_suggestion = "Request the required access or remove the unauthorized resource.";
791        let table = VlorQLError::policy(
792            PolicyErrorKind::TableDenied {
793                table: "secrets".to_owned(),
794            },
795            json!({}),
796        );
797        assert_code_and_suggestion(&table, "P001", Some(shared_suggestion));
798
799        let column = VlorQLError::policy(
800            PolicyErrorKind::ColumnDenied {
801                table: "users".to_owned(),
802                column: "password_hash".to_owned(),
803            },
804            json!({}),
805        );
806        assert_code_and_suggestion(&column, "P002", Some(shared_suggestion));
807    }
808
809    #[test]
810    fn policy_errors_share_a_default_suggestion() {
811        let policy = VlorQLError::policy(
812            PolicyErrorKind::ColumnDenied {
813                table: "users".to_owned(),
814                column: "secret".to_owned(),
815            },
816            json!({}),
817        );
818        let response = policy.to_error_response();
819        assert_eq!(response.code, "P002");
820        assert_eq!(
821            response.suggestion.as_deref(),
822            Some("Request the required access or remove the unauthorized resource.")
823        );
824    }
825
826    #[test]
827    fn every_compilation_error_kind_has_a_distinct_code() {
828        let shared_suggestion = "Use only features supported by the selected SQL dialect compiler.";
829        let unsupported = VlorQLError::compilation(
830            CompilationErrorKind::UnsupportedDialectFeature {
831                feature: "FETCH".to_owned(),
832            },
833            json!({}),
834        );
835        assert_code_and_suggestion(&unsupported, "C001", Some(shared_suggestion));
836
837        let placeholder = VlorQLError::compilation(
838            CompilationErrorKind::InvalidPlaceholder { index: 7 },
839            json!({}),
840        );
841        assert_code_and_suggestion(&placeholder, "C002", Some(shared_suggestion));
842    }
843
844    #[test]
845    fn every_schema_error_kind_has_a_distinct_code() {
846        let shared_suggestion =
847            "Refresh the schema snapshot and reference an existing table or column.";
848        let missing_table = VlorQLError::schema(
849            SchemaErrorKind::TableNotFound {
850                table: "ghost".to_owned(),
851            },
852            json!({}),
853        );
854        assert_code_and_suggestion(&missing_table, "S001", Some(shared_suggestion));
855
856        let missing_column = VlorQLError::schema(
857            SchemaErrorKind::ColumnNotFound {
858                table: "users".to_owned(),
859                column: "secret".to_owned(),
860            },
861            json!({}),
862        );
863        assert_code_and_suggestion(&missing_column, "S002", Some(shared_suggestion));
864    }
865
866    #[test]
867    fn every_llm_error_kind_has_a_distinct_code_and_suggestion() {
868        let transient = VlorQLError::llm(
869            LlmErrorKind::ApiError {
870                status: 500,
871                message: "down".to_owned(),
872            },
873            json!({}),
874        );
875        assert_code_and_suggestion(
876            &transient,
877            "L001",
878            Some("Retry the LLM request with backoff, then inspect the provider status."),
879        );
880
881        let timeout = VlorQLError::llm(LlmErrorKind::Timeout, json!({}));
882        assert_code_and_suggestion(
883            &timeout,
884            "L002",
885            Some("Retry the LLM request or increase the request timeout."),
886        );
887
888        let parse = VlorQLError::llm(
889            LlmErrorKind::ParseError {
890                details: "bad JSON".to_owned(),
891            },
892            json!({}),
893        );
894        assert_code_and_suggestion(
895            &parse,
896            "L003",
897            Some("Return only a JSON query plan matching the requested schema."),
898        );
899    }
900
901    #[test]
902    fn llm_suggestion_distinguishes_auth_failures_from_transient_errors() {
903        let auth = VlorQLError::llm(
904            LlmErrorKind::ApiError {
905                status: 401,
906                message: "unauthorized".to_owned(),
907            },
908            json!({}),
909        );
910        let transient = VlorQLError::llm(
911            LlmErrorKind::ApiError {
912                status: 503,
913                message: "down".to_owned(),
914            },
915            json!({}),
916        );
917        assert_eq!(
918            auth.to_error_response().suggestion.as_deref(),
919            Some("Check the LLM provider credentials and permissions.")
920        );
921        assert_eq!(
922            transient.to_error_response().suggestion.as_deref(),
923            Some("Retry the LLM request with backoff, then inspect the provider status.")
924        );
925    }
926
927    #[test]
928    fn every_config_error_kind_has_a_distinct_code_and_no_suggestion() {
929        let missing_client = VlorQLError::config(ConfigErrorKind::MissingLlmClient, json!({}));
930        assert_code_and_suggestion(&missing_client, "G001", None);
931
932        let missing_schema = VlorQLError::config(ConfigErrorKind::MissingSchema, json!({}));
933        assert_code_and_suggestion(&missing_schema, "G002", None);
934
935        let bad_dialect = VlorQLError::config(
936            ConfigErrorKind::InvalidDialect {
937                dialect: "oracle".to_owned(),
938            },
939            json!({}),
940        );
941        assert_code_and_suggestion(&bad_dialect, "G003", None);
942    }
943
944    #[test]
945    fn only_validation_and_llm_errors_are_retryable() {
946        let cases = [
947            (
948                VlorQLError::validation(ValidationErrorKind::InvalidJson, json!({})),
949                true,
950            ),
951            (
952                VlorQLError::validation(
953                    ValidationErrorKind::TooManyJoins { actual: 3, max: 1 },
954                    json!({}),
955                ),
956                false,
957            ),
958            (VlorQLError::llm(LlmErrorKind::Timeout, json!({})), true),
959            (
960                VlorQLError::llm(
961                    LlmErrorKind::ApiError {
962                        status: 500,
963                        message: "down".to_owned(),
964                    },
965                    json!({}),
966                ),
967                true,
968            ),
969            (
970                VlorQLError::policy(
971                    PolicyErrorKind::TableDenied {
972                        table: "secrets".to_owned(),
973                    },
974                    json!({}),
975                ),
976                false,
977            ),
978            (
979                VlorQLError::policy(
980                    PolicyErrorKind::ColumnDenied {
981                        table: "users".to_owned(),
982                        column: "password_hash".to_owned(),
983                    },
984                    json!({}),
985                ),
986                false,
987            ),
988            (
989                VlorQLError::compilation(
990                    CompilationErrorKind::UnsupportedDialectFeature {
991                        feature: "FETCH".to_owned(),
992                    },
993                    json!({}),
994                ),
995                false,
996            ),
997            (
998                VlorQLError::schema(
999                    SchemaErrorKind::TableNotFound {
1000                        table: "missing".to_owned(),
1001                    },
1002                    json!({}),
1003                ),
1004                false,
1005            ),
1006            (
1007                VlorQLError::config(ConfigErrorKind::MissingSchema, json!({})),
1008                false,
1009            ),
1010        ];
1011        for (error, expected) in cases {
1012            assert_eq!(
1013                error.is_retryable(),
1014                expected,
1015                "retryability for {:?} should be {expected}",
1016                error
1017            );
1018        }
1019    }
1020
1021    #[test]
1022    fn error_response_round_trips_through_serde() {
1023        let error = VlorQLError::validation(
1024            ValidationErrorKind::TypeMismatch {
1025                expected: "int".to_owned(),
1026                found: "string".to_owned(),
1027                expr: "users.id".to_owned(),
1028            },
1029            json!({"path": ["where"]}),
1030        );
1031        let response = error.to_error_response();
1032        let serialized =
1033            serde_json::to_string(&response).expect("response should serialize to JSON");
1034        let restored: ErrorResponse =
1035            serde_json::from_str(&serialized).expect("response should round-trip");
1036        assert_eq!(restored.code, response.code);
1037        assert_eq!(restored.message, response.message);
1038        assert_eq!(restored.suggestion, response.suggestion);
1039        assert_eq!(restored.details, response.details);
1040    }
1041
1042    #[test]
1043    fn kind_name_reports_the_top_level_category() {
1044        let validation = VlorQLError::validation(ValidationErrorKind::InvalidJson, json!({}));
1045        let policy = VlorQLError::policy(
1046            PolicyErrorKind::TableDenied {
1047                table: "x".to_owned(),
1048            },
1049            json!({}),
1050        );
1051        let compilation = VlorQLError::compilation(
1052            CompilationErrorKind::InvalidPlaceholder { index: 1 },
1053            json!({}),
1054        );
1055        let schema = VlorQLError::schema(
1056            SchemaErrorKind::TableNotFound {
1057                table: "x".to_owned(),
1058            },
1059            json!({}),
1060        );
1061        let llm = VlorQLError::llm(LlmErrorKind::Timeout, json!({}));
1062        let config = VlorQLError::config(ConfigErrorKind::MissingSchema, json!({}));
1063        assert_eq!(validation.kind_name(), "validation");
1064        assert_eq!(policy.kind_name(), "policy");
1065        assert_eq!(compilation.kind_name(), "compilation");
1066        assert_eq!(schema.kind_name(), "schema");
1067        assert_eq!(llm.kind_name(), "llm");
1068        assert_eq!(config.kind_name(), "config");
1069    }
1070
1071    #[test]
1072    fn single_validation_error_renders_without_count_header() {
1073        let error = VlorQLError::validation(
1074            ValidationErrorKind::MissingField {
1075                field: "from".to_owned(),
1076            },
1077            json!({}),
1078        );
1079        let aggregated = ValidationErrors::from(vec![error]);
1080        let rendered = aggregated.to_string();
1081        assert!(
1082            rendered.contains("1 validation error:") || rendered.contains("validation error:"),
1083            "rendered: {rendered}"
1084        );
1085        assert!(rendered.contains("V002"), "rendered: {rendered}");
1086        assert!(
1087            rendered.contains("required field `from` is missing"),
1088            "rendered: {rendered}"
1089        );
1090        // Single-error rendering should not contain the multi-error
1091        // "occurred (codes:" line.
1092        assert!(
1093            !rendered.contains("occurred (codes:"),
1094            "rendered: {rendered}"
1095        );
1096    }
1097
1098    #[test]
1099    fn empty_validation_errors_renders_no_errors_message() {
1100        let aggregated = ValidationErrors(Vec::new());
1101        assert_eq!(aggregated.to_string(), "no validation errors");
1102    }
1103
1104    #[test]
1105    fn validation_errors_into_inner_returns_owned_vector() {
1106        let errors = vec![VlorQLError::validation(
1107            ValidationErrorKind::InvalidJson,
1108            json!({}),
1109        )];
1110        let aggregated = ValidationErrors::from(errors);
1111        let inner = aggregated.into_inner();
1112        assert_eq!(inner.len(), 1);
1113    }
1114
1115    #[test]
1116    fn free_function_validate_aggregates_iterator_input() {
1117        let errors = [
1118            VlorQLError::validation(ValidationErrorKind::InvalidJson, json!({})),
1119            VlorQLError::validation(
1120                ValidationErrorKind::MissingField {
1121                    field: "select".to_owned(),
1122                },
1123                json!({}),
1124            ),
1125        ];
1126        let result = crate::errors::validate(errors);
1127        let aggregated = result.expect_err("non-empty iterator should produce ValidationErrors");
1128        assert_eq!(aggregated.len(), 2);
1129    }
1130
1131    #[test]
1132    fn validation_errors_serialize_and_deserialize_through_serde() {
1133        let errors = vec![
1134            VlorQLError::validation(ValidationErrorKind::InvalidJson, json!({})),
1135            VlorQLError::policy(
1136                PolicyErrorKind::TableDenied {
1137                    table: "secrets".to_owned(),
1138                },
1139                json!({}),
1140            ),
1141        ];
1142        let aggregated = ValidationErrors::from(errors);
1143        let serialized = serde_json::to_string(&aggregated).expect("should serialize");
1144        let restored: ValidationErrors =
1145            serde_json::from_str(&serialized).expect("should round-trip");
1146        assert_eq!(restored, aggregated);
1147    }
1148}