vlorql-core 0.5.0

A high-performance SQL query optimizer with constant folding, predicate pushdown, column pruning, and cost-based join reordering
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! End-to-end validation pipeline orchestration.

use super::audit::AuditStage;
use super::dialect::DialectValidator;
use super::operand::OperandValidator;
use super::schema::validate_schema;
use crate::errors::{ValidationErrors, VlorQLError};
use crate::fix;
use crate::optimizer::QueryOptimizer;
use crate::policy::PolicyEngine;
use crate::schema::{ArcSchemaSnapshot, DialectProfile, Predicate, QueryPlan, SchemaSnapshot};
use std::ops::Deref;
use std::sync::Arc;

/// A query plan that has passed schema, policy, operand, and dialect validation.
///
/// # Examples
///
/// ```
/// use vlorql_core::validate::ValidatedPlan;
/// use vlorql_core::schema::{QueryPlan, Projection, FromClause};
/// use std::sync::Arc;
///
/// let plan = QueryPlan {
///     select: vec![Projection::Column {
///         table: None, column: "id".to_owned(), alias: None,
///     }],
///     from: FromClause::table("users".to_owned(), None),
///     r#where: None, group_by: None, having: None,
///     order_by: None, limit: None, offset: None,
///     joins: None, ctes: None, distinct: false, distinct_on: None, set_operation: None,
/// };
/// let validated = ValidatedPlan(Arc::new(plan));
/// assert_eq!(validated.as_plan().from.table_name().unwrap(), "users");
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct ValidatedPlan(pub Arc<QueryPlan>);

impl ValidatedPlan {
    /// Borrows the validated query plan.
    pub fn as_plan(&self) -> &QueryPlan {
        self.0.as_ref()
    }

    /// Consumes the wrapper and returns the query plan.
    pub fn into_inner(self) -> Arc<QueryPlan> {
        self.0
    }
}

impl Deref for ValidatedPlan {
    type Target = QueryPlan;

    fn deref(&self) -> &Self::Target {
        self.as_plan()
    }
}

/// A query plan that has been validated **and** optimized.
///
/// Wraps a [`ValidatedPlan`] so that downstream consumers (notably the
/// SQL compiler) can distinguish optimised plans from merely-validated
/// ones.  `OptimizedPlan` derefs to `ValidatedPlan`, so it can be used
/// wherever a `&ValidatedPlan` is expected.
///
/// # Examples
///
/// ```
/// use vlorql_core::validate::{ValidatedPlan, OptimizedPlan};
/// use vlorql_core::schema::{QueryPlan, Projection, FromClause};
/// use std::sync::Arc;
///
/// let plan = QueryPlan {
///     select: vec![Projection::Column {
///         table: None, column: "id".to_owned(), alias: None,
///     }],
///     from: FromClause::table("users".to_owned(), None),
///     r#where: None, group_by: None, having: None,
///     order_by: None, limit: None, offset: None,
///     joins: None, ctes: None, distinct: false, distinct_on: None, set_operation: None,
/// };
/// let validated = ValidatedPlan(Arc::new(plan));
/// let optimized = OptimizedPlan::from(validated);
/// assert_eq!(optimized.as_plan().from.table_name().unwrap(), "users");
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct OptimizedPlan(ValidatedPlan);

impl OptimizedPlan {
    /// Borrows the underlying validated plan.
    pub fn as_validated(&self) -> &ValidatedPlan {
        &self.0
    }

    /// Consumes the wrapper and returns the validated plan.
    pub fn into_validated(self) -> ValidatedPlan {
        self.0
    }

    /// Consumes the wrapper and returns the query plan.
    pub fn into_inner(self) -> Arc<QueryPlan> {
        self.0.into_inner()
    }
}

impl From<ValidatedPlan> for OptimizedPlan {
    fn from(plan: ValidatedPlan) -> Self {
        Self(plan)
    }
}

impl Deref for OptimizedPlan {
    type Target = ValidatedPlan;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Runs all validation stages while sharing an immutable schema snapshot.
///
/// The pipeline runs schema validation, policy checks, operand validation,
/// dialect validation, and an optional SQL injection audit stage.  If
/// configured via [`with_audit`](Self::with_audit), critical audit findings
/// short-circuit the pipeline immediately.
///
/// # Examples
///
/// ```
/// use vlorql_core::validate::ValidationPipeline;
/// use vlorql_core::schema::{SchemaSnapshot, DialectProfile, SqlDialect, QueryPlan, Projection, FromClause, TableSchema, ColumnSchema, DataType, SchemaMetadata};
/// use vlorql_core::policy::{PolicyConfig, PolicyEngine};
/// use std::sync::Arc;
///
/// let schema = Arc::new(SchemaSnapshot::new(
///     vec![TableSchema {
///         name: "users".to_owned(),
///         columns: vec![ColumnSchema {
///             name: "id".to_owned(), data_type: DataType::Int,
///             nullable: false, description: None,
///             is_primary_key: true, foreign_key: None,
///         }],
///         description: None, primary_key: Some(vec!["id".to_owned()]),
///     }],
///     SchemaMetadata::default(),
/// ));
/// let pipeline = ValidationPipeline::new(
///     schema,
///     DialectProfile::default(),
///     PolicyEngine::new(PolicyConfig::default()),
/// )
/// .with_audit(true);
/// let plan = QueryPlan {
///     select: vec![Projection::Column {
///         table: None, column: "id".to_owned(), alias: None,
///     }],
///     from: FromClause::table("users".to_owned(), None),
///     r#where: None, group_by: None, having: None,
///     order_by: None, limit: None, offset: None,
///     joins: None, ctes: None, distinct: false, distinct_on: None, set_operation: None,
/// };
/// assert!(pipeline.validate(&plan).is_ok());
/// ```
#[derive(Debug, Clone)]
pub struct ValidationPipeline {
    schema: ArcSchemaSnapshot,
    dialect: DialectProfile,
    policy: PolicyEngine,
    optimizer: Option<QueryOptimizer>,
    audit_stage: Option<AuditStage>,
}

impl ValidationPipeline {
    /// Creates a complete validation pipeline without an optimizer.
    pub fn new(schema: Arc<SchemaSnapshot>, dialect: DialectProfile, policy: PolicyEngine) -> Self {
        Self {
            schema,
            dialect,
            policy,
            optimizer: None,
            audit_stage: None,
        }
    }

    /// Attaches an optional [`QueryOptimizer`] to the pipeline.
    ///
    /// When set, [`Self::validate_and_optimize`] will run the optimizer
    /// after validation succeeds and re-validate policy constraints on
    /// the optimised plan.
    #[must_use]
    pub fn with_optimizer(mut self, optimizer: QueryOptimizer) -> Self {
        self.optimizer = Some(optimizer);
        self
    }

    /// Attaches an optional [`AuditStage`] to the pipeline.
    ///
    /// When enabled, [`Self::validate`] and [`Self::validate_repairing`] will
    /// run an SQL-injection audit on the plan after dialect validation and
    /// return critical errors immediately without proceeding to policy
    /// injection.
    #[must_use]
    pub fn with_audit(mut self, enable: bool) -> Self {
        if enable {
            self.audit_stage = Some(AuditStage::new());
        } else {
            self.audit_stage = None;
        }
        self
    }

    /// Executes every validation stage and aggregates all returned errors.
    ///
    /// After successful validation, mandatory policy row filters are
    /// injected into the plan's `WHERE` clause so they are enforced
    /// at the SQL level.
    pub fn validate(&self, plan: &QueryPlan) -> Result<ValidatedPlan, ValidationErrors> {
        // Clone the plan early so we can apply schema-aware fixes before
        // validation.  The fixer repairs common LLM mistakes (missing joins,
        // nested aggregates, broken GROUP BY) using the real schema metadata.
        let mut plan = plan.clone();
        let _span = tracing::info_span!("vlorql.validate.fix").entered();
        let _ = fix::schema_aware_fix(&mut plan, &self.schema);
        drop(_span);

        let mut errors = Vec::new();

        {
            let _span = tracing::info_span!("vlorql.validate.schema").entered();
            if let Err(stage_errors) = self.validate_schema(&plan) {
                extend_unique(&mut errors, stage_errors);
            }
        }
        {
            let _span = tracing::info_span!("vlorql.validate.policy").entered();
            if let Err(stage_errors) = self.policy.validate(&plan, &self.schema) {
                extend_unique(&mut errors, stage_errors);
            }
        }
        {
            let _span = tracing::info_span!("vlorql.validate.operand").entered();
            if let Err(stage_errors) = OperandValidator::validate(&plan, &self.schema) {
                extend_unique(&mut errors, stage_errors);
            }
        }
        {
            let _span = tracing::info_span!("vlorql.validate.dialect").entered();
            if let Err(stage_errors) = DialectValidator::validate(&plan, &self.dialect) {
                extend_unique(&mut errors, stage_errors);
            }
        }

        // SQL injection audit stage.
        if let Some(ref audit) = self.audit_stage
            && let Err(audit_errors) = audit.audit(&plan, &self.schema)
        {
            // SuspiciousPattern (critical) errors are NOT retryable;
            // separate them so the pipeline can short-circuit.
            let (critical, others): (Vec<_>, Vec<_>) =
                audit_errors.into_iter().partition(|e| !e.is_retryable());
            if !critical.is_empty() {
                return Err(ValidationErrors(critical));
            }
            extend_unique(&mut errors, others);
        }

        if !errors.is_empty() {
            return Err(ValidationErrors(errors));
        }

        // Inject mandatory policy row filters into the plan's WHERE clause.
        // These are AND-ed with any existing WHERE predicate so they are
        // enforced at the SQL level and cannot be bypassed.
        if let Some(row_filter) = self.policy.apply_row_filters(&plan) {
            plan.r#where = Some(match plan.r#where {
                Some(existing) => Predicate::And {
                    left: Box::new(existing),
                    right: Box::new(row_filter),
                },
                None => row_filter,
            });
        }

        // Re-validate schema on the modified plan to catch any invalid
        // table/column references introduced by the policy row filters.
        // The original plan already passed schema validation, so only
        // the injected predicates are checked here.
        if let Err(stage_errors) = self.validate_schema(&plan) {
            return Err(ValidationErrors(stage_errors));
        }

        Ok(ValidatedPlan(Arc::new(plan)))
    }

    /// Like [`validate`](Self::validate), but first applies execution-time
    /// auto-repairs that are unsafe for diagnostics — currently dropping
    /// JOINs to tables that do not exist in the schema (hallucinated by the
    /// LLM). Use this on the query/execution path so a bogus JOIN does not
    /// abort the request; use [`validate`](Self::validate) (via
    /// `validate_only`) when you want every schema error surfaced.
    ///
    /// # Errors
    /// Returns [`ValidationErrors`] when any validation stage fails on the
    /// repaired plan.
    pub fn validate_repairing(&self, plan: &QueryPlan) -> Result<ValidatedPlan, ValidationErrors> {
        let mut repaired = plan.clone();
        let _ = fix::drop_hallucinated_joins(&mut repaired, &self.schema);

        // SQL injection audit stage — run on the repaired plan before
        // proceeding to the full validation pipeline.
        if let Some(ref audit) = self.audit_stage
            && let Err(audit_errors) = audit.audit(&repaired, &self.schema)
        {
            let (critical, others): (Vec<_>, Vec<_>) =
                audit_errors.into_iter().partition(|e| !e.is_retryable());
            if !critical.is_empty() {
                return Err(ValidationErrors(critical));
            }
            if !others.is_empty() {
                return Err(ValidationErrors(others));
            }
        }

        self.validate(&repaired)
    }

    /// Validates a plan and, when an optimizer is configured, applies
    /// optimisation passes to the validated result.
    ///
    /// After optimisation the plan is **re-validated against the policy**
    /// engine to ensure the rewrite rules did not introduce any
    /// unauthorised table or column access.  Schema, operand, and dialect
    /// checks are *not* re-run because the optimiser never introduces
    /// new tables, columns, or expressions that those stages would reject.
    ///
    /// The CPU-intensive validation and policy check stages are offloaded
    /// to a blocking thread via [`tokio::task::spawn_blocking`].
    ///
    /// # Errors
    ///
    /// Returns [`ValidationErrors`] when any stage (including the
    /// post-optimisation policy check) fails.
    pub async fn validate_and_optimize(
        &self,
        plan: &QueryPlan,
    ) -> Result<OptimizedPlan, ValidationErrors> {
        // Offload CPU-intensive validation to blocking thread.
        let this = self.clone();
        let plan_clone = plan.clone();
        let validated = tokio::task::spawn_blocking(move || this.validate(&plan_clone))
            .await
            .map_err(|join_err| {
                ValidationErrors::new(vec![VlorQLError::config(
                    crate::errors::ConfigErrorKind::InternalError {
                        reason: format!("validate spawn_blocking join failed: {join_err}"),
                    },
                    serde_json::json!({"operation": "validate_and_optimize"}),
                )])
            })??;

        let Some(ref optimizer) = self.optimizer else {
            return Ok(OptimizedPlan::from(validated));
        };

        let optimized_plan = match optimizer.optimize_async(validated.as_plan()).await {
            Ok(p) => p,
            Err(e) => {
                return Err(ValidationErrors::new(vec![e]));
            }
        };

        // Re-validate policy on the optimised plan — the rewrite rules
        // are conservative, but a reorder could, in theory, expose a
        // column that was previously pruned.
        let this = self.clone();
        let opt_clone = optimized_plan.clone();
        if let Err(stage_errors) =
            tokio::task::spawn_blocking(move || this.policy.validate(&opt_clone, &this.schema))
                .await
                .map_err(|join_err| {
                    ValidationErrors::new(vec![VlorQLError::config(
                        crate::errors::ConfigErrorKind::InternalError {
                            reason: format!(
                                "policy validate spawn_blocking join failed: {join_err}"
                            ),
                        },
                        serde_json::json!({"operation": "validate_and_optimize"}),
                    )])
                })?
        {
            return Err(ValidationErrors(stage_errors));
        }

        Ok(OptimizedPlan::from(ValidatedPlan(Arc::new(optimized_plan))))
    }

    /// Runs only schema table and column existence validation.
    pub fn validate_schema(&self, plan: &QueryPlan) -> Result<(), Vec<VlorQLError>> {
        validate_schema(plan, &self.schema)
    }

    /// Returns the shared schema snapshot.
    pub fn schema(&self) -> &ArcSchemaSnapshot {
        &self.schema
    }

    /// Returns the dialect profile.
    pub fn dialect(&self) -> &DialectProfile {
        &self.dialect
    }

    /// Returns the policy engine.
    pub fn policy(&self) -> &PolicyEngine {
        &self.policy
    }
}

fn extend_unique(errors: &mut Vec<VlorQLError>, stage_errors: Vec<VlorQLError>) {
    for error in stage_errors {
        if !errors.contains(&error) {
            errors.push(error);
        }
    }
}