Skip to main content

reddb_server/storage/query/planner/
optimizer.rs

1//! Query Optimizer
2//!
3//! Multi-pass query optimization with pluggable strategies.
4//!
5//! # Optimization Passes
6//!
7//! 1. **PredicatePushdown**: Move filters to data sources
8//! 2. **JoinReordering**: Optimal join order via IDP algorithm
9//! 3. **IndexSelection**: Choose best indexes for scans
10//! 4. **ProjectionPushdown**: Eliminate unused columns early
11//! 5. **ExpressionSimplification**: Simplify complex expressions
12
13use crate::storage::query::ast::{JoinQuery, JoinType, QueryExpr};
14use crate::storage::query::sql_lowering::{effective_table_filter, effective_vector_filter};
15
16/// An optimization pass that transforms query expressions
17pub trait OptimizationPass: Send + Sync {
18    /// Pass name for debugging
19    fn name(&self) -> &str;
20
21    /// Apply the optimization pass
22    fn apply(&self, query: QueryExpr) -> QueryExpr;
23
24    /// Estimated benefit (higher = more important)
25    fn benefit(&self) -> u32;
26}
27
28/// Query optimizer with multiple passes
29pub struct QueryOptimizer {
30    /// Ordered optimization passes
31    passes: Vec<Box<dyn OptimizationPass>>,
32    /// Enable cost-based optimization
33    cost_based: bool,
34}
35
36impl QueryOptimizer {
37    /// Create a new optimizer with default passes
38    pub fn new() -> Self {
39        let passes: Vec<Box<dyn OptimizationPass>> = vec![
40            Box::new(PredicatePushdownPass),
41            Box::new(ProjectionPushdownPass),
42            Box::new(JoinReorderingPass),
43            Box::new(IndexSelectionPass),
44            Box::new(LimitPushdownPass),
45        ];
46
47        Self {
48            passes,
49            cost_based: true,
50        }
51    }
52
53    /// Add a custom optimization pass
54    pub fn add_pass(&mut self, pass: Box<dyn OptimizationPass>) {
55        self.passes.push(pass);
56        // Sort by benefit (highest first)
57        self.passes.sort_by_key(|b| std::cmp::Reverse(b.benefit()));
58    }
59
60    /// Optimize a query expression
61    pub fn optimize(&self, query: QueryExpr) -> (QueryExpr, Vec<String>) {
62        let mut optimized = query;
63        let mut applied_passes = Vec::new();
64
65        for pass in &self.passes {
66            let before = format!("{:?}", optimized);
67            optimized = pass.apply(optimized);
68            let after = format!("{:?}", optimized);
69
70            if before != after {
71                applied_passes.push(pass.name().to_string());
72            }
73        }
74
75        (optimized, applied_passes)
76    }
77
78    /// Optimize with hints
79    pub fn optimize_with_hints(&self, query: QueryExpr, hints: &OptimizationHints) -> QueryExpr {
80        let mut optimized = query;
81
82        for pass in &self.passes {
83            // Check if pass is disabled by hints
84            if hints.disabled_passes.contains(&pass.name().to_string()) {
85                continue;
86            }
87
88            optimized = pass.apply(optimized);
89        }
90
91        optimized
92    }
93}
94
95impl Default for QueryOptimizer {
96    fn default() -> Self {
97        Self::new()
98    }
99}
100
101/// Hints to control optimization
102#[derive(Debug, Clone, Default)]
103pub struct OptimizationHints {
104    /// Disabled optimization passes
105    pub disabled_passes: Vec<String>,
106    /// Force specific join order
107    pub join_order: Option<Vec<String>>,
108    /// Force specific index usage
109    pub force_index: Option<String>,
110    /// Disable parallel execution
111    pub no_parallel: bool,
112}
113
114// =============================================================================
115// Built-in Optimization Passes
116// =============================================================================
117
118/// Push predicates down to data sources
119struct PredicatePushdownPass;
120
121impl OptimizationPass for PredicatePushdownPass {
122    fn name(&self) -> &str {
123        "PredicatePushdown"
124    }
125
126    fn apply(&self, query: QueryExpr) -> QueryExpr {
127        match query {
128            QueryExpr::Join(jq) => self.optimize_join(jq),
129            other => other,
130        }
131    }
132
133    fn benefit(&self) -> u32 {
134        100 // High priority - reduces data early
135    }
136}
137
138impl PredicatePushdownPass {
139    fn optimize_join(&self, query: JoinQuery) -> QueryExpr {
140        // Analyze join condition to find pushable predicates
141        // This is a simplified version - real implementation would analyze
142        // predicate dependencies on join columns
143
144        let left = self.apply(*query.left);
145        let right = self.apply(*query.right);
146
147        QueryExpr::Join(JoinQuery {
148            left: Box::new(left),
149            right: Box::new(right),
150            ..query
151        })
152    }
153}
154
155/// Push projections down to eliminate columns early
156struct ProjectionPushdownPass;
157
158impl OptimizationPass for ProjectionPushdownPass {
159    fn name(&self) -> &str {
160        "ProjectionPushdown"
161    }
162
163    fn apply(&self, query: QueryExpr) -> QueryExpr {
164        match query {
165            QueryExpr::Join(jq) => {
166                // Analyze which columns are actually needed
167                let left = self.apply(*jq.left);
168                let right = self.apply(*jq.right);
169
170                QueryExpr::Join(JoinQuery {
171                    left: Box::new(left),
172                    right: Box::new(right),
173                    ..jq
174                })
175            }
176            QueryExpr::Table(tq) => {
177                // Table projections already use specific column projections
178                // No transformation needed - already efficient
179                QueryExpr::Table(tq)
180            }
181            other => other,
182        }
183    }
184
185    fn benefit(&self) -> u32 {
186        80 // High priority - reduces memory
187    }
188}
189
190/// Reorder joins for optimal execution
191struct JoinReorderingPass;
192
193impl OptimizationPass for JoinReorderingPass {
194    fn name(&self) -> &str {
195        "JoinReordering"
196    }
197
198    fn apply(&self, query: QueryExpr) -> QueryExpr {
199        match query {
200            QueryExpr::Join(jq) => {
201                // For now, just ensure smaller table is on build side
202                // Real IDP algorithm would enumerate join orderings
203                self.optimize_join_order(jq)
204            }
205            other => other,
206        }
207    }
208
209    fn benefit(&self) -> u32 {
210        90 // High priority - join order greatly affects cost
211    }
212}
213
214impl JoinReorderingPass {
215    fn optimize_join_order(&self, query: JoinQuery) -> QueryExpr {
216        // Estimate cardinalities
217        let left_size = Self::estimate_size(&query.left);
218        let right_size = Self::estimate_size(&query.right);
219
220        // For hash join, smaller table should be build side (left)
221        if left_size > right_size && query.join_type == JoinType::Inner {
222            // Swap left and right
223            let JoinQuery {
224                left,
225                right,
226                join_type,
227                on,
228                filter,
229                order_by,
230                limit,
231                offset,
232                return_items,
233                return_,
234            } = query;
235            QueryExpr::Join(JoinQuery {
236                left: right,
237                right: left,
238                join_type,
239                on: swap_condition(on),
240                filter,
241                order_by,
242                limit,
243                offset,
244                return_items,
245                return_,
246            })
247        } else {
248            QueryExpr::Join(query)
249        }
250    }
251
252    fn estimate_size(query: &QueryExpr) -> f64 {
253        match query {
254            QueryExpr::Table(tq) => {
255                let base = 1000.0;
256                if effective_table_filter(tq).is_some() {
257                    base * 0.1
258                } else if tq.limit.is_some() {
259                    tq.limit.unwrap() as f64
260                } else {
261                    base
262                }
263            }
264            QueryExpr::Graph(_) => 100.0,
265            QueryExpr::Join(jq) => {
266                Self::estimate_size(&jq.left) * Self::estimate_size(&jq.right) * 0.1
267            }
268            QueryExpr::Path(_) => 10.0,
269            QueryExpr::Vector(vq) => {
270                // Vector search returns k results
271                if effective_vector_filter(vq).is_some() {
272                    (vq.k as f64).min(100.0)
273                } else {
274                    vq.k as f64
275                }
276            }
277            QueryExpr::Hybrid(hq) => {
278                // Hybrid query combines structured and vector results
279                let structured_size = Self::estimate_size(&hq.structured);
280                let vector_size = hq.vector.k as f64;
281                // Fusion typically reduces to min of both, limited by limit
282                let base = structured_size.min(vector_size);
283                hq.limit.map(|l| base.min(l as f64)).unwrap_or(base)
284            }
285            // DML/DDL/Command statements return minimal result sets
286            QueryExpr::Insert(_)
287            | QueryExpr::Update(_)
288            | QueryExpr::Delete(_)
289            | QueryExpr::CreateTable(_)
290            | QueryExpr::CreateCollection(_)
291            | QueryExpr::CreateVector(_)
292            | QueryExpr::DropTable(_)
293            | QueryExpr::DropGraph(_)
294            | QueryExpr::DropVector(_)
295            | QueryExpr::DropDocument(_)
296            | QueryExpr::DropKv(_)
297            | QueryExpr::DropCollection(_)
298            | QueryExpr::Truncate(_)
299            | QueryExpr::AlterTable(_)
300            | QueryExpr::GraphCommand(_)
301            | QueryExpr::SearchCommand(_)
302            | QueryExpr::CreateIndex(_)
303            | QueryExpr::DropIndex(_)
304            | QueryExpr::ProbabilisticCommand(_)
305            | QueryExpr::Ask(_)
306            | QueryExpr::SetConfig { .. }
307            | QueryExpr::ShowConfig { .. }
308            | QueryExpr::SetSecret { .. }
309            | QueryExpr::DeleteSecret { .. }
310            | QueryExpr::ShowSecrets { .. }
311            | QueryExpr::SetTenant(_)
312            | QueryExpr::ShowTenant
313            | QueryExpr::CreateTimeSeries(_)
314            | QueryExpr::CreateMetric(_)
315            | QueryExpr::AlterMetric(_)
316            | QueryExpr::CreateSlo(_)
317            | QueryExpr::DropTimeSeries(_)
318            | QueryExpr::CreateQueue(_)
319            | QueryExpr::AlterQueue(_)
320            | QueryExpr::DropQueue(_)
321            | QueryExpr::QueueSelect(_)
322            | QueryExpr::QueueCommand(_)
323            | QueryExpr::KvCommand(_)
324            | QueryExpr::ConfigCommand(_)
325            | QueryExpr::CreateTree(_)
326            | QueryExpr::DropTree(_)
327            | QueryExpr::TreeCommand(_)
328            | QueryExpr::ExplainAlter(_)
329            | QueryExpr::TransactionControl(_)
330            | QueryExpr::MaintenanceCommand(_)
331            | QueryExpr::CreateSchema(_)
332            | QueryExpr::DropSchema(_)
333            | QueryExpr::CreateSequence(_)
334            | QueryExpr::DropSequence(_)
335            | QueryExpr::CopyFrom(_)
336            | QueryExpr::CreateView(_)
337            | QueryExpr::DropView(_)
338            | QueryExpr::RefreshMaterializedView(_)
339            | QueryExpr::CreatePolicy(_)
340            | QueryExpr::DropPolicy(_)
341            | QueryExpr::CreateServer(_)
342            | QueryExpr::DropServer(_)
343            | QueryExpr::CreateForeignTable(_)
344            | QueryExpr::DropForeignTable(_)
345            | QueryExpr::Grant(_)
346            | QueryExpr::Revoke(_)
347            | QueryExpr::AlterUser(_)
348            | QueryExpr::CreateIamPolicy { .. }
349            | QueryExpr::DropIamPolicy { .. }
350            | QueryExpr::AttachPolicy { .. }
351            | QueryExpr::DetachPolicy { .. }
352            | QueryExpr::ShowPolicies { .. }
353            | QueryExpr::ShowEffectivePermissions { .. }
354            | QueryExpr::SimulatePolicy { .. }
355            | QueryExpr::LintPolicy { .. }
356            | QueryExpr::MigratePolicyMode { .. }
357            | QueryExpr::CreateMigration(_)
358            | QueryExpr::ApplyMigration(_)
359            | QueryExpr::RollbackMigration(_)
360            | QueryExpr::ExplainMigration(_)
361            | QueryExpr::EventsBackfill(_)
362            | QueryExpr::EventsBackfillStatus { .. } => 1.0,
363        }
364    }
365}
366
367/// Select optimal indexes for table scans.
368///
369/// Analyzes filter predicates and annotates the query plan with index hints:
370/// - Equality predicates (`col = value`) → prefer Hash index if available
371/// - Low-cardinality equality → prefer Bitmap index
372/// - Range predicates (`col > value`, `BETWEEN`) → prefer B-tree
373/// - Spatial predicates → prefer R-tree
374///
375/// The hints are stored in the TableQuery's alias field as a prefix
376/// (e.g., `__idx:hash:col_name`) which the executor can read to skip
377/// full scans. This is a lightweight approach that avoids adding new
378/// fields to the AST while enabling index-aware execution.
379struct IndexSelectionPass;
380
381impl OptimizationPass for IndexSelectionPass {
382    fn name(&self) -> &str {
383        "IndexSelection"
384    }
385
386    fn apply(&self, query: QueryExpr) -> QueryExpr {
387        match query {
388            QueryExpr::Table(mut tq) => {
389                if let Some(filter) = effective_table_filter(&tq).as_ref() {
390                    if let Some(hint) = Self::analyze_filter(filter) {
391                        // Store index hint in expand metadata for executor
392                        let expand = tq.expand.get_or_insert_with(Default::default);
393                        expand.index_hint = Some(hint);
394                    }
395                }
396                QueryExpr::Table(tq)
397            }
398            other => other,
399        }
400    }
401
402    fn benefit(&self) -> u32 {
403        70
404    }
405}
406
407impl IndexSelectionPass {
408    /// Analyze a filter predicate and return the best index hint
409    fn analyze_filter(filter: &crate::storage::query::ast::Filter) -> Option<IndexHint> {
410        match filter {
411            // Equality on a single column → Hash index candidate
412            crate::storage::query::ast::Filter::Compare { field, op, .. }
413                if *op == crate::storage::query::ast::CompareOp::Eq =>
414            {
415                let col = Self::field_name(field);
416                Some(IndexHint {
417                    method: IndexHintMethod::Hash,
418                    column: col,
419                })
420            }
421            // Range predicates → B-tree candidate
422            crate::storage::query::ast::Filter::Compare {
423                field,
424                op:
425                    crate::storage::query::ast::CompareOp::Lt
426                    | crate::storage::query::ast::CompareOp::Le
427                    | crate::storage::query::ast::CompareOp::Gt
428                    | crate::storage::query::ast::CompareOp::Ge,
429                ..
430            } => {
431                let col = Self::field_name(field);
432                Some(IndexHint {
433                    method: IndexHintMethod::BTree,
434                    column: col,
435                })
436            }
437            // BETWEEN → B-tree candidate
438            crate::storage::query::ast::Filter::Between { field, .. } => {
439                let col = Self::field_name(field);
440                Some(IndexHint {
441                    method: IndexHintMethod::BTree,
442                    column: col,
443                })
444            }
445            // IN with few values → Bitmap candidate
446            crate::storage::query::ast::Filter::In { field, values } if values.len() <= 10 => {
447                let col = Self::field_name(field);
448                Some(IndexHint {
449                    method: IndexHintMethod::Bitmap,
450                    column: col,
451                })
452            }
453            // AND: pick the most selective hint from left or right
454            crate::storage::query::ast::Filter::And(left, right) => {
455                Self::analyze_filter(left).or_else(|| Self::analyze_filter(right))
456            }
457            _ => None,
458        }
459    }
460
461    fn field_name(field: &crate::storage::query::ast::FieldRef) -> String {
462        match field {
463            crate::storage::query::ast::FieldRef::TableColumn { column, .. } => column.clone(),
464            crate::storage::query::ast::FieldRef::NodeProperty { property, .. } => property.clone(),
465            crate::storage::query::ast::FieldRef::EdgeProperty { property, .. } => property.clone(),
466            crate::storage::query::ast::FieldRef::NodeId { alias } => {
467                format!("{}.id", alias)
468            }
469        }
470    }
471}
472
473/// Hint about which index method to prefer for a query
474#[derive(Debug, Clone)]
475pub struct IndexHint {
476    /// Preferred index method
477    pub method: IndexHintMethod,
478    /// Column the index applies to
479    pub column: String,
480}
481
482/// Which index method the optimizer recommends
483#[derive(Debug, Clone, Copy, PartialEq, Eq)]
484pub enum IndexHintMethod {
485    Hash,
486    BTree,
487    Bitmap,
488    Spatial,
489}
490
491/// Push LIMIT down through operations
492struct LimitPushdownPass;
493
494impl OptimizationPass for LimitPushdownPass {
495    fn name(&self) -> &str {
496        "LimitPushdown"
497    }
498
499    fn apply(&self, query: QueryExpr) -> QueryExpr {
500        match query {
501            QueryExpr::Join(jq) => {
502                // Can push limit through certain joins
503                let left = self.apply(*jq.left);
504                let right = self.apply(*jq.right);
505
506                QueryExpr::Join(JoinQuery {
507                    left: Box::new(left),
508                    right: Box::new(right),
509                    ..jq
510                })
511            }
512            other => other,
513        }
514    }
515
516    fn benefit(&self) -> u32 {
517        60
518    }
519}
520
521// =============================================================================
522// Helper Functions
523// =============================================================================
524
525fn swap_condition(
526    condition: crate::storage::query::ast::JoinCondition,
527) -> crate::storage::query::ast::JoinCondition {
528    crate::storage::query::ast::JoinCondition {
529        left_field: condition.right_field,
530        right_field: condition.left_field,
531    }
532}
533
534#[cfg(test)]
535mod tests {
536    use super::*;
537    use crate::storage::query::ast::{
538        DistanceMetric, FieldRef, FusionStrategy, JoinCondition, Projection, TableQuery,
539    };
540
541    fn make_table_query(name: &str) -> QueryExpr {
542        QueryExpr::Table(TableQuery {
543            table: name.to_string(),
544            source: None,
545            alias: Some(name.to_string()),
546            select_items: Vec::new(),
547            columns: vec![Projection::All],
548            where_expr: None,
549            filter: None,
550            group_by_exprs: Vec::new(),
551            group_by: Vec::new(),
552            having_expr: None,
553            having: None,
554            order_by: vec![],
555            limit: None,
556            limit_param: None,
557            offset: None,
558            offset_param: None,
559            expand: None,
560            as_of: None,
561            sessionize: None,
562        })
563    }
564
565    #[test]
566    fn test_optimizer_applies_passes() {
567        let optimizer = QueryOptimizer::new();
568        let query = make_table_query("hosts");
569
570        let (optimized, passes) = optimizer.optimize(query);
571        // Should at least attempt the passes
572        assert!(matches!(optimized, QueryExpr::Table(_)));
573    }
574
575    #[test]
576    fn test_join_reordering() {
577        let optimizer = QueryOptimizer::new();
578
579        let small = QueryExpr::Table(TableQuery {
580            table: "small".to_string(),
581            source: None,
582            alias: None,
583            select_items: Vec::new(),
584            columns: vec![Projection::All],
585            where_expr: None,
586            filter: None,
587            group_by_exprs: Vec::new(),
588            group_by: Vec::new(),
589            having_expr: None,
590            having: None,
591            order_by: vec![],
592            limit: Some(10), // Small table
593            limit_param: None,
594            offset: None,
595            offset_param: None,
596            expand: None,
597            as_of: None,
598            sessionize: None,
599        });
600
601        let large = QueryExpr::Table(TableQuery {
602            table: "large".to_string(),
603            source: None,
604            alias: None,
605            select_items: Vec::new(),
606            columns: vec![Projection::All],
607            where_expr: None,
608            filter: None,
609            group_by_exprs: Vec::new(),
610            group_by: Vec::new(),
611            having_expr: None,
612            having: None,
613            order_by: vec![],
614            limit: None, // Large table
615            limit_param: None,
616            offset: None,
617            offset_param: None,
618            expand: None,
619            as_of: None,
620            sessionize: None,
621        });
622
623        let join = QueryExpr::Join(JoinQuery {
624            left: Box::new(large.clone()),
625            right: Box::new(small.clone()),
626            join_type: JoinType::Inner,
627            on: JoinCondition {
628                left_field: FieldRef::TableColumn {
629                    table: "large".to_string(),
630                    column: "id".to_string(),
631                },
632                right_field: FieldRef::TableColumn {
633                    table: "small".to_string(),
634                    column: "id".to_string(),
635                },
636            },
637            filter: None,
638            order_by: Vec::new(),
639            limit: None,
640            offset: None,
641            return_items: Vec::new(),
642            return_: Vec::new(),
643        });
644
645        let (optimized, passes) = optimizer.optimize(join);
646
647        // Should have applied JoinReordering
648        if let QueryExpr::Join(jq) = optimized {
649            // Small table should now be on left (build side)
650            if let QueryExpr::Table(left) = *jq.left {
651                assert_eq!(left.table, "small");
652            }
653        }
654    }
655}