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::{Value, json};
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                SchemaErrorKind::TableNotInScope { .. } => "S003",
193            },
194            Self::Llm { kind, .. } => match kind {
195                LlmErrorKind::ApiError { .. } => "L001",
196                LlmErrorKind::Timeout => "L002",
197                LlmErrorKind::ParseError { .. } => "L003",
198            },
199            Self::Config { kind, .. } => match kind {
200                ConfigErrorKind::MissingLlmClient => "G001",
201                ConfigErrorKind::MissingSchema => "G002",
202                ConfigErrorKind::InvalidDialect { .. } => "G003",
203                ConfigErrorKind::MissingApiKey { .. } => "G004",
204                ConfigErrorKind::EmptyModel => "G005",
205                ConfigErrorKind::ConfigFileError { .. } => "G006",
206            },
207        }
208    }
209
210    /// Converts this error into a machine-readable response with repair guidance.
211    pub fn to_error_response(&self) -> ErrorResponse {
212        // Record the error in the current span context so it can be
213        // correlated with the request's trace_id in the tracing backend.
214        tracing::error!(
215            error.code = %self.error_code(),
216            error.message = %self,
217            "Error response generated for {}",
218            self.error_code(),
219        );
220        ErrorResponse {
221            code: self.error_code().to_owned(),
222            message: self.to_string(),
223            details: self.details().clone(),
224            suggestion: self.suggestion(),
225        }
226    }
227
228    /// Returns whether asking the LLM to produce a corrected request can help.
229    pub fn is_retryable(&self) -> bool {
230        match self {
231            Self::Validation { kind, .. } => matches!(
232                kind,
233                ValidationErrorKind::InvalidJson
234                    | ValidationErrorKind::MissingField { .. }
235                    | ValidationErrorKind::InvalidTable { .. }
236                    | ValidationErrorKind::InvalidColumn { .. }
237                    | ValidationErrorKind::InvalidFunction { .. }
238                    | ValidationErrorKind::TypeMismatch { .. }
239                    | ValidationErrorKind::AggregationMismatch { .. }
240            ),
241            Self::Schema { kind, .. } => matches!(
242                kind,
243                SchemaErrorKind::TableNotFound { .. }
244                    | SchemaErrorKind::TableNotInScope { .. }
245                    | SchemaErrorKind::ColumnNotFound { .. }
246            ),
247            Self::Llm { .. } => true,
248            _ => false,
249        }
250    }
251
252    /// Returns the structured details payload.
253    pub fn details(&self) -> &Value {
254        match self {
255            Self::Validation { details, .. }
256            | Self::Policy { details, .. }
257            | Self::Compilation { details, .. }
258            | Self::Schema { details, .. }
259            | Self::Llm { details, .. }
260            | Self::Config { details, .. } => details,
261        }
262    }
263
264    /// Returns the typed error category without exposing the JSON details.
265    pub fn kind_name(&self) -> &'static str {
266        match self {
267            Self::Validation { .. } => "validation",
268            Self::Policy { .. } => "policy",
269            Self::Compilation { .. } => "compilation",
270            Self::Schema { .. } => "schema",
271            Self::Llm { .. } => "llm",
272            Self::Config { .. } => "config",
273        }
274    }
275
276    fn suggestion(&self) -> Option<String> {
277        match self {
278            Self::Validation { kind, .. } => match kind {
279                ValidationErrorKind::InvalidJson => {
280                    Some("Return a JSON object matching the query plan schema.".to_owned())
281                }
282                ValidationErrorKind::MissingField { field } => Some(format!(
283                    "Add the required field `{field}` to the query plan."
284                )),
285                ValidationErrorKind::InvalidTable {
286                    table,
287                    available_tables,
288                } => available_values_suggestion(
289                    format!("Replace table `{table}` with an available table"),
290                    available_tables,
291                ),
292                ValidationErrorKind::InvalidColumn {
293                    table,
294                    column,
295                    available_columns,
296                } => available_values_suggestion(
297                    format!("Replace column `{table}.{column}` with an available column"),
298                    available_columns,
299                ),
300                ValidationErrorKind::InvalidFunction {
301                    function,
302                    allowed_functions,
303                } => available_values_suggestion(
304                    format!("Replace function `{function}` with an allowed function"),
305                    allowed_functions,
306                ),
307                ValidationErrorKind::TypeMismatch {
308                    expected,
309                    found,
310                    expr,
311                } => Some(format!(
312                    "Change `{expr}` from type `{found}` to the expected type `{expected}`."
313                )),
314                ValidationErrorKind::DialectFeatureDisabled { feature } => Some(format!(
315                    "Remove `{feature}` or select a dialect profile that enables it."
316                )),
317                ValidationErrorKind::TooManyJoins { actual, max } => Some(format!(
318                    "Reduce the query from {actual} joins to at most {max} joins."
319                )),
320                ValidationErrorKind::AggregationMismatch { message } => Some(format!(
321                    "Adjust the selected and grouped expressions to satisfy aggregation rules: {message}"
322                )),
323                ValidationErrorKind::MultipleErrors { .. } => {
324                    Some("Fix each listed validation error and resubmit.".to_owned())
325                }
326            },
327            Self::Policy { .. } => {
328                Some("Request the required access or remove the unauthorized resource.".to_owned())
329            }
330            Self::Compilation { .. } => {
331                Some("Use only features supported by the selected SQL dialect compiler.".to_owned())
332            }
333            Self::Schema { kind, .. } => match kind {
334                SchemaErrorKind::TableNotFound { table } => {
335                    let tip = if table == "where" || table == "from" {
336                        "The 'table' field contains a reserved word or structural field name, not an actual table. Use a valid table name from the schema."
337                    } else {
338                        "Add the table as a JOIN (with an ON clause) or as the FROM source. If you reference columns with 'table: \"<name>\"', that table must be in FROM or JOINs."
339                    };
340                    Some(tip.to_owned())
341                }
342                SchemaErrorKind::TableNotInScope { table } => {
343                    let tip = if table == "where" || table == "from" {
344                        "The 'table' field contains a reserved word or structural field name, not an actual table. Use a valid table name from the schema."
345                    } else {
346                        "The table exists in the schema but is not part of the query's FROM or JOIN clauses. Add a JOIN (with an ON clause) for this table."
347                    };
348                    Some(tip.to_owned())
349                }
350                SchemaErrorKind::ColumnNotFound { .. } => Some(
351                    "Use only column names listed in the schema for the referenced table."
352                        .to_owned(),
353                ),
354            },
355            Self::Llm { kind, .. } => match kind {
356                LlmErrorKind::ApiError { status, .. } if *status == 401 || *status == 403 => {
357                    Some("Check the LLM provider credentials and permissions.".to_owned())
358                }
359                LlmErrorKind::ApiError { .. } => Some(
360                    "Retry the LLM request with backoff, then inspect the provider status."
361                        .to_owned(),
362                ),
363                LlmErrorKind::Timeout => {
364                    Some("Retry the LLM request or increase the request timeout.".to_owned())
365                }
366                LlmErrorKind::ParseError { details } => {
367                    let details_lower = details.to_lowercase();
368                    let tip = if details_lower.contains("where")
369                        && (details_lower.contains("array")
370                            || details_lower.contains("sequence")
371                            || details_lower.contains("list")
372                            || details_lower.contains("expected"))
373                    {
374                        "The 'where' field must be a single Predicate object (NOT an array). In 'and'/'or', each of 'left' and 'right' is a single Predicate {...} — never wrap them in [...]."
375                    } else if details_lower.contains("unknown field") {
376                        "Remove any unrecognized fields from the JSON. Only fields defined in the schema are allowed."
377                    } else if details_lower.contains("invalid type")
378                        && details_lower.contains("expected")
379                    {
380                        "A field has the wrong JSON type — e.g., an array where an object was expected, or a string where a number was expected. Check the field types in the schema."
381                    } else if details_lower.contains("expected struct") {
382                        "A field contains a string instead of a JSON object, or a JSON array has an element of the wrong type. Ensure all nested objects use {...} not \"...\"."
383                    } else if details_lower.contains("expected variant")
384                        || details_lower.contains("unknown variant")
385                    {
386                        "The 'type' field has an unrecognized value. Use only valid type tags: 'column_ref', 'literal', 'comparison', 'and', 'or', etc."
387                    } else if details_lower.contains("missing field") {
388                        "A required field is missing. Add the required field to the JSON object."
389                    } else if details_lower.contains("trailing characters")
390                        || details_lower.contains("control character")
391                        || details_lower.contains("escape")
392                        || details_lower.contains("expected")
393                    {
394                        "The response contains invalid JSON syntax. Return ONLY a raw JSON object — no markdown fences (```json), no extra text before or after."
395                    } else {
396                        "Return only a JSON object matching the QueryPlan schema. No markdown fences, no extra text, no comments."
397                    };
398                    Some(tip.to_owned())
399                }
400            },
401            Self::Config { .. } => None,
402        }
403    }
404}
405
406/// A convenient constructor namespace for validation errors.
407#[derive(Debug, Clone, Copy, Default)]
408pub struct ValidationError;
409
410impl ValidationError {
411    /// Builds a [`VlorQLError::Validation`] value.
412    pub fn error<T: Serialize>(kind: ValidationErrorKind, details: T) -> VlorQLError {
413        VlorQLError::validation(kind, details)
414    }
415}
416
417/// A convenient constructor namespace for policy errors.
418#[derive(Debug, Clone, Copy, Default)]
419pub struct PolicyError;
420
421/// A convenient constructor namespace for compilation errors.
422#[derive(Debug, Clone, Copy, Default)]
423pub struct CompilationError;
424
425/// A convenient constructor namespace for schema errors.
426#[derive(Debug, Clone, Copy, Default)]
427pub struct SchemaError;
428
429/// A convenient constructor namespace for LLM errors.
430#[derive(Debug, Clone, Copy, Default)]
431pub struct LlmError;
432
433/// A convenient constructor namespace for configuration errors.
434#[derive(Debug, Clone, Copy, Default)]
435pub struct ConfigError;
436
437/// A collection of validation errors returned after validating a whole request.
438///
439/// Use [`ValidationErrors::validate`] to convert an iterator of
440/// [`VlorQLError`] into `Result<(), Self>`. The vector can be
441/// inspected via [`ValidationErrors::as_slice`].
442///
443/// # Examples
444///
445/// ```
446/// use vlorql_core::errors::{VlorQLError, ValidationErrorKind, ValidationErrors};
447/// use serde_json::json;
448///
449/// let errors = ValidationErrors::new(vec![
450///     VlorQLError::validation(
451///         ValidationErrorKind::InvalidJson,
452///         json!({"response": "bad"}),
453///     ),
454/// ]);
455/// assert_eq!(errors.len(), 1);
456/// assert!(!errors.is_empty());
457/// ```
458#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
459pub struct ValidationErrors(
460    /// The individual errors collected by the validation pipeline.
461    pub Vec<VlorQLError>,
462);
463
464impl std::fmt::Display for ValidationErrors {
465    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
466        match self.0.len() {
467            0 => formatter.write_str("no validation errors"),
468            1 => {
469                let error = &self.0[0];
470                write!(
471                    formatter,
472                    "{} validation error: {}",
473                    error.error_code(),
474                    error
475                )
476            }
477            count => {
478                writeln!(
479                    formatter,
480                    "{count} validation errors occurred (codes: {}):",
481                    self.0
482                        .iter()
483                        .map(VlorQLError::error_code)
484                        .collect::<Vec<_>>()
485                        .join(", ")
486                )?;
487                for (index, error) in self.0.iter().enumerate() {
488                    writeln!(formatter, "  [{index}] {}: {error}", error.error_code())?;
489                }
490                Ok(())
491            }
492        }
493    }
494}
495
496impl std::error::Error for ValidationErrors {
497    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
498        None
499    }
500}
501
502impl ValidationErrors {
503    /// Creates an error collection from an iterator.
504    pub fn new<I>(errors: I) -> Self
505    where
506        I: IntoIterator<Item = VlorQLError>,
507    {
508        Self(errors.into_iter().collect())
509    }
510
511    /// Validates a collection of errors, returning `Ok(())` when there are none.
512    pub fn validate<I>(errors: I) -> Result<(), Self>
513    where
514        I: IntoIterator<Item = VlorQLError>,
515    {
516        let errors = Self::new(errors);
517        if errors.0.is_empty() {
518            Ok(())
519        } else {
520            Err(errors)
521        }
522    }
523
524    /// Returns the number of collected errors.
525    pub fn len(&self) -> usize {
526        self.0.len()
527    }
528
529    /// Returns whether no validation errors were collected.
530    pub fn is_empty(&self) -> bool {
531        self.0.is_empty()
532    }
533
534    /// Returns the collected errors as a slice.
535    pub fn as_slice(&self) -> &[VlorQLError] {
536        &self.0
537    }
538
539    /// Consumes the collection and returns its errors.
540    pub fn into_inner(self) -> Vec<VlorQLError> {
541        self.0
542    }
543}
544
545impl From<Vec<VlorQLError>> for ValidationErrors {
546    fn from(errors: Vec<VlorQLError>) -> Self {
547        Self(errors)
548    }
549}
550
551/// Returns `Ok(())` when the iterator contains no errors, or aggregates all errors.
552pub fn validate<I>(errors: I) -> Result<(), ValidationErrors>
553where
554    I: IntoIterator<Item = VlorQLError>,
555{
556    ValidationErrors::validate(errors)
557}
558
559fn details_to_value<T: Serialize>(details: T) -> Value {
560    serde_json::to_value(details).unwrap_or_else(|error| {
561        json!({
562            "serialization_error": error.to_string(),
563        })
564    })
565}
566
567fn available_values_suggestion(prefix: String, values: &[String]) -> Option<String> {
568    if values.is_empty() {
569        Some(format!("{prefix}; no alternatives are available."))
570    } else {
571        Some(format!("{prefix}: {}.", values.join(", ")))
572    }
573}
574
575#[cfg(test)]
576mod tests {
577    use super::*;
578    use serde_json::json;
579    use std::error::Error;
580
581    #[test]
582    fn validation_error_serializes_with_context() {
583        let error = VlorQLError::validation(
584            ValidationErrorKind::InvalidColumn {
585                table: "users".to_owned(),
586                column: "emali".to_owned(),
587                available_columns: vec!["email".to_owned(), "id".to_owned()],
588            },
589            json!({"path": ["select", 0]}),
590        );
591
592        let serialized = serde_json::to_value(&error).expect("error should serialize");
593        assert_eq!(
594            serialized["Validation"]["kind"]["invalid_column"]["table"],
595            "users"
596        );
597        assert_eq!(serialized["Validation"]["details"]["path"][0], "select");
598    }
599
600    #[test]
601    fn error_code_and_response_include_repair_guidance() {
602        let error = VlorQLError::validation(
603            ValidationErrorKind::InvalidTable {
604                table: "usrers".to_owned(),
605                available_tables: vec!["users".to_owned()],
606            },
607            json!({"source": "llm"}),
608        );
609
610        let response = error.to_error_response();
611        assert_eq!(error.error_code(), "V003");
612        assert_eq!(response.code, "V003");
613        assert!(response.message.contains("usrers"));
614        assert_eq!(response.details["source"], "llm");
615        assert!(
616            response
617                .suggestion
618                .as_deref()
619                .is_some_and(|suggestion| suggestion.contains("users"))
620        );
621    }
622
623    #[test]
624    fn all_error_categories_have_unique_codes() {
625        let errors = [
626            VlorQLError::validation(ValidationErrorKind::InvalidJson, json!({})),
627            VlorQLError::policy(
628                PolicyErrorKind::TableDenied {
629                    table: "secrets".to_owned(),
630                },
631                json!({}),
632            ),
633            VlorQLError::compilation(
634                CompilationErrorKind::InvalidPlaceholder { index: 0 },
635                json!({}),
636            ),
637            VlorQLError::schema(
638                SchemaErrorKind::TableNotFound {
639                    table: "users".to_owned(),
640                },
641                json!({}),
642            ),
643            VlorQLError::llm(LlmErrorKind::Timeout, json!({})),
644            VlorQLError::config(ConfigErrorKind::MissingSchema, json!({})),
645        ];
646        let codes: std::collections::HashSet<_> =
647            errors.iter().map(VlorQLError::error_code).collect();
648        assert_eq!(codes.len(), errors.len());
649    }
650
651    #[test]
652    fn retryability_distinguishes_recoverable_and_configuration_errors() {
653        let validation = VlorQLError::validation(
654            ValidationErrorKind::MissingField {
655                field: "from".to_owned(),
656            },
657            json!({}),
658        );
659        let llm = VlorQLError::llm(
660            LlmErrorKind::ParseError {
661                details: "bad JSON".to_owned(),
662            },
663            json!({}),
664        );
665        let policy = VlorQLError::policy(
666            PolicyErrorKind::ColumnDenied {
667                table: "users".to_owned(),
668                column: "password_hash".to_owned(),
669            },
670            json!({}),
671        );
672        let config = VlorQLError::config(
673            ConfigErrorKind::InvalidDialect {
674                dialect: "unknown".to_owned(),
675            },
676            json!({}),
677        );
678
679        assert!(validation.is_retryable());
680        assert!(llm.is_retryable());
681        assert!(!policy.is_retryable());
682        assert!(!config.is_retryable());
683    }
684
685    #[test]
686    fn validation_errors_aggregate_and_implement_error() {
687        let errors = vec![
688            VlorQLError::validation(ValidationErrorKind::InvalidJson, json!({})),
689            VlorQLError::validation(
690                ValidationErrorKind::MissingField {
691                    field: "select".to_owned(),
692                },
693                json!({}),
694            ),
695        ];
696        let aggregated = ValidationErrors::from(errors);
697
698        assert_eq!(aggregated.len(), 2);
699        assert!(!aggregated.is_empty());
700        let rendered = aggregated.to_string();
701        assert!(rendered.contains("2 validation errors occurred"));
702        assert!(rendered.contains("V001"));
703        assert!(rendered.contains("V002"));
704        assert!(rendered.contains("[0]"));
705        assert!(rendered.contains("[1]"));
706        assert!(rendered.contains("the LLM response is not valid JSON"));
707        assert!(rendered.contains("required field `select` is missing"));
708        assert!(aggregated.source().is_none());
709        assert!(ValidationErrors::validate(Vec::<VlorQLError>::new()).is_ok());
710        assert!(ValidationErrors::validate(aggregated.as_slice().iter().cloned()).is_err());
711    }
712
713    // -----------------------------------------------------------------
714    // Exhaustive coverage of every error kind, asserting that
715    // (a) construction works, (b) error_code() returns the expected
716    // string, and (c) to_error_response() exposes the right fields.
717    // -----------------------------------------------------------------
718
719    fn assert_code_and_suggestion(
720        error: &VlorQLError,
721        expected_code: &str,
722        expected_suggestion: Option<&str>,
723    ) {
724        assert_eq!(error.error_code(), expected_code, "code for {error:?}");
725        let response = error.to_error_response();
726        assert_eq!(response.code, expected_code, "response code for {error:?}");
727        assert!(!response.message.is_empty(), "message for {error:?}");
728        match expected_suggestion {
729            Some(suggestion) => assert_eq!(
730                response.suggestion.as_deref(),
731                Some(suggestion),
732                "suggestion for {error:?}"
733            ),
734            None => assert!(
735                response.suggestion.is_none(),
736                "expected no suggestion for {error:?}, got {:?}",
737                response.suggestion
738            ),
739        }
740        // The details payload must round-trip through serde.
741        serde_json::to_value(&response).expect("response should serialize");
742    }
743
744    #[test]
745    fn every_validation_error_kind_has_a_distinct_code_and_useful_suggestion() {
746        assert_code_and_suggestion(
747            &VlorQLError::validation(ValidationErrorKind::InvalidJson, json!({})),
748            "V001",
749            Some("Return a JSON object matching the query plan schema."),
750        );
751        assert_code_and_suggestion(
752            &VlorQLError::validation(
753                ValidationErrorKind::MissingField {
754                    field: "from".to_owned(),
755                },
756                json!({}),
757            ),
758            "V002",
759            Some("Add the required field `from` to the query plan."),
760        );
761        assert_code_and_suggestion(
762            &VlorQLError::validation(
763                ValidationErrorKind::InvalidColumn {
764                    table: "users".to_owned(),
765                    column: "emali".to_owned(),
766                    available_columns: vec!["email".to_owned(), "id".to_owned()],
767                },
768                json!({}),
769            ),
770            "V004",
771            Some("Replace column `users.emali` with an available column: email, id."),
772        );
773        assert_code_and_suggestion(
774            &VlorQLError::validation(
775                ValidationErrorKind::InvalidFunction {
776                    function: "load_extension".to_owned(),
777                    allowed_functions: vec!["count".to_owned()],
778                },
779                json!({}),
780            ),
781            "V005",
782            Some("Replace function `load_extension` with an allowed function: count."),
783        );
784        assert_code_and_suggestion(
785            &VlorQLError::validation(
786                ValidationErrorKind::TypeMismatch {
787                    expected: "int".to_owned(),
788                    found: "string".to_owned(),
789                    expr: "users.id".to_owned(),
790                },
791                json!({}),
792            ),
793            "V006",
794            Some("Change `users.id` from type `string` to the expected type `int`."),
795        );
796        assert_code_and_suggestion(
797            &VlorQLError::validation(
798                ValidationErrorKind::DialectFeatureDisabled {
799                    feature: "cte".to_owned(),
800                },
801                json!({}),
802            ),
803            "V007",
804            Some("Remove `cte` or select a dialect profile that enables it."),
805        );
806        assert_code_and_suggestion(
807            &VlorQLError::validation(
808                ValidationErrorKind::TooManyJoins { actual: 5, max: 2 },
809                json!({}),
810            ),
811            "V008",
812            Some("Reduce the query from 5 joins to at most 2 joins."),
813        );
814        assert_code_and_suggestion(
815            &VlorQLError::validation(
816                ValidationErrorKind::AggregationMismatch {
817                    message: "mixed aggregation".to_owned(),
818                },
819                json!({}),
820            ),
821            "V009",
822            Some(
823                "Adjust the selected and grouped expressions to satisfy aggregation rules: \
824                 mixed aggregation",
825            ),
826        );
827
828        // `InvalidTable` with no available alternatives gets a slightly
829        // different suggestion.
830        let isolated = VlorQLError::validation(
831            ValidationErrorKind::InvalidTable {
832                table: "missing".to_owned(),
833                available_tables: vec![],
834            },
835            json!({}),
836        );
837        let response = isolated.to_error_response();
838        assert_eq!(response.code, "V003");
839        assert!(
840            response
841                .suggestion
842                .as_deref()
843                .is_some_and(|s| s.contains("no alternatives")),
844            "got {:?}",
845            response.suggestion
846        );
847    }
848
849    #[test]
850    fn every_policy_error_kind_has_a_distinct_code() {
851        let shared_suggestion = "Request the required access or remove the unauthorized resource.";
852        let table = VlorQLError::policy(
853            PolicyErrorKind::TableDenied {
854                table: "secrets".to_owned(),
855            },
856            json!({}),
857        );
858        assert_code_and_suggestion(&table, "P001", Some(shared_suggestion));
859
860        let column = VlorQLError::policy(
861            PolicyErrorKind::ColumnDenied {
862                table: "users".to_owned(),
863                column: "password_hash".to_owned(),
864            },
865            json!({}),
866        );
867        assert_code_and_suggestion(&column, "P002", Some(shared_suggestion));
868    }
869
870    #[test]
871    fn policy_errors_share_a_default_suggestion() {
872        let policy = VlorQLError::policy(
873            PolicyErrorKind::ColumnDenied {
874                table: "users".to_owned(),
875                column: "secret".to_owned(),
876            },
877            json!({}),
878        );
879        let response = policy.to_error_response();
880        assert_eq!(response.code, "P002");
881        assert_eq!(
882            response.suggestion.as_deref(),
883            Some("Request the required access or remove the unauthorized resource.")
884        );
885    }
886
887    #[test]
888    fn every_compilation_error_kind_has_a_distinct_code() {
889        let shared_suggestion = "Use only features supported by the selected SQL dialect compiler.";
890        let unsupported = VlorQLError::compilation(
891            CompilationErrorKind::UnsupportedDialectFeature {
892                feature: "FETCH".to_owned(),
893            },
894            json!({}),
895        );
896        assert_code_and_suggestion(&unsupported, "C001", Some(shared_suggestion));
897
898        let placeholder = VlorQLError::compilation(
899            CompilationErrorKind::InvalidPlaceholder { index: 7 },
900            json!({}),
901        );
902        assert_code_and_suggestion(&placeholder, "C002", Some(shared_suggestion));
903    }
904
905    #[test]
906    fn every_schema_error_kind_has_a_distinct_code() {
907        let missing_table = VlorQLError::schema(
908            SchemaErrorKind::TableNotFound {
909                table: "ghost".to_owned(),
910            },
911            json!({}),
912        );
913        assert_code_and_suggestion(
914            &missing_table,
915            "S001",
916            Some(
917                "Add the table as a JOIN (with an ON clause) or as the FROM source. If you reference columns with 'table: \"<name>\"', that table must be in FROM or JOINs.",
918            ),
919        );
920
921        let missing_column = VlorQLError::schema(
922            SchemaErrorKind::ColumnNotFound {
923                table: "users".to_owned(),
924                column: "secret".to_owned(),
925            },
926            json!({}),
927        );
928        assert_code_and_suggestion(
929            &missing_column,
930            "S002",
931            Some("Use only column names listed in the schema for the referenced table."),
932        );
933
934        let not_in_scope = VlorQLError::schema(
935            SchemaErrorKind::TableNotInScope {
936                table: "users".to_owned(),
937            },
938            json!({}),
939        );
940        assert_code_and_suggestion(
941            &not_in_scope,
942            "S003",
943            Some(
944                "The table exists in the schema but is not part of the query's FROM or JOIN clauses. Add a JOIN (with an ON clause) for this table.",
945            ),
946        );
947    }
948
949    #[test]
950    fn every_llm_error_kind_has_a_distinct_code_and_suggestion() {
951        let transient = VlorQLError::llm(
952            LlmErrorKind::ApiError {
953                status: 500,
954                message: "down".to_owned(),
955            },
956            json!({}),
957        );
958        assert_code_and_suggestion(
959            &transient,
960            "L001",
961            Some("Retry the LLM request with backoff, then inspect the provider status."),
962        );
963
964        let timeout = VlorQLError::llm(LlmErrorKind::Timeout, json!({}));
965        assert_code_and_suggestion(
966            &timeout,
967            "L002",
968            Some("Retry the LLM request or increase the request timeout."),
969        );
970
971        let parse = VlorQLError::llm(
972            LlmErrorKind::ParseError {
973                details: "bad JSON".to_owned(),
974            },
975            json!({}),
976        );
977        assert_code_and_suggestion(
978            &parse,
979            "L003",
980            Some(
981                "Return only a JSON object matching the QueryPlan schema. No markdown fences, no extra text, no comments.",
982            ),
983        );
984    }
985
986    #[test]
987    fn llm_suggestion_distinguishes_auth_failures_from_transient_errors() {
988        let auth = VlorQLError::llm(
989            LlmErrorKind::ApiError {
990                status: 401,
991                message: "unauthorized".to_owned(),
992            },
993            json!({}),
994        );
995        let transient = VlorQLError::llm(
996            LlmErrorKind::ApiError {
997                status: 503,
998                message: "down".to_owned(),
999            },
1000            json!({}),
1001        );
1002        assert_eq!(
1003            auth.to_error_response().suggestion.as_deref(),
1004            Some("Check the LLM provider credentials and permissions.")
1005        );
1006        assert_eq!(
1007            transient.to_error_response().suggestion.as_deref(),
1008            Some("Retry the LLM request with backoff, then inspect the provider status.")
1009        );
1010    }
1011
1012    #[test]
1013    fn every_config_error_kind_has_a_distinct_code_and_no_suggestion() {
1014        let missing_client = VlorQLError::config(ConfigErrorKind::MissingLlmClient, json!({}));
1015        assert_code_and_suggestion(&missing_client, "G001", None);
1016
1017        let missing_schema = VlorQLError::config(ConfigErrorKind::MissingSchema, json!({}));
1018        assert_code_and_suggestion(&missing_schema, "G002", None);
1019
1020        let bad_dialect = VlorQLError::config(
1021            ConfigErrorKind::InvalidDialect {
1022                dialect: "oracle".to_owned(),
1023            },
1024            json!({}),
1025        );
1026        assert_code_and_suggestion(&bad_dialect, "G003", None);
1027    }
1028
1029    #[test]
1030    fn only_validation_and_llm_errors_are_retryable() {
1031        let cases = [
1032            (
1033                VlorQLError::validation(ValidationErrorKind::InvalidJson, json!({})),
1034                true,
1035            ),
1036            (
1037                VlorQLError::validation(
1038                    ValidationErrorKind::TooManyJoins { actual: 3, max: 1 },
1039                    json!({}),
1040                ),
1041                false,
1042            ),
1043            (VlorQLError::llm(LlmErrorKind::Timeout, json!({})), true),
1044            (
1045                VlorQLError::llm(
1046                    LlmErrorKind::ApiError {
1047                        status: 500,
1048                        message: "down".to_owned(),
1049                    },
1050                    json!({}),
1051                ),
1052                true,
1053            ),
1054            (
1055                VlorQLError::policy(
1056                    PolicyErrorKind::TableDenied {
1057                        table: "secrets".to_owned(),
1058                    },
1059                    json!({}),
1060                ),
1061                false,
1062            ),
1063            (
1064                VlorQLError::policy(
1065                    PolicyErrorKind::ColumnDenied {
1066                        table: "users".to_owned(),
1067                        column: "password_hash".to_owned(),
1068                    },
1069                    json!({}),
1070                ),
1071                false,
1072            ),
1073            (
1074                VlorQLError::compilation(
1075                    CompilationErrorKind::UnsupportedDialectFeature {
1076                        feature: "FETCH".to_owned(),
1077                    },
1078                    json!({}),
1079                ),
1080                false,
1081            ),
1082            (
1083                VlorQLError::schema(
1084                    SchemaErrorKind::TableNotFound {
1085                        table: "missing".to_owned(),
1086                    },
1087                    json!({}),
1088                ),
1089                true,
1090            ),
1091            (
1092                VlorQLError::schema(
1093                    SchemaErrorKind::TableNotInScope {
1094                        table: "users".to_owned(),
1095                    },
1096                    json!({}),
1097                ),
1098                true,
1099            ),
1100            (
1101                VlorQLError::config(ConfigErrorKind::MissingSchema, json!({})),
1102                false,
1103            ),
1104        ];
1105        for (error, expected) in cases {
1106            assert_eq!(
1107                error.is_retryable(),
1108                expected,
1109                "retryability for {:?} should be {expected}",
1110                error
1111            );
1112        }
1113    }
1114
1115    #[test]
1116    fn error_response_round_trips_through_serde() {
1117        let error = VlorQLError::validation(
1118            ValidationErrorKind::TypeMismatch {
1119                expected: "int".to_owned(),
1120                found: "string".to_owned(),
1121                expr: "users.id".to_owned(),
1122            },
1123            json!({"path": ["where"]}),
1124        );
1125        let response = error.to_error_response();
1126        let serialized =
1127            serde_json::to_string(&response).expect("response should serialize to JSON");
1128        let restored: ErrorResponse =
1129            serde_json::from_str(&serialized).expect("response should round-trip");
1130        assert_eq!(restored.code, response.code);
1131        assert_eq!(restored.message, response.message);
1132        assert_eq!(restored.suggestion, response.suggestion);
1133        assert_eq!(restored.details, response.details);
1134    }
1135
1136    #[test]
1137    fn kind_name_reports_the_top_level_category() {
1138        let validation = VlorQLError::validation(ValidationErrorKind::InvalidJson, json!({}));
1139        let policy = VlorQLError::policy(
1140            PolicyErrorKind::TableDenied {
1141                table: "x".to_owned(),
1142            },
1143            json!({}),
1144        );
1145        let compilation = VlorQLError::compilation(
1146            CompilationErrorKind::InvalidPlaceholder { index: 1 },
1147            json!({}),
1148        );
1149        let schema = VlorQLError::schema(
1150            SchemaErrorKind::TableNotFound {
1151                table: "x".to_owned(),
1152            },
1153            json!({}),
1154        );
1155        let llm = VlorQLError::llm(LlmErrorKind::Timeout, json!({}));
1156        let config = VlorQLError::config(ConfigErrorKind::MissingSchema, json!({}));
1157        assert_eq!(validation.kind_name(), "validation");
1158        assert_eq!(policy.kind_name(), "policy");
1159        assert_eq!(compilation.kind_name(), "compilation");
1160        assert_eq!(schema.kind_name(), "schema");
1161        assert_eq!(llm.kind_name(), "llm");
1162        assert_eq!(config.kind_name(), "config");
1163    }
1164
1165    #[test]
1166    fn single_validation_error_renders_without_count_header() {
1167        let error = VlorQLError::validation(
1168            ValidationErrorKind::MissingField {
1169                field: "from".to_owned(),
1170            },
1171            json!({}),
1172        );
1173        let aggregated = ValidationErrors::from(vec![error]);
1174        let rendered = aggregated.to_string();
1175        assert!(
1176            rendered.contains("1 validation error:") || rendered.contains("validation error:"),
1177            "rendered: {rendered}"
1178        );
1179        assert!(rendered.contains("V002"), "rendered: {rendered}");
1180        assert!(
1181            rendered.contains("required field `from` is missing"),
1182            "rendered: {rendered}"
1183        );
1184        // Single-error rendering should not contain the multi-error
1185        // "occurred (codes:" line.
1186        assert!(
1187            !rendered.contains("occurred (codes:"),
1188            "rendered: {rendered}"
1189        );
1190    }
1191
1192    #[test]
1193    fn empty_validation_errors_renders_no_errors_message() {
1194        let aggregated = ValidationErrors(Vec::new());
1195        assert_eq!(aggregated.to_string(), "no validation errors");
1196    }
1197
1198    #[test]
1199    fn validation_errors_into_inner_returns_owned_vector() {
1200        let errors = vec![VlorQLError::validation(
1201            ValidationErrorKind::InvalidJson,
1202            json!({}),
1203        )];
1204        let aggregated = ValidationErrors::from(errors);
1205        let inner = aggregated.into_inner();
1206        assert_eq!(inner.len(), 1);
1207    }
1208
1209    #[test]
1210    fn free_function_validate_aggregates_iterator_input() {
1211        let errors = [
1212            VlorQLError::validation(ValidationErrorKind::InvalidJson, json!({})),
1213            VlorQLError::validation(
1214                ValidationErrorKind::MissingField {
1215                    field: "select".to_owned(),
1216                },
1217                json!({}),
1218            ),
1219        ];
1220        let result = crate::errors::validate(errors);
1221        let aggregated = result.expect_err("non-empty iterator should produce ValidationErrors");
1222        assert_eq!(aggregated.len(), 2);
1223    }
1224
1225    #[test]
1226    fn validation_errors_serialize_and_deserialize_through_serde() {
1227        let errors = vec![
1228            VlorQLError::validation(ValidationErrorKind::InvalidJson, json!({})),
1229            VlorQLError::policy(
1230                PolicyErrorKind::TableDenied {
1231                    table: "secrets".to_owned(),
1232                },
1233                json!({}),
1234            ),
1235        ];
1236        let aggregated = ValidationErrors::from(errors);
1237        let serialized = serde_json::to_string(&aggregated).expect("should serialize");
1238        let restored: ValidationErrors =
1239            serde_json::from_str(&serialized).expect("should round-trip");
1240        assert_eq!(restored, aggregated);
1241    }
1242}