Skip to main content

velesdb_core/velesql/explain/
plan_builder.rs

1//! Plan construction logic for `VelesQL` EXPLAIN.
2//!
3//! Contains `impl QueryPlan` methods for building plans from SELECT statements,
4//! MATCH clauses, and related query structures.
5
6use std::collections::HashSet;
7
8use super::filter_strategy::{estimate_filter_stats, resolve_filter_strategy};
9use super::formatter;
10use super::node_stats;
11use super::types::{
12    AggregatePlan, FilterPlan, FilterStrategy, FusionInfo, GroupByPlan, IndexLookupPlan, IndexType,
13    JoinPlanNode, LimitPlan, MatchTraversalPlan, OffsetPlan, PlanNode, QueryPlan, SortPlan,
14    TableScanPlan, VectorSearchPlan,
15};
16use crate::collection::search::query::match_planner::{
17    CollectionStats, MatchExecutionStrategy, MatchQueryPlanner,
18};
19use crate::collection::stats::CollectionStats as CoreCollectionStats;
20use crate::velesql::ast::{Condition, LetBinding, SelectStatement, DEFAULT_SELECT_LIMIT};
21use crate::velesql::MatchClause;
22
23impl QueryPlan {
24    /// Creates a new query plan from a SELECT statement.
25    #[must_use]
26    pub fn from_select(stmt: &SelectStatement) -> Self {
27        Self::from_select_with_stats(stmt, &HashSet::new(), None)
28    }
29
30    /// Creates a new query plan from SELECT with known indexed metadata fields.
31    #[must_use]
32    pub fn from_select_with_indexed_fields(
33        stmt: &SelectStatement,
34        indexed_fields: &HashSet<String>,
35    ) -> Self {
36        Self::from_select_with_stats(stmt, indexed_fields, None)
37    }
38
39    /// Creates a query plan with access to calibrated collection statistics.
40    ///
41    /// When `stats` is `Some`, cost and filter-strategy decisions use the
42    /// calibrated `CostEstimator` pipeline (issue #471). When `None`, falls
43    /// back bit-for-bit to the heuristic path so legacy tests and callers
44    /// without a resolved collection keep working.
45    #[must_use]
46    pub fn from_select_with_stats(
47        stmt: &SelectStatement,
48        indexed_fields: &HashSet<String>,
49        stats: Option<&CoreCollectionStats>,
50    ) -> Self {
51        Self::build_select_plan(stmt, indexed_fields, stats, true)
52    }
53
54    /// Shared SELECT plan construction.
55    ///
56    /// `implicit_limit` controls whether the engine default
57    /// [`DEFAULT_SELECT_LIMIT`] is surfaced as a Limit node when the statement
58    /// has no explicit LIMIT. Plain SELECT statements pass `true`; MATCH and
59    /// compound queries pass `false` (no implicit limit applies to them).
60    fn build_select_plan(
61        stmt: &SelectStatement,
62        indexed_fields: &HashSet<String>,
63        stats: Option<&CoreCollectionStats>,
64        implicit_limit: bool,
65    ) -> Self {
66        let mut has_vector_search = false;
67        let mut filter_conditions = Vec::new();
68        let mut index_lookup = None;
69
70        if let Some(ref condition) = stmt.where_clause {
71            Self::analyze_condition(condition, &mut has_vector_search, &mut filter_conditions);
72            index_lookup = Self::extract_index_lookup(condition, indexed_fields);
73        }
74
75        let (mut nodes, index_used) = Self::build_scan_node(stmt, has_vector_search, index_lookup);
76        let filter_strategy = Self::append_filter_nodes_with_stats(
77            &mut nodes,
78            &filter_conditions,
79            stmt,
80            has_vector_search,
81            stats,
82        );
83        Self::append_post_filter_nodes(&mut nodes, stmt);
84        Self::push_pagination_nodes(&mut nodes, stmt, implicit_limit);
85
86        let mut plan = Self::assemble_plan_with_stats(
87            nodes,
88            index_used,
89            filter_strategy,
90            has_vector_search,
91            stats,
92        );
93        plan.with_options = Self::extract_with_options(stmt);
94        plan.fusion_info = Self::extract_fusion_info(stmt);
95        plan
96    }
97
98    /// Creates a full query plan from a `Query`, including LET bindings (issue #471).
99    #[must_use]
100    pub fn from_query(query: &crate::velesql::ast::Query) -> Self {
101        Self::from_query_with_stats(query, &HashSet::new(), None)
102    }
103
104    /// Creates a full query plan from a `Query`, with optional collection stats
105    /// for calibrated cost estimation (issue #471).
106    #[must_use]
107    pub fn from_query_with_stats(
108        query: &crate::velesql::ast::Query,
109        indexed_fields: &HashSet<String>,
110        stats: Option<&CoreCollectionStats>,
111    ) -> Self {
112        Self::from_query_with_all_stats(query, indexed_fields, stats, None)
113    }
114
115    /// Creates a full query plan from a `Query`, threading both calibrated
116    /// `CoreCollectionStats` (SELECT cost estimation) and graph
117    /// `CollectionStats` (MATCH traversal-strategy selection).
118    ///
119    /// MATCH queries route through [`Self::from_match`] so the EXPLAIN/exec
120    /// path emits a `MatchTraversal` node with a real strategy instead of a
121    /// bare `TableScan` mislabeled MATCH (backlog #14). `match_stats` is `None`
122    /// on the pure-AST path (default graph stats); the Database layer supplies
123    /// the live graph stats from `compute_match_collection_stats`.
124    #[must_use]
125    pub fn from_query_with_all_stats(
126        query: &crate::velesql::ast::Query,
127        indexed_fields: &HashSet<String>,
128        stats: Option<&CoreCollectionStats>,
129        match_stats: Option<&CollectionStats>,
130    ) -> Self {
131        let mut plan = if let Some(ref match_clause) = query.match_clause {
132            let default_stats = CollectionStats::default();
133            Self::from_match(match_clause, match_stats.unwrap_or(&default_stats))
134        } else {
135            // Compound queries have no implicit default LIMIT either.
136            let implicit_limit = query.compound.is_none();
137            Self::build_select_plan(&query.select, indexed_fields, stats, implicit_limit)
138        };
139        plan.let_bindings = Self::format_let_bindings(&query.let_bindings);
140        plan
141    }
142
143    /// Creates a new query plan from a MATCH clause (EPIC-046 US-004).
144    #[must_use]
145    pub fn from_match(match_clause: &MatchClause, stats: &CollectionStats) -> Self {
146        let strategy = MatchQueryPlanner::plan(match_clause, stats);
147        let strategy_explanation = MatchQueryPlanner::explain(&strategy);
148
149        let (start_labels, max_depth, has_similarity, similarity_threshold) =
150            Self::extract_strategy_info(&strategy);
151
152        let relationship_count = match_clause
153            .patterns
154            .first()
155            .map_or(0, |p| p.relationships.len());
156
157        let traversal = PlanNode::MatchTraversal(MatchTraversalPlan {
158            strategy: strategy_explanation,
159            start_labels,
160            max_depth,
161            relationship_count,
162            has_similarity,
163            similarity_threshold,
164        });
165
166        let mut nodes = vec![traversal];
167        if let Some(limit) = match_clause.return_clause.limit {
168            nodes.push(PlanNode::Limit(LimitPlan {
169                count: limit,
170                is_default: false,
171            }));
172        }
173
174        let index_used = if has_similarity {
175            Some(IndexType::Hnsw)
176        } else {
177            None
178        };
179
180        Self::assemble_plan_with_stats(
181            nodes,
182            index_used,
183            FilterStrategy::None,
184            has_similarity,
185            None,
186        )
187    }
188
189    /// Variant of `assemble_plan` with optional calibrated `CollectionStats`.
190    fn assemble_plan_with_stats(
191        mut nodes: Vec<PlanNode>,
192        index_used: Option<IndexType>,
193        filter_strategy: FilterStrategy,
194        has_vector_search: bool,
195        stats: Option<&CoreCollectionStats>,
196    ) -> Self {
197        let root = if nodes.len() == 1 {
198            nodes.swap_remove(0)
199        } else {
200            PlanNode::Sequence(nodes)
201        };
202        let estimated_cost_ms = node_stats::estimate_cost(&root, has_vector_search, stats);
203        Self {
204            root,
205            estimated_cost_ms,
206            index_used,
207            filter_strategy,
208            with_options: Vec::new(),
209            let_bindings: Vec::new(),
210            fusion_info: None,
211            cache_hit: None,
212            plan_reuse_count: None,
213        }
214    }
215
216    /// Default `ef_search` when the WITH clause does not specify one.
217    const DEFAULT_EF_SEARCH: u32 = 100;
218
219    /// Builds the primary scan node based on search type.
220    fn build_scan_node(
221        stmt: &SelectStatement,
222        has_vector_search: bool,
223        index_lookup: Option<(String, String)>,
224    ) -> (Vec<PlanNode>, Option<IndexType>) {
225        let mut nodes = Vec::new();
226        let index_used;
227
228        if has_vector_search {
229            index_used = Some(IndexType::Hnsw);
230            let candidates =
231                u32::try_from(stmt.limit.unwrap_or(DEFAULT_SELECT_LIMIT)).unwrap_or(u32::MAX);
232            let ef_search = Self::resolve_ef_search(stmt);
233            nodes.push(PlanNode::VectorSearch(VectorSearchPlan {
234                collection: stmt.from.clone(),
235                ef_search,
236                candidates,
237            }));
238        } else if let Some((property, value)) = index_lookup {
239            index_used = Some(IndexType::Property);
240            nodes.push(PlanNode::IndexLookup(IndexLookupPlan {
241                label: stmt.from.clone(),
242                property,
243                value,
244            }));
245        } else {
246            index_used = None;
247            nodes.push(PlanNode::TableScan(TableScanPlan {
248                collection: stmt.from.clone(),
249            }));
250        }
251
252        (nodes, index_used)
253    }
254
255    /// Reads `ef_search` from the WITH clause, falling back to [`Self::DEFAULT_EF_SEARCH`].
256    #[allow(clippy::cast_possible_truncation)]
257    fn resolve_ef_search(stmt: &SelectStatement) -> u32 {
258        stmt.with_clause
259            .as_ref()
260            .and_then(crate::velesql::ast::WithClause::get_ef_search)
261            .map_or(Self::DEFAULT_EF_SEARCH, |v| v as u32)
262    }
263
264    /// Extracts WITH clause options as display pairs (issue #471).
265    fn extract_with_options(stmt: &SelectStatement) -> Vec<(String, String)> {
266        let Some(ref wc) = stmt.with_clause else {
267            return Vec::new();
268        };
269        wc.options
270            .iter()
271            .map(|opt| (opt.key.clone(), formatter::format_with_value(&opt.value)))
272            .collect()
273    }
274
275    /// Extracts FUSION clause info for EXPLAIN display (issue #471).
276    fn extract_fusion_info(stmt: &SelectStatement) -> Option<FusionInfo> {
277        let fc = stmt.fusion_clause.as_ref()?;
278        let strategy = match fc.strategy {
279            crate::velesql::ast::FusionStrategyType::Rrf => "RRF",
280            crate::velesql::ast::FusionStrategyType::Weighted => "Weighted",
281            crate::velesql::ast::FusionStrategyType::Maximum => "Maximum",
282            crate::velesql::ast::FusionStrategyType::Rsf => "RSF",
283            crate::velesql::ast::FusionStrategyType::Average => "Average",
284        };
285        let weights = Self::format_fusion_weights(fc);
286        Some(FusionInfo {
287            strategy: strategy.to_string(),
288            k: fc.k,
289            weights,
290        })
291    }
292
293    /// Formats fusion weights into a human-readable string.
294    fn format_fusion_weights(fc: &crate::velesql::ast::FusionClause) -> Option<String> {
295        let mut parts = Vec::new();
296        if let Some(vw) = fc.vector_weight {
297            parts.push(format!("vector={vw}"));
298        }
299        if let Some(gw) = fc.graph_weight {
300            parts.push(format!("graph={gw}"));
301        }
302        if let Some(dw) = fc.dense_weight {
303            parts.push(format!("dense={dw}"));
304        }
305        if let Some(sw) = fc.sparse_weight {
306            parts.push(format!("sparse={sw}"));
307        }
308        if parts.is_empty() {
309            None
310        } else {
311            Some(parts.join(", "))
312        }
313    }
314
315    /// Formats LET bindings as `"name = expr"` strings (issue #471).
316    fn format_let_bindings(bindings: &[LetBinding]) -> Vec<String> {
317        bindings
318            .iter()
319            .map(|b| format!("{} = {}", b.name, b.expr))
320            .collect()
321    }
322
323    /// Variant of `append_filter_nodes` with access to the calibrated
324    /// `CostEstimator` (issue #471).
325    ///
326    /// Selectivity and filter strategy use histogram data when `stats` is
327    /// `Some`. When `None`, the historical heuristic (selectivity from
328    /// condition count, 0.1 threshold) is preserved bit-for-bit.
329    fn append_filter_nodes_with_stats(
330        nodes: &mut Vec<PlanNode>,
331        filter_conditions: &[String],
332        stmt: &SelectStatement,
333        has_vector_search: bool,
334        stats: Option<&CoreCollectionStats>,
335    ) -> FilterStrategy {
336        let mut filter_strategy = FilterStrategy::None;
337
338        if !filter_conditions.is_empty() {
339            let heuristic_fallback = Self::estimate_selectivity(filter_conditions);
340            let (selectivity, estimation_method, estimated_rows) =
341                estimate_filter_stats(stmt, heuristic_fallback, stats);
342
343            // Reason: plan_builder owns stmt so the real ef_search/candidates
344            // are the same values used in `build_scan_node` above
345            // (Devin finding 4). These values drive the pre/post-filter cost
346            // comparison so it reflects the user's actual WITH clause instead
347            // of a fixed k = 10.
348            let ef_search = Self::resolve_ef_search(stmt);
349            let candidates =
350                u32::try_from(stmt.limit.unwrap_or(DEFAULT_SELECT_LIMIT)).unwrap_or(u32::MAX);
351
352            filter_strategy = resolve_filter_strategy(
353                selectivity,
354                has_vector_search,
355                ef_search,
356                candidates,
357                stats,
358            );
359
360            nodes.push(PlanNode::Filter(FilterPlan {
361                conditions: filter_conditions.join(" AND "),
362                selectivity,
363                estimated_rows,
364                estimation_method,
365            }));
366        }
367
368        filter_strategy
369    }
370
371    /// Appends post-filter pipeline nodes (JOIN, GROUP BY, aggregation, ORDER
372    /// BY) in the order they execute, mirroring the previous server-side
373    /// reconstruction so the single-sourced plan is step-compatible.
374    fn append_post_filter_nodes(nodes: &mut Vec<PlanNode>, stmt: &SelectStatement) {
375        for join in &stmt.joins {
376            nodes.push(PlanNode::Join(JoinPlanNode {
377                join_type: format!("{:?}", join.join_type),
378                table: join.table.clone(),
379            }));
380        }
381        if let Some(ref group_by) = stmt.group_by {
382            nodes.push(PlanNode::GroupBy(GroupByPlan {
383                columns: group_by.columns.clone(),
384            }));
385        }
386        let functions = Self::aggregate_function_names(&stmt.columns);
387        if !functions.is_empty() {
388            nodes.push(PlanNode::Aggregate(AggregatePlan { functions }));
389        }
390        if let Some(ref order_by) = stmt.order_by {
391            let keys = order_by
392                .iter()
393                .map(|o| {
394                    let (col, dir) = o.to_display_pair();
395                    format!("{col} {dir}")
396                })
397                .collect();
398            nodes.push(PlanNode::Sort(SortPlan { keys }));
399        }
400    }
401
402    /// Returns the aggregate function names in SELECT-list order, or an empty
403    /// vec when the projection has no aggregates.
404    fn aggregate_function_names(columns: &crate::velesql::ast::SelectColumns) -> Vec<String> {
405        use crate::velesql::ast::SelectColumns;
406        let aggregations = match columns {
407            SelectColumns::Aggregations(aggs) => aggs.as_slice(),
408            SelectColumns::Mixed { aggregations, .. } => aggregations.as_slice(),
409            _ => &[],
410        };
411        aggregations
412            .iter()
413            .map(|a| format!("{:?}", a.function_type))
414            .collect()
415    }
416
417    /// Appends the OFFSET (when present) and LIMIT pagination nodes last, so the
418    /// pipeline order is scan → filter → joins → group → aggregate → sort →
419    /// offset → limit.
420    fn push_pagination_nodes(
421        nodes: &mut Vec<PlanNode>,
422        stmt: &SelectStatement,
423        implicit_limit: bool,
424    ) {
425        if let Some(offset) = stmt.offset {
426            nodes.push(PlanNode::Offset(OffsetPlan { count: offset }));
427        }
428        Self::push_limit_node(nodes, stmt, implicit_limit);
429    }
430
431    /// Pushes the Limit node for a statement.
432    ///
433    /// Without an explicit LIMIT, plain SELECT statements (`implicit_limit ==
434    /// true`) surface the engine default [`DEFAULT_SELECT_LIMIT`] so EXPLAIN
435    /// matches what execution actually returns. MATCH and compound queries
436    /// (`implicit_limit == false`) keep their unlimited semantics: no node.
437    fn push_limit_node(nodes: &mut Vec<PlanNode>, stmt: &SelectStatement, implicit_limit: bool) {
438        let (count, is_default) = match (stmt.limit, implicit_limit) {
439            (Some(limit), _) => (limit, false),
440            (None, true) => (DEFAULT_SELECT_LIMIT, true),
441            (None, false) => return,
442        };
443        nodes.push(PlanNode::Limit(LimitPlan { count, is_default }));
444    }
445
446    /// Analyzes a condition to extract vector search and filter info.
447    fn analyze_condition(
448        condition: &Condition,
449        has_vector_search: &mut bool,
450        filter_conditions: &mut Vec<String>,
451    ) {
452        match condition {
453            Condition::VectorSearch(_)
454            | Condition::VectorFusedSearch(_)
455            | Condition::SparseVectorSearch(_)
456            | Condition::Similarity(_) => {
457                *has_vector_search = true;
458            }
459            Condition::And(left, right) | Condition::Or(left, right) => {
460                Self::analyze_condition(left, has_vector_search, filter_conditions);
461                Self::analyze_condition(right, has_vector_search, filter_conditions);
462            }
463            Condition::Not(inner) | Condition::Group(inner) => {
464                Self::analyze_condition(inner, has_vector_search, filter_conditions);
465            }
466            leaf => {
467                if let Some(desc) = Self::describe_leaf_condition(leaf) {
468                    filter_conditions.push(desc);
469                }
470            }
471        }
472    }
473
474    /// Renders a non-composite condition as a short human-readable string for
475    /// the EXPLAIN plan filter list. Returns `None` for vector/composite
476    /// variants — those are handled in [`analyze_condition`] itself.
477    fn describe_leaf_condition(condition: &Condition) -> Option<String> {
478        let desc = match condition {
479            Condition::Comparison(cmp) => {
480                format!("{} {} ?", cmp.column, cmp.operator.as_str())
481            }
482            Condition::In(inc) => {
483                let op = if inc.negated { "NOT IN" } else { "IN" };
484                format!("{} {op} (...)", inc.column)
485            }
486            Condition::Between(btw) => format!("{} BETWEEN ? AND ?", btw.column),
487            Condition::Like(lk) => format!("{} LIKE ?", lk.column),
488            Condition::IsNull(isn) => {
489                let op = if isn.is_null {
490                    "IS NULL"
491                } else {
492                    "IS NOT NULL"
493                };
494                format!("{} {op}", isn.column)
495            }
496            Condition::Match(m) => format!("{} MATCH ?", m.column),
497            Condition::ContainsText(ct) => format!("{} CONTAINS_TEXT ?", ct.column),
498            Condition::GraphMatch(_) => "MATCH (...)".to_string(),
499            Condition::Contains(cc) => {
500                let mode_str = match cc.mode {
501                    crate::velesql::ContainsMode::Single => "CONTAINS",
502                    crate::velesql::ContainsMode::Any => "CONTAINS ANY",
503                    crate::velesql::ContainsMode::All => "CONTAINS ALL",
504                };
505                format!("{} {mode_str} ?", cc.column)
506            }
507            Condition::GeoDistance(gd) => format!(
508                "GEO_DISTANCE({}, {}, {}) {} ?",
509                gd.column,
510                gd.lat,
511                gd.lng,
512                gd.operator.as_str()
513            ),
514            Condition::GeoBbox(gb) => format!("GEO_BBOX({}, ...)", gb.column),
515            _ => return None,
516        };
517        Some(desc)
518    }
519
520    fn extract_index_lookup(
521        condition: &Condition,
522        indexed_fields: &HashSet<String>,
523    ) -> Option<(String, String)> {
524        if let Condition::Comparison(cmp) = condition {
525            if cmp.operator == crate::velesql::CompareOp::Eq && indexed_fields.contains(&cmp.column)
526            {
527                return Some((cmp.column.clone(), format!("{:?}", cmp.value)));
528            }
529        }
530        if let Condition::In(inc) = condition {
531            if indexed_fields.contains(&inc.column) {
532                let op = if inc.negated { "NOT IN" } else { "IN" };
533                return Some((inc.column.clone(), format!("{op} (...)")));
534            }
535        }
536        None
537    }
538
539    /// Estimates selectivity (placeholder - would need statistics in production).
540    pub(crate) fn estimate_selectivity(conditions: &[String]) -> f64 {
541        node_stats::estimate_selectivity(conditions, None)
542    }
543
544    /// Returns the heuristic cost for a single plan node.
545    #[cfg(test)]
546    pub(crate) fn node_cost(node: &PlanNode) -> f64 {
547        node_stats::node_cost(node)
548    }
549
550    /// Extracts traversal parameters from a `MatchExecutionStrategy`.
551    fn extract_strategy_info(
552        strategy: &MatchExecutionStrategy,
553    ) -> (Vec<String>, u32, bool, Option<f32>) {
554        match strategy {
555            MatchExecutionStrategy::GraphFirst {
556                start_labels,
557                max_depth,
558            } => (start_labels.clone(), *max_depth, false, None),
559            MatchExecutionStrategy::VectorFirst { threshold, .. } => {
560                (Vec::new(), 1, true, Some(*threshold))
561            }
562            MatchExecutionStrategy::Parallel {
563                graph_hint,
564                vector_hint,
565            } => {
566                let (labels, depth) = match graph_hint.as_ref() {
567                    MatchExecutionStrategy::GraphFirst {
568                        start_labels,
569                        max_depth,
570                    } => (start_labels.clone(), *max_depth),
571                    _ => (Vec::new(), 1),
572                };
573                let threshold = match vector_hint.as_ref() {
574                    MatchExecutionStrategy::VectorFirst { threshold, .. } => Some(*threshold),
575                    _ => None,
576                };
577                (labels, depth, true, threshold)
578            }
579        }
580    }
581}