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::DropTimeSeries(_)
315            | QueryExpr::CreateQueue(_)
316            | QueryExpr::AlterQueue(_)
317            | QueryExpr::DropQueue(_)
318            | QueryExpr::QueueSelect(_)
319            | QueryExpr::QueueCommand(_)
320            | QueryExpr::KvCommand(_)
321            | QueryExpr::ConfigCommand(_)
322            | QueryExpr::CreateTree(_)
323            | QueryExpr::DropTree(_)
324            | QueryExpr::TreeCommand(_)
325            | QueryExpr::ExplainAlter(_)
326            | QueryExpr::TransactionControl(_)
327            | QueryExpr::MaintenanceCommand(_)
328            | QueryExpr::CreateSchema(_)
329            | QueryExpr::DropSchema(_)
330            | QueryExpr::CreateSequence(_)
331            | QueryExpr::DropSequence(_)
332            | QueryExpr::CopyFrom(_)
333            | QueryExpr::CreateView(_)
334            | QueryExpr::DropView(_)
335            | QueryExpr::RefreshMaterializedView(_)
336            | QueryExpr::CreatePolicy(_)
337            | QueryExpr::DropPolicy(_)
338            | QueryExpr::CreateServer(_)
339            | QueryExpr::DropServer(_)
340            | QueryExpr::CreateForeignTable(_)
341            | QueryExpr::DropForeignTable(_)
342            | QueryExpr::Grant(_)
343            | QueryExpr::Revoke(_)
344            | QueryExpr::AlterUser(_)
345            | QueryExpr::CreateIamPolicy { .. }
346            | QueryExpr::DropIamPolicy { .. }
347            | QueryExpr::AttachPolicy { .. }
348            | QueryExpr::DetachPolicy { .. }
349            | QueryExpr::ShowPolicies { .. }
350            | QueryExpr::ShowEffectivePermissions { .. }
351            | QueryExpr::SimulatePolicy { .. }
352            | QueryExpr::CreateMigration(_)
353            | QueryExpr::ApplyMigration(_)
354            | QueryExpr::RollbackMigration(_)
355            | QueryExpr::ExplainMigration(_)
356            | QueryExpr::EventsBackfill(_)
357            | QueryExpr::EventsBackfillStatus { .. } => 1.0,
358        }
359    }
360}
361
362/// Select optimal indexes for table scans.
363///
364/// Analyzes filter predicates and annotates the query plan with index hints:
365/// - Equality predicates (`col = value`) → prefer Hash index if available
366/// - Low-cardinality equality → prefer Bitmap index
367/// - Range predicates (`col > value`, `BETWEEN`) → prefer B-tree
368/// - Spatial predicates → prefer R-tree
369///
370/// The hints are stored in the TableQuery's alias field as a prefix
371/// (e.g., `__idx:hash:col_name`) which the executor can read to skip
372/// full scans. This is a lightweight approach that avoids adding new
373/// fields to the AST while enabling index-aware execution.
374struct IndexSelectionPass;
375
376impl OptimizationPass for IndexSelectionPass {
377    fn name(&self) -> &str {
378        "IndexSelection"
379    }
380
381    fn apply(&self, query: QueryExpr) -> QueryExpr {
382        match query {
383            QueryExpr::Table(mut tq) => {
384                if let Some(filter) = effective_table_filter(&tq).as_ref() {
385                    if let Some(hint) = Self::analyze_filter(filter) {
386                        // Store index hint in expand metadata for executor
387                        let expand = tq.expand.get_or_insert_with(Default::default);
388                        expand.index_hint = Some(hint);
389                    }
390                }
391                QueryExpr::Table(tq)
392            }
393            other => other,
394        }
395    }
396
397    fn benefit(&self) -> u32 {
398        70
399    }
400}
401
402impl IndexSelectionPass {
403    /// Analyze a filter predicate and return the best index hint
404    fn analyze_filter(filter: &crate::storage::query::ast::Filter) -> Option<IndexHint> {
405        match filter {
406            // Equality on a single column → Hash index candidate
407            crate::storage::query::ast::Filter::Compare { field, op, .. }
408                if *op == crate::storage::query::ast::CompareOp::Eq =>
409            {
410                let col = Self::field_name(field);
411                Some(IndexHint {
412                    method: IndexHintMethod::Hash,
413                    column: col,
414                })
415            }
416            // Range predicates → B-tree candidate
417            crate::storage::query::ast::Filter::Compare {
418                field,
419                op:
420                    crate::storage::query::ast::CompareOp::Lt
421                    | crate::storage::query::ast::CompareOp::Le
422                    | crate::storage::query::ast::CompareOp::Gt
423                    | crate::storage::query::ast::CompareOp::Ge,
424                ..
425            } => {
426                let col = Self::field_name(field);
427                Some(IndexHint {
428                    method: IndexHintMethod::BTree,
429                    column: col,
430                })
431            }
432            // BETWEEN → B-tree candidate
433            crate::storage::query::ast::Filter::Between { field, .. } => {
434                let col = Self::field_name(field);
435                Some(IndexHint {
436                    method: IndexHintMethod::BTree,
437                    column: col,
438                })
439            }
440            // IN with few values → Bitmap candidate
441            crate::storage::query::ast::Filter::In { field, values } if values.len() <= 10 => {
442                let col = Self::field_name(field);
443                Some(IndexHint {
444                    method: IndexHintMethod::Bitmap,
445                    column: col,
446                })
447            }
448            // AND: pick the most selective hint from left or right
449            crate::storage::query::ast::Filter::And(left, right) => {
450                Self::analyze_filter(left).or_else(|| Self::analyze_filter(right))
451            }
452            _ => None,
453        }
454    }
455
456    fn field_name(field: &crate::storage::query::ast::FieldRef) -> String {
457        match field {
458            crate::storage::query::ast::FieldRef::TableColumn { column, .. } => column.clone(),
459            crate::storage::query::ast::FieldRef::NodeProperty { property, .. } => property.clone(),
460            crate::storage::query::ast::FieldRef::EdgeProperty { property, .. } => property.clone(),
461            crate::storage::query::ast::FieldRef::NodeId { alias } => {
462                format!("{}.id", alias)
463            }
464        }
465    }
466}
467
468/// Hint about which index method to prefer for a query
469#[derive(Debug, Clone)]
470pub struct IndexHint {
471    /// Preferred index method
472    pub method: IndexHintMethod,
473    /// Column the index applies to
474    pub column: String,
475}
476
477/// Which index method the optimizer recommends
478#[derive(Debug, Clone, Copy, PartialEq, Eq)]
479pub enum IndexHintMethod {
480    Hash,
481    BTree,
482    Bitmap,
483    Spatial,
484}
485
486/// Push LIMIT down through operations
487struct LimitPushdownPass;
488
489impl OptimizationPass for LimitPushdownPass {
490    fn name(&self) -> &str {
491        "LimitPushdown"
492    }
493
494    fn apply(&self, query: QueryExpr) -> QueryExpr {
495        match query {
496            QueryExpr::Join(jq) => {
497                // Can push limit through certain joins
498                let left = self.apply(*jq.left);
499                let right = self.apply(*jq.right);
500
501                QueryExpr::Join(JoinQuery {
502                    left: Box::new(left),
503                    right: Box::new(right),
504                    ..jq
505                })
506            }
507            other => other,
508        }
509    }
510
511    fn benefit(&self) -> u32 {
512        60
513    }
514}
515
516// =============================================================================
517// Helper Functions
518// =============================================================================
519
520fn swap_condition(
521    condition: crate::storage::query::ast::JoinCondition,
522) -> crate::storage::query::ast::JoinCondition {
523    crate::storage::query::ast::JoinCondition {
524        left_field: condition.right_field,
525        right_field: condition.left_field,
526    }
527}
528
529#[cfg(test)]
530mod tests {
531    use super::*;
532    use crate::storage::query::ast::{
533        DistanceMetric, FieldRef, FusionStrategy, JoinCondition, Projection, TableQuery,
534    };
535
536    fn make_table_query(name: &str) -> QueryExpr {
537        QueryExpr::Table(TableQuery {
538            table: name.to_string(),
539            source: None,
540            alias: Some(name.to_string()),
541            select_items: Vec::new(),
542            columns: vec![Projection::All],
543            where_expr: None,
544            filter: None,
545            group_by_exprs: Vec::new(),
546            group_by: Vec::new(),
547            having_expr: None,
548            having: None,
549            order_by: vec![],
550            limit: None,
551            limit_param: None,
552            offset: None,
553            offset_param: None,
554            expand: None,
555            as_of: None,
556        })
557    }
558
559    #[test]
560    fn test_optimizer_applies_passes() {
561        let optimizer = QueryOptimizer::new();
562        let query = make_table_query("hosts");
563
564        let (optimized, passes) = optimizer.optimize(query);
565        // Should at least attempt the passes
566        assert!(matches!(optimized, QueryExpr::Table(_)));
567    }
568
569    #[test]
570    fn test_join_reordering() {
571        let optimizer = QueryOptimizer::new();
572
573        let small = QueryExpr::Table(TableQuery {
574            table: "small".to_string(),
575            source: None,
576            alias: None,
577            select_items: Vec::new(),
578            columns: vec![Projection::All],
579            where_expr: None,
580            filter: None,
581            group_by_exprs: Vec::new(),
582            group_by: Vec::new(),
583            having_expr: None,
584            having: None,
585            order_by: vec![],
586            limit: Some(10), // Small table
587            limit_param: None,
588            offset: None,
589            offset_param: None,
590            expand: None,
591            as_of: None,
592        });
593
594        let large = QueryExpr::Table(TableQuery {
595            table: "large".to_string(),
596            source: None,
597            alias: None,
598            select_items: Vec::new(),
599            columns: vec![Projection::All],
600            where_expr: None,
601            filter: None,
602            group_by_exprs: Vec::new(),
603            group_by: Vec::new(),
604            having_expr: None,
605            having: None,
606            order_by: vec![],
607            limit: None, // Large table
608            limit_param: None,
609            offset: None,
610            offset_param: None,
611            expand: None,
612            as_of: None,
613        });
614
615        let join = QueryExpr::Join(JoinQuery {
616            left: Box::new(large.clone()),
617            right: Box::new(small.clone()),
618            join_type: JoinType::Inner,
619            on: JoinCondition {
620                left_field: FieldRef::TableColumn {
621                    table: "large".to_string(),
622                    column: "id".to_string(),
623                },
624                right_field: FieldRef::TableColumn {
625                    table: "small".to_string(),
626                    column: "id".to_string(),
627                },
628            },
629            filter: None,
630            order_by: Vec::new(),
631            limit: None,
632            offset: None,
633            return_items: Vec::new(),
634            return_: Vec::new(),
635        });
636
637        let (optimized, passes) = optimizer.optimize(join);
638
639        // Should have applied JoinReordering
640        if let QueryExpr::Join(jq) = optimized {
641            // Small table should now be on left (build side)
642            if let QueryExpr::Table(left) = *jq.left {
643                assert_eq!(left.table, "small");
644            }
645        }
646    }
647}