Skip to main content

reddb_server/storage/query/planner/
cost.rs

1//! Cost Estimation
2//!
3//! Cost-based query plan selection with cardinality estimation.
4//!
5//! # Cost Model
6//!
7//! - **CPU cost**: Computation overhead
8//! - **IO cost**: Disk/memory access
9//! - **Network cost**: For distributed queries
10//! - **Memory cost**: Working memory required
11
12use std::sync::Arc;
13
14use super::stats_provider::{NullProvider, StatsProvider};
15use reddb_rql::ast::{
16    CompareOp, FieldRef, Filter as AstFilter, GraphQuery, HybridQuery, JoinQuery, JoinType,
17    PathQuery, QueryExpr, TableQuery, VectorQuery,
18};
19use reddb_types::Value;
20
21/// Cardinality estimate for a query result
22#[derive(Debug, Clone, Default)]
23pub struct CardinalityEstimate {
24    /// Estimated row/record count
25    pub rows: f64,
26    /// Selectivity factor (0.0 - 1.0)
27    pub selectivity: f64,
28    /// Confidence in the estimate (0.0 - 1.0)
29    pub confidence: f64,
30}
31
32impl CardinalityEstimate {
33    /// Create a new cardinality estimate
34    pub fn new(rows: f64, selectivity: f64) -> Self {
35        Self {
36            rows,
37            selectivity,
38            confidence: 1.0,
39        }
40    }
41
42    /// Full table scan estimate
43    pub fn full_scan(table_size: f64) -> Self {
44        Self {
45            rows: table_size,
46            selectivity: 1.0,
47            confidence: 1.0,
48        }
49    }
50
51    /// Apply a filter to reduce cardinality
52    pub fn with_filter(mut self, filter_selectivity: f64) -> Self {
53        self.rows *= filter_selectivity;
54        self.selectivity *= filter_selectivity;
55        self.confidence *= 0.9; // Reduce confidence with each estimate
56        self
57    }
58}
59
60/// Cost of executing a query plan.
61///
62/// Mirrors PostgreSQL's `Cost` split: `startup_cost` is the work needed
63/// before the **first** row can be produced, `total` is the work to
64/// produce the **last** row. Both are reported so plan selection can
65/// pick a low-startup plan when a small `LIMIT` is in scope, even if
66/// total work is higher.
67///
68/// See `src/storage/query/planner/README.md` § Invariant 1.
69#[derive(Debug, Clone, Default)]
70pub struct PlanCost {
71    /// CPU computation cost
72    pub cpu: f64,
73    /// IO access cost
74    pub io: f64,
75    /// Network transfer cost (for distributed)
76    pub network: f64,
77    /// Memory requirement
78    pub memory: f64,
79    /// Cost to produce the **first** row.
80    ///
81    /// Zero for streaming operators (full scan, index scan, filter over
82    /// scan). Equal to `total` for blocking operators (sort, hash join
83    /// build side, materialize).
84    pub startup_cost: f64,
85    /// Cost to produce the **last** row.
86    pub total: f64,
87}
88
89impl PlanCost {
90    /// Create a new cost estimate with `startup_cost = 0` (streaming).
91    pub fn new(cpu: f64, io: f64, memory: f64) -> Self {
92        let total = cpu + io * 10.0 + memory * 0.1; // IO is expensive
93        Self {
94            cpu,
95            io,
96            network: 0.0,
97            memory,
98            startup_cost: 0.0,
99            total,
100        }
101    }
102
103    /// Create a cost with an explicit `startup_cost`. Use for blocking
104    /// operators (sort, hash build) and for index point lookups whose
105    /// first-row cost is non-zero.
106    pub fn with_startup(cpu: f64, io: f64, memory: f64, startup_cost: f64) -> Self {
107        let total = cpu + io * 10.0 + memory * 0.1;
108        Self {
109            cpu,
110            io,
111            network: 0.0,
112            memory,
113            startup_cost: startup_cost.max(0.0),
114            total: total.max(startup_cost),
115        }
116    }
117
118    /// Compose two costs in a **pipelined** fashion: the second operator
119    /// consumes the first as a stream.
120    ///
121    /// Both `startup_cost` and `total` add together. Use for filter
122    /// over scan, projection over filter, etc.
123    pub fn combine_pipelined(&self, other: &PlanCost) -> PlanCost {
124        PlanCost {
125            cpu: self.cpu + other.cpu,
126            io: self.io + other.io,
127            network: self.network + other.network,
128            memory: self.memory.max(other.memory),
129            startup_cost: self.startup_cost + other.startup_cost,
130            total: self.total + other.total,
131        }
132    }
133
134    /// Compose two costs where `self` must be **fully consumed** before
135    /// `blocker` can produce its first row.
136    ///
137    /// `self.total` flows into `blocker.startup_cost`. Use for sort,
138    /// hash build, materialise — anything that has to drain its input
139    /// before emitting.
140    pub fn combine_blocking(&self, blocker: &PlanCost) -> PlanCost {
141        PlanCost {
142            cpu: self.cpu + blocker.cpu,
143            io: self.io + blocker.io,
144            network: self.network + blocker.network,
145            memory: self.memory.max(blocker.memory),
146            startup_cost: self.total + blocker.startup_cost,
147            total: self.total + blocker.total,
148        }
149    }
150
151    /// Backwards-compatible alias for [`combine_pipelined`].
152    ///
153    /// New code should prefer `combine_pipelined` / `combine_blocking`
154    /// explicitly. This is kept so existing callers compile unchanged.
155    pub fn combine(&self, other: &PlanCost) -> PlanCost {
156        self.combine_pipelined(other)
157    }
158
159    /// Scale cost by a factor (cardinality multiplier, etc.).
160    pub fn scale(&self, factor: f64) -> PlanCost {
161        PlanCost {
162            cpu: self.cpu * factor,
163            io: self.io * factor,
164            network: self.network * factor,
165            memory: self.memory,             // Memory doesn't scale linearly
166            startup_cost: self.startup_cost, // startup is per-plan, not per-row
167            total: self.total * factor,
168        }
169    }
170
171    /// Plan-comparison helper. Picks `Less` when `self` should be
172    /// preferred over `other`.
173    ///
174    /// When `limit` is `Some(k)` and `k < 0.1 * cardinality`, the
175    /// comparison switches from `total` to `startup_cost` — the client
176    /// will only consume a small slice of the result, so we want the
177    /// plan that produces the first rows fastest even if the full scan
178    /// would be more expensive.
179    ///
180    /// This mirrors PostgreSQL's `compare_path_costs_fuzzily` logic for
181    /// `STARTUP` vs `TOTAL` cost ordering.
182    pub fn prefer_over(
183        &self,
184        other: &PlanCost,
185        limit: Option<u64>,
186        cardinality: f64,
187    ) -> std::cmp::Ordering {
188        let use_startup = matches!(limit, Some(k) if (k as f64) < 0.1 * cardinality.max(1.0));
189        let (lhs, rhs) = if use_startup {
190            (self.startup_cost, other.startup_cost)
191        } else {
192            (self.total, other.total)
193        };
194        lhs.partial_cmp(&rhs).unwrap_or(std::cmp::Ordering::Equal)
195    }
196}
197
198/// Statistics about a table or graph
199#[derive(Debug, Clone, Default)]
200pub struct TableStats {
201    /// Total row count
202    pub row_count: u64,
203    /// Average row size in bytes
204    pub avg_row_size: u32,
205    /// Number of pages
206    pub page_count: u64,
207    /// Column statistics
208    pub columns: Vec<ColumnStats>,
209}
210
211/// Statistics about a column
212#[derive(Debug, Clone, Default)]
213pub struct ColumnStats {
214    /// Column name
215    pub name: String,
216    /// Number of distinct values
217    pub distinct_count: u64,
218    /// Null count
219    pub null_count: u64,
220    /// Minimum value (if orderable)
221    pub min_value: Option<String>,
222    /// Maximum value (if orderable)
223    pub max_value: Option<String>,
224    /// Has index
225    pub has_index: bool,
226}
227
228/// Cost estimator for query plans
229pub struct CostEstimator {
230    /// Default table row count estimate
231    default_row_count: f64,
232    /// Cost per row scan
233    row_scan_cost: f64,
234    /// Cost per index lookup
235    index_lookup_cost: f64,
236    /// Cost per hash join probe
237    hash_probe_cost: f64,
238    /// Cost per nested loop iteration
239    nested_loop_cost: f64,
240    /// Cost per graph edge traversal
241    edge_traversal_cost: f64,
242    /// Optional stats provider. When present, `estimate_table_cardinality`
243    /// and the selectivity computation use real per-table / per-column
244    /// statistics instead of the heuristic constants. `None` preserves the
245    /// legacy behaviour so callers can adopt stats incrementally.
246    stats: Arc<dyn StatsProvider>,
247}
248
249impl CostEstimator {
250    /// Create a new cost estimator with default parameters and a
251    /// [`NullProvider`] — no real stats, pure heuristic mode.
252    pub fn new() -> Self {
253        Self {
254            default_row_count: 1000.0,
255            row_scan_cost: 1.0,
256            index_lookup_cost: 0.1,
257            hash_probe_cost: 0.5,
258            nested_loop_cost: 2.0,
259            edge_traversal_cost: 1.5,
260            stats: Arc::new(NullProvider),
261        }
262    }
263
264    /// Create a cost estimator that consults `provider` for real table /
265    /// column / index statistics. Any lookups the provider cannot satisfy
266    /// fall back to the heuristic path automatically.
267    pub fn with_stats(provider: Arc<dyn StatsProvider>) -> Self {
268        Self {
269            stats: provider,
270            ..Self::new()
271        }
272    }
273
274    /// Swap the stats provider on an existing estimator. Useful for tests
275    /// and for planners that build one `CostEstimator` and repoint it at
276    /// per-query snapshots.
277    pub fn set_stats(&mut self, provider: Arc<dyn StatsProvider>) {
278        self.stats = provider;
279    }
280
281    /// Estimate cost of a query expression
282    pub fn estimate(&self, query: &QueryExpr) -> PlanCost {
283        match query {
284            QueryExpr::Table(tq) => self.estimate_table(tq),
285            QueryExpr::Graph(gq) => self.estimate_graph(gq),
286            QueryExpr::Join(jq) => self.estimate_join(jq),
287            QueryExpr::Path(pq) => self.estimate_path(pq),
288            QueryExpr::Vector(vq) => self.estimate_vector(vq),
289            QueryExpr::Hybrid(hq) => self.estimate_hybrid(hq),
290            QueryExpr::Explain(explain) => self.estimate(&explain.inner),
291            // DML/DDL statements have minimal query cost
292            QueryExpr::Insert(_)
293            | QueryExpr::Update(_)
294            | QueryExpr::Delete(_)
295            | QueryExpr::Function(_)
296            | QueryExpr::CreateTable(_)
297            | QueryExpr::CreateCollection(_)
298            | QueryExpr::CreateVector(_)
299            | QueryExpr::DropTable(_)
300            | QueryExpr::DropGraph(_)
301            | QueryExpr::DropVector(_)
302            | QueryExpr::DropDocument(_)
303            | QueryExpr::DropKv(_)
304            | QueryExpr::DropCollection(_)
305            | QueryExpr::Truncate(_)
306            | QueryExpr::AlterTable(_)
307            | QueryExpr::CreateVcsRef(_)
308            | QueryExpr::DropVcsRef(_)
309            | QueryExpr::ForkStore(_)
310            | QueryExpr::PromoteFork(_)
311            | QueryExpr::DropFork(_)
312            | QueryExpr::VcsCommand(_)
313            | QueryExpr::GraphCommand(_)
314            | QueryExpr::SearchCommand(_)
315            | QueryExpr::CreateIndex(_)
316            | QueryExpr::DropIndex(_)
317            | QueryExpr::ProbabilisticCommand(_)
318            | QueryExpr::Ask(_)
319            | QueryExpr::SetConfig { .. }
320            | QueryExpr::ShowConfig { .. }
321            | QueryExpr::Scrub { .. }
322            | QueryExpr::SetSecret { .. }
323            | QueryExpr::DeleteSecret { .. }
324            | QueryExpr::SetKv { .. }
325            | QueryExpr::DeleteKv { .. }
326            | QueryExpr::ShowSecrets { .. }
327            | QueryExpr::SetTenant(_)
328            | QueryExpr::ShowTenant
329            | QueryExpr::CreateTimeSeries(_)
330            | QueryExpr::CreateMetric(_)
331            | QueryExpr::AlterMetric(_)
332            | QueryExpr::CreateSlo(_)
333            | QueryExpr::DropTimeSeries(_)
334            | QueryExpr::CreateQueue(_)
335            | QueryExpr::AlterQueue(_)
336            | QueryExpr::DropQueue(_)
337            | QueryExpr::QueueSelect(_)
338            | QueryExpr::QueueCommand(_)
339            | QueryExpr::KvCommand(_)
340            | QueryExpr::ConfigCommand(_)
341            | QueryExpr::CreateTree(_)
342            | QueryExpr::DropTree(_)
343            | QueryExpr::TreeCommand(_)
344            | QueryExpr::ExplainAlter(_)
345            | QueryExpr::TransactionControl(_)
346            | QueryExpr::MaintenanceCommand(_)
347            | QueryExpr::CreateSchema(_)
348            | QueryExpr::DropSchema(_)
349            | QueryExpr::CreateSequence(_)
350            | QueryExpr::DropSequence(_)
351            | QueryExpr::CopyFrom(_)
352            | QueryExpr::CreateView(_)
353            | QueryExpr::DropView(_)
354            | QueryExpr::RefreshMaterializedView(_)
355            | QueryExpr::CreatePolicy(_)
356            | QueryExpr::DropPolicy(_)
357            | QueryExpr::CreateServer(_)
358            | QueryExpr::DropServer(_)
359            | QueryExpr::CreateForeignTable(_)
360            | QueryExpr::DropForeignTable(_)
361            | QueryExpr::Grant(_)
362            | QueryExpr::Revoke(_)
363            | QueryExpr::AlterUser(_)
364            | QueryExpr::CreateUser(_)
365            | QueryExpr::CreateIamPolicy { .. }
366            | QueryExpr::DropIamPolicy { .. }
367            | QueryExpr::AttachPolicy { .. }
368            | QueryExpr::DetachPolicy { .. }
369            | QueryExpr::ShowPolicies { .. }
370            | QueryExpr::ShowEffectivePermissions { .. }
371            | QueryExpr::RankOf(_)
372            | QueryExpr::ApproxRankOf(_)
373            | QueryExpr::RankRange(_)
374            | QueryExpr::SimulatePolicy { .. }
375            | QueryExpr::LintPolicy { .. }
376            | QueryExpr::MigratePolicyMode { .. }
377            | QueryExpr::CreateMigration(_)
378            | QueryExpr::ApplyMigration(_)
379            | QueryExpr::RollbackMigration(_)
380            | QueryExpr::ExplainMigration(_)
381            | QueryExpr::EventsBackfill(_)
382            | QueryExpr::EventsBackfillStatus { .. } => PlanCost::new(1.0, 1.0, 0.0),
383        }
384    }
385
386    /// Estimate cardinality of a query result
387    pub fn estimate_cardinality(&self, query: &QueryExpr) -> CardinalityEstimate {
388        match query {
389            QueryExpr::Table(tq) => self.estimate_table_cardinality(tq),
390            QueryExpr::Graph(gq) => self.estimate_graph_cardinality(gq),
391            QueryExpr::Join(jq) => self.estimate_join_cardinality(jq),
392            QueryExpr::Path(pq) => self.estimate_path_cardinality(pq),
393            QueryExpr::Vector(vq) => self.estimate_vector_cardinality(vq),
394            QueryExpr::Hybrid(hq) => self.estimate_hybrid_cardinality(hq),
395            QueryExpr::Explain(explain) => self.estimate_cardinality(&explain.inner),
396            // DML/DDL/Command statements return affected-row count or nothing
397            QueryExpr::Insert(_)
398            | QueryExpr::Update(_)
399            | QueryExpr::Delete(_)
400            | QueryExpr::Function(_)
401            | QueryExpr::CreateTable(_)
402            | QueryExpr::CreateCollection(_)
403            | QueryExpr::CreateVector(_)
404            | QueryExpr::DropTable(_)
405            | QueryExpr::DropGraph(_)
406            | QueryExpr::DropVector(_)
407            | QueryExpr::DropDocument(_)
408            | QueryExpr::DropKv(_)
409            | QueryExpr::DropCollection(_)
410            | QueryExpr::Truncate(_)
411            | QueryExpr::AlterTable(_)
412            | QueryExpr::CreateVcsRef(_)
413            | QueryExpr::DropVcsRef(_)
414            | QueryExpr::ForkStore(_)
415            | QueryExpr::PromoteFork(_)
416            | QueryExpr::DropFork(_)
417            | QueryExpr::VcsCommand(_)
418            | QueryExpr::GraphCommand(_)
419            | QueryExpr::SearchCommand(_)
420            | QueryExpr::CreateIndex(_)
421            | QueryExpr::DropIndex(_)
422            | QueryExpr::ProbabilisticCommand(_)
423            | QueryExpr::Ask(_)
424            | QueryExpr::SetConfig { .. }
425            | QueryExpr::ShowConfig { .. }
426            | QueryExpr::Scrub { .. }
427            | QueryExpr::SetSecret { .. }
428            | QueryExpr::DeleteSecret { .. }
429            | QueryExpr::SetKv { .. }
430            | QueryExpr::DeleteKv { .. }
431            | QueryExpr::ShowSecrets { .. }
432            | QueryExpr::SetTenant(_)
433            | QueryExpr::ShowTenant
434            | QueryExpr::CreateTimeSeries(_)
435            | QueryExpr::CreateMetric(_)
436            | QueryExpr::AlterMetric(_)
437            | QueryExpr::CreateSlo(_)
438            | QueryExpr::DropTimeSeries(_)
439            | QueryExpr::CreateQueue(_)
440            | QueryExpr::AlterQueue(_)
441            | QueryExpr::DropQueue(_)
442            | QueryExpr::QueueSelect(_)
443            | QueryExpr::QueueCommand(_)
444            | QueryExpr::KvCommand(_)
445            | QueryExpr::ConfigCommand(_)
446            | QueryExpr::CreateTree(_)
447            | QueryExpr::DropTree(_)
448            | QueryExpr::TreeCommand(_)
449            | QueryExpr::ExplainAlter(_)
450            | QueryExpr::TransactionControl(_)
451            | QueryExpr::MaintenanceCommand(_)
452            | QueryExpr::CreateSchema(_)
453            | QueryExpr::DropSchema(_)
454            | QueryExpr::CreateSequence(_)
455            | QueryExpr::DropSequence(_)
456            | QueryExpr::CopyFrom(_)
457            | QueryExpr::CreateView(_)
458            | QueryExpr::DropView(_)
459            | QueryExpr::RefreshMaterializedView(_)
460            | QueryExpr::CreatePolicy(_)
461            | QueryExpr::DropPolicy(_)
462            | QueryExpr::CreateServer(_)
463            | QueryExpr::DropServer(_)
464            | QueryExpr::CreateForeignTable(_)
465            | QueryExpr::DropForeignTable(_)
466            | QueryExpr::Grant(_)
467            | QueryExpr::Revoke(_)
468            | QueryExpr::AlterUser(_)
469            | QueryExpr::CreateUser(_)
470            | QueryExpr::CreateIamPolicy { .. }
471            | QueryExpr::DropIamPolicy { .. }
472            | QueryExpr::AttachPolicy { .. }
473            | QueryExpr::DetachPolicy { .. }
474            | QueryExpr::ShowPolicies { .. }
475            | QueryExpr::ShowEffectivePermissions { .. }
476            | QueryExpr::RankOf(_)
477            | QueryExpr::ApproxRankOf(_)
478            | QueryExpr::RankRange(_)
479            | QueryExpr::SimulatePolicy { .. }
480            | QueryExpr::LintPolicy { .. }
481            | QueryExpr::MigratePolicyMode { .. }
482            | QueryExpr::CreateMigration(_)
483            | QueryExpr::ApplyMigration(_)
484            | QueryExpr::RollbackMigration(_)
485            | QueryExpr::ExplainMigration(_)
486            | QueryExpr::EventsBackfill(_)
487            | QueryExpr::EventsBackfillStatus { .. } => CardinalityEstimate::new(1.0, 1.0),
488        }
489    }
490
491    // =========================================================================
492    // Table Query Estimation
493    // =========================================================================
494
495    fn estimate_table(&self, query: &TableQuery) -> PlanCost {
496        let cardinality = self.estimate_table_cardinality(query);
497
498        let cpu = cardinality.rows * self.row_scan_cost;
499
500        // I/O cost: use Mackert-Lohman when we have index stats and a filter
501        // column with a known index; otherwise fall back to the naive heuristic.
502        let io = self.estimate_table_io(query, cardinality.rows);
503
504        let memory = cardinality.rows * 100.0; // 100 bytes per row estimate
505
506        PlanCost::new(cpu, io, memory)
507    }
508
509    /// Compute the I/O page cost for a table scan.
510    ///
511    /// When the query has a simple equality or range filter on an indexed
512    /// column, use `IndexStats::correlated_io_cost` (Mackert-Lohman) which
513    /// accounts for `index_correlation` (0.0 = random I/O, 1.0 = sequential).
514    /// Falls back to the naive `rows / 100` heuristic otherwise.
515    fn estimate_table_io(&self, query: &TableQuery, result_rows: f64) -> f64 {
516        const ROWS_PER_PAGE: f64 = 100.0;
517
518        // Look up total heap pages from table stats if available
519        let table_stats = self.stats.table_stats(&query.table);
520        let heap_pages = table_stats
521            .map(|s| s.page_count as f64)
522            .unwrap_or_else(|| (result_rows / ROWS_PER_PAGE).max(1.0));
523
524        // If the filter is a simple comparison on an indexed column, use
525        // the Mackert-Lohman formula with correlation from IndexStats.
526        if let Some(filter) = reddb_rql::sql_lowering::effective_table_filter(query) {
527            if let Some(col) = first_filter_column(&filter, &query.table) {
528                if let Some(idx) = self.stats.index_stats(&query.table, col) {
529                    return idx.correlated_io_cost(result_rows, heap_pages);
530                }
531            }
532        }
533
534        // Heuristic fallback: assume sequential pages = rows / 100
535        (result_rows / ROWS_PER_PAGE).ceil()
536    }
537
538    fn estimate_table_cardinality(&self, query: &TableQuery) -> CardinalityEstimate {
539        // Prefer real row counts from the stats provider; fall back to the
540        // heuristic `default_row_count` when no stats are registered.
541        let base_rows = self
542            .stats
543            .table_stats(&query.table)
544            .map(|s| s.row_count as f64)
545            .unwrap_or(self.default_row_count);
546
547        let mut estimate = CardinalityEstimate::full_scan(base_rows);
548
549        // Apply filter selectivity (stats-aware when provider has index
550        // stats on the compared column).
551        if let Some(filter) = reddb_rql::sql_lowering::effective_table_filter(query) {
552            let selectivity = self.filter_selectivity(&filter, &query.table);
553            estimate = estimate.with_filter(selectivity);
554        }
555
556        // Apply limit
557        if let Some(limit) = query.limit {
558            estimate.rows = estimate.rows.min(limit as f64);
559        }
560
561        estimate
562    }
563
564    /// Stats-aware selectivity computation.
565    ///
566    /// Resolution order (best → worst):
567    ///   1. `column_mcv` for equality on a known frequent value
568    ///   2. `column_histogram` for ranges and BETWEEN
569    ///   3. `index_stats.point_selectivity()` for indexed columns
570    ///   4. Hardcoded heuristic constants as final fallback
571    ///
572    /// Mirrors postgres `var_eq_const` / `histogram_selectivity` in
573    /// `src/backend/utils/adt/selfuncs.c`. Histogram + MCV data
574    /// structures already live in `super::histogram`; this method is
575    /// where we finally consume them on the hot planner path.
576    fn filter_selectivity(&self, filter: &AstFilter, table: &str) -> f64 {
577        match filter {
578            AstFilter::Compare { field, op, value } => {
579                let column = column_name_for_table(field, table);
580                match op {
581                    CompareOp::Eq => self.eq_selectivity(table, column, value),
582                    CompareOp::Ne => 1.0 - self.eq_selectivity(table, column, value),
583                    CompareOp::Lt | CompareOp::Le => {
584                        self.range_selectivity(table, column, None, Some(value))
585                    }
586                    CompareOp::Gt | CompareOp::Ge => {
587                        self.range_selectivity(table, column, Some(value), None)
588                    }
589                }
590            }
591            AstFilter::Between {
592                field, low, high, ..
593            } => {
594                let column = column_name_for_table(field, table);
595                self.range_selectivity(table, column, Some(low), Some(high))
596            }
597            AstFilter::In { field, values, .. } => {
598                let column = column_name_for_table(field, table);
599                // If we have an MCV list, sum the per-value frequencies
600                // for values that are actually in the list, plus the
601                // residual estimate for the rest.
602                if let Some(c) = column {
603                    if let Some(mcv) = self.stats.column_mcv(table, c) {
604                        let mut hits: f64 = 0.0;
605                        let mut residual_count = 0usize;
606                        for v in values {
607                            if let Some(cv) = column_value_from(v) {
608                                if let Some(freq) = mcv.frequency_of(&cv) {
609                                    hits += freq;
610                                } else {
611                                    residual_count += 1;
612                                }
613                            } else {
614                                residual_count += 1;
615                            }
616                        }
617                        let total = mcv.total_frequency();
618                        let distinct = self.stats.distinct_values(table, c).unwrap_or(100);
619                        let non_mcv_distinct =
620                            distinct.saturating_sub(mcv.values.len() as u64).max(1);
621                        let per_residual = (1.0 - total) / non_mcv_distinct as f64;
622                        let estimate = hits + (residual_count as f64) * per_residual;
623                        return estimate.clamp(0.0, 1.0).min(0.5);
624                    }
625                    if let Some(s) = self.stats.index_stats(table, c) {
626                        return (s.point_selectivity() * values.len() as f64).min(0.5);
627                    }
628                }
629                (values.len() as f64 * 0.01).min(0.5)
630            }
631            AstFilter::Like { .. } => 0.1,
632            AstFilter::StartsWith { .. } => 0.15,
633            AstFilter::EndsWith { .. } => 0.15,
634            AstFilter::Contains { .. } => 0.1,
635            AstFilter::IsNull { .. } => 0.01,
636            AstFilter::IsNotNull { .. } => 0.99,
637            AstFilter::And(left, right) => {
638                self.filter_selectivity(left, table) * self.filter_selectivity(right, table)
639            }
640            AstFilter::Or(left, right) => {
641                let s1 = self.filter_selectivity(left, table);
642                let s2 = self.filter_selectivity(right, table);
643                s1 + s2 - (s1 * s2)
644            }
645            AstFilter::Not(inner) => 1.0 - self.filter_selectivity(inner, table),
646            AstFilter::CompareFields { .. } => {
647                // Column-to-column predicates lack histogram leverage
648                // — assume moderate selectivity. Histogram/MCV hooks
649                // only help literal-valued filters.
650                0.1
651            }
652            AstFilter::CompareExpr { .. } => {
653                // Expression-shaped predicates: conservative 0.1 until
654                // the planner learns to walk Expr trees. Matches the
655                // CompareFields default.
656                0.1
657            }
658        }
659    }
660
661    // =========================================================================
662    // Graph Query Estimation
663    // =========================================================================
664
665    fn estimate_graph(&self, query: &GraphQuery) -> PlanCost {
666        let cardinality = self.estimate_graph_cardinality(query);
667
668        // Graph queries are more expensive due to pointer chasing
669        let nodes = query.pattern.nodes.len() as f64;
670        let edges = query.pattern.edges.len() as f64;
671
672        let cpu = cardinality.rows * self.edge_traversal_cost * (nodes + edges);
673        let io = cardinality.rows * 0.1; // More random IO
674        let memory = cardinality.rows * 200.0; // Larger due to paths
675
676        PlanCost::new(cpu, io, memory)
677    }
678
679    fn estimate_graph_cardinality(&self, query: &GraphQuery) -> CardinalityEstimate {
680        let nodes = query.pattern.nodes.len() as f64;
681        let edges = query.pattern.edges.len() as f64;
682
683        // Each edge reduces cardinality
684        let base_rows = self.default_row_count;
685        let edge_factor = 0.1_f64.powf(edges); // Each edge is highly selective
686
687        let mut estimate = CardinalityEstimate::new(base_rows * nodes * edge_factor, edge_factor);
688        estimate.confidence = 0.5; // Graph estimates are less accurate
689
690        // Apply filter
691        if let Some(ref filter) = query.filter {
692            let selectivity = Self::estimate_filter_selectivity(filter);
693            estimate = estimate.with_filter(selectivity);
694        }
695
696        estimate
697    }
698
699    // =========================================================================
700    // Join Query Estimation
701    // =========================================================================
702
703    fn estimate_join(&self, query: &JoinQuery) -> PlanCost {
704        let left_cost = self.estimate(&query.left);
705        let right_cost = self.estimate(&query.right);
706
707        let left_card = self.estimate_cardinality(&query.left);
708        let right_card = self.estimate_cardinality(&query.right);
709
710        // Hash join cost model.
711        //
712        // Build side (left) is **blocking** — we must drain the entire
713        // left input and populate the hash table before any probe can
714        // produce its first output row. Probe side (right) is then
715        // streamed pipelined.
716        let build_cpu = left_card.rows * self.hash_probe_cost;
717        let probe_cpu = right_card.rows * self.hash_probe_cost;
718        let join_memory = left_card.rows * 100.0; // hash table footprint
719
720        // The build operator: zero work upstream, blocking on left input.
721        let build_op = PlanCost::with_startup(build_cpu, 0.0, join_memory, build_cpu);
722        // The probe operator: pipelined over right input.
723        let probe_op = PlanCost::new(probe_cpu, 0.0, 0.0);
724
725        // Compose: left → block on build → pipelined probe with right.
726        let after_build = left_cost.combine_blocking(&build_op);
727        after_build
728            .combine_pipelined(&right_cost)
729            .combine_pipelined(&probe_op)
730    }
731
732    fn estimate_join_cardinality(&self, query: &JoinQuery) -> CardinalityEstimate {
733        let left = self.estimate_cardinality(&query.left);
734        let right = self.estimate_cardinality(&query.right);
735
736        // Join selectivity based on join type
737        let selectivity = match query.join_type {
738            JoinType::Inner => 0.1,      // Inner join is selective
739            JoinType::LeftOuter => 1.0,  // Left join preserves left side
740            JoinType::RightOuter => 1.0, // Right join preserves right side
741            JoinType::FullOuter => 1.0,  // Full outer preserves both sides entirely
742            JoinType::Cross => 1.0,      // Cartesian product — every pair matches
743        };
744
745        CardinalityEstimate::new(
746            left.rows * right.rows * selectivity,
747            left.selectivity * right.selectivity * selectivity,
748        )
749    }
750
751    // =========================================================================
752    // Path Query Estimation
753    // =========================================================================
754
755    fn estimate_path(&self, query: &PathQuery) -> PlanCost {
756        let cardinality = self.estimate_path_cardinality(query);
757
758        // BFS/DFS cost
759        let max_hops = query.max_length;
760        let branching_factor: f64 = 5.0; // Average edges per node
761
762        let nodes_visited = branching_factor.powf(max_hops as f64).min(10000.0);
763        let cpu = nodes_visited * self.edge_traversal_cost;
764        let io = nodes_visited * 0.1;
765        let memory = nodes_visited * 50.0; // Visited set
766
767        PlanCost::new(cpu, io, memory)
768    }
769
770    fn estimate_path_cardinality(&self, query: &PathQuery) -> CardinalityEstimate {
771        // Path queries typically return few results
772        let max_paths = 10.0;
773        CardinalityEstimate::new(max_paths, 0.001)
774    }
775
776    // =========================================================================
777    // Vector Query Estimation
778    // =========================================================================
779
780    fn estimate_vector(&self, query: &VectorQuery) -> PlanCost {
781        // HNSW search is O(log n) with relatively low constant
782        // Typical search visits ~100-500 nodes for 1M vectors
783        let k = query.k as f64;
784
785        // Base cost from HNSW traversal — must descend the layer graph
786        // before *any* candidate can be returned. This is the operator's
787        // intrinsic startup cost.
788        let hnsw_cost = 100.0 * (1.0 + k.ln()); // ~100-300 node visits
789
790        // Metadata filtering adds cost if present
791        let filter_cost = if reddb_rql::sql_lowering::effective_vector_filter(query).is_some() {
792            50.0
793        } else {
794            0.0
795        };
796
797        let cpu = hnsw_cost + filter_cost;
798        let io = 20.0; // HNSW layers are cached
799        let memory = k * 32.0 + 1000.0; // k results + working set
800
801        // Vector search is *partly* blocking: HNSW must traverse the
802        // entry layers before the first neighbour is known, so the
803        // first-row cost is roughly the descent cost. Subsequent rows
804        // come essentially free until `k`.
805        PlanCost::with_startup(cpu, io, memory, hnsw_cost * 0.5)
806    }
807
808    fn estimate_vector_cardinality(&self, query: &VectorQuery) -> CardinalityEstimate {
809        // Vector search returns exactly k results (or fewer if not enough vectors)
810        let k = query.k as f64;
811        CardinalityEstimate::new(k, 0.1)
812    }
813
814    // =========================================================================
815    // Hybrid Query Estimation
816    // =========================================================================
817
818    fn estimate_hybrid(&self, query: &HybridQuery) -> PlanCost {
819        // Hybrid cost = structured + vector + fusion overhead
820        let structured_cost = self.estimate(&query.structured);
821        let vector_cost = self.estimate_vector(&query.vector);
822
823        // Fusion overhead depends on strategy
824        let fusion_overhead = match &query.fusion {
825            reddb_rql::ast::FusionStrategy::Rerank { .. } => 50.0,
826            reddb_rql::ast::FusionStrategy::FilterThenSearch => 10.0,
827            reddb_rql::ast::FusionStrategy::SearchThenFilter => 10.0,
828            reddb_rql::ast::FusionStrategy::RRF { .. } => 30.0,
829            reddb_rql::ast::FusionStrategy::Intersection => 20.0,
830            reddb_rql::ast::FusionStrategy::Union { .. } => 40.0,
831        };
832
833        PlanCost::new(
834            structured_cost.cpu + vector_cost.cpu + fusion_overhead,
835            structured_cost.io + vector_cost.io,
836            structured_cost.memory + vector_cost.memory,
837        )
838    }
839
840    fn estimate_hybrid_cardinality(&self, query: &HybridQuery) -> CardinalityEstimate {
841        let structured_card = self.estimate_cardinality(&query.structured);
842        let vector_card = self.estimate_vector_cardinality(&query.vector);
843
844        // Result size depends on fusion strategy
845        let rows = match &query.fusion {
846            reddb_rql::ast::FusionStrategy::Intersection => {
847                structured_card.rows.min(vector_card.rows)
848            }
849            reddb_rql::ast::FusionStrategy::Union { .. } => structured_card.rows + vector_card.rows,
850            _ => vector_card.rows, // Rerank and filter strategies return vector k
851        };
852
853        CardinalityEstimate::new(rows, 0.2)
854    }
855
856    // =========================================================================
857    // Filter Selectivity
858    // =========================================================================
859
860    fn estimate_filter_selectivity(filter: &AstFilter) -> f64 {
861        match filter {
862            AstFilter::Compare { op, .. } => {
863                match op {
864                    CompareOp::Eq => 0.01, // Equality is very selective
865                    CompareOp::Ne => 0.99, // Inequality is not selective
866                    CompareOp::Lt | CompareOp::Le => 0.3,
867                    CompareOp::Gt | CompareOp::Ge => 0.3,
868                }
869            }
870            AstFilter::Between { .. } => 0.25,
871            AstFilter::In { values, .. } => {
872                // Each value adds 1% selectivity
873                (values.len() as f64 * 0.01).min(0.5)
874            }
875            AstFilter::Like { .. } => 0.1,
876            AstFilter::StartsWith { .. } => 0.15,
877            AstFilter::EndsWith { .. } => 0.15,
878            AstFilter::Contains { .. } => 0.1,
879            AstFilter::IsNull { .. } => 0.01,
880            AstFilter::IsNotNull { .. } => 0.99,
881            AstFilter::And(left, right) => {
882                Self::estimate_filter_selectivity(left) * Self::estimate_filter_selectivity(right)
883            }
884            AstFilter::Or(left, right) => {
885                let s1 = Self::estimate_filter_selectivity(left);
886                let s2 = Self::estimate_filter_selectivity(right);
887                s1 + s2 - (s1 * s2) // Inclusion-exclusion
888            }
889            AstFilter::Not(inner) => 1.0 - Self::estimate_filter_selectivity(inner),
890            AstFilter::CompareFields { .. } => 0.1,
891            AstFilter::CompareExpr { .. } => 0.1,
892        }
893    }
894}
895
896impl CostEstimator {
897    /// Equality selectivity for `column = value`.
898    ///
899    /// Resolution order:
900    /// 1. MCV list — exact frequency for tracked values, residual
901    ///    formula for untracked values.
902    /// 2. `index_stats.point_selectivity()` — `1 / distinct_keys`.
903    /// 3. Heuristic constant `0.01`.
904    fn eq_selectivity(&self, table: &str, column: Option<&str>, value: &Value) -> f64 {
905        if let Some(col) = column {
906            // 1. Most-common-values lookup.
907            if let Some(mcv) = self.stats.column_mcv(table, col) {
908                if let Some(cv) = column_value_from(value) {
909                    if let Some(freq) = mcv.frequency_of(&cv) {
910                        return freq;
911                    }
912                    // Untracked value: residual / non_mcv_distinct.
913                    let total = mcv.total_frequency();
914                    let distinct = self.stats.distinct_values(table, col).unwrap_or(100);
915                    let non_mcv_distinct = distinct.saturating_sub(mcv.values.len() as u64).max(1);
916                    return ((1.0 - total) / non_mcv_distinct as f64).clamp(0.0, 1.0);
917                }
918            }
919            // 2. Index stats fallback.
920            if let Some(s) = self.stats.index_stats(table, col) {
921                return s.point_selectivity();
922            }
923        }
924        // 3. Heuristic.
925        0.01
926    }
927
928    /// Range selectivity for `lo <= column <= hi`. Either bound may
929    /// be `None` to express an open side. Used by `<`, `<=`, `>`,
930    /// `>=`, and `BETWEEN`.
931    ///
932    /// Resolution order:
933    /// 1. Histogram — `Histogram::range_selectivity` with bounds
934    ///    converted via `column_value_from`.
935    /// 2. `index_stats.point_selectivity() * (distinct_keys / 2)`
936    ///    capped at the legacy heuristic.
937    /// 3. Heuristic `0.3` for one-sided, `0.25` for two-sided.
938    fn range_selectivity(
939        &self,
940        table: &str,
941        column: Option<&str>,
942        lo: Option<&Value>,
943        hi: Option<&Value>,
944    ) -> f64 {
945        if let Some(col) = column {
946            // 1. Histogram bucket arithmetic.
947            if let Some(h) = self.stats.column_histogram(table, col) {
948                let lo_cv = lo.and_then(column_value_from);
949                let hi_cv = hi.and_then(column_value_from);
950                return h.range_selectivity(lo_cv.as_ref(), hi_cv.as_ref());
951            }
952            // 2. Index stats fallback.
953            if let Some(s) = self.stats.index_stats(table, col) {
954                let cap = if lo.is_some() && hi.is_some() {
955                    0.25
956                } else {
957                    0.3
958                };
959                return (s.point_selectivity() * (s.distinct_keys as f64 / 2.0)).min(cap);
960            }
961        }
962        // 3. Heuristic.
963        if lo.is_some() && hi.is_some() {
964            0.25
965        } else {
966            0.3
967        }
968    }
969}
970
971impl Default for CostEstimator {
972    fn default() -> Self {
973        Self::new()
974    }
975}
976
977/// Convert a query AST `Value` into a histogram-comparable
978/// [`super::histogram::ColumnValue`]. Returns `None` for value types
979/// that histograms don't support (Bool, Null, Bytes, etc.) — callers
980/// fall through to the heuristic path.
981fn column_value_from(v: &reddb_types::Value) -> Option<super::histogram::ColumnValue> {
982    use super::histogram::ColumnValue;
983    use reddb_types::Value;
984    match v {
985        Value::Integer(i) | Value::BigInt(i) => Some(ColumnValue::Int(*i)),
986        Value::UnsignedInteger(u) => Some(ColumnValue::Int(*u as i64)),
987        Value::Float(f) if f.is_finite() => Some(ColumnValue::Float(*f)),
988        Value::Text(s) => Some(ColumnValue::Text(s.to_string())),
989        Value::Email(s)
990        | Value::Url(s)
991        | Value::NodeRef(s)
992        | Value::EdgeRef(s)
993        | Value::TableRef(s)
994        | Value::Password(s) => Some(ColumnValue::Text(s.clone())),
995        Value::Timestamp(t) => Some(ColumnValue::Int(*t)),
996        Value::Duration(d) => Some(ColumnValue::Int(*d)),
997        Value::TimestampMs(t) => Some(ColumnValue::Int(*t)),
998        Value::Decimal(d) => Some(ColumnValue::Int(*d)),
999        Value::Date(d) => Some(ColumnValue::Int(i64::from(*d))),
1000        Value::Time(t) => Some(ColumnValue::Int(i64::from(*t))),
1001        Value::Phone(p) => Some(ColumnValue::Int(*p as i64)),
1002        Value::Semver(v) => Some(ColumnValue::Int(i64::from(*v))),
1003        Value::Port(v) => Some(ColumnValue::Int(i64::from(*v))),
1004        Value::PageRef(v) => Some(ColumnValue::Int(i64::from(*v))),
1005        Value::EnumValue(v) => Some(ColumnValue::Int(i64::from(*v))),
1006        Value::Latitude(v) => Some(ColumnValue::Int(i64::from(*v))),
1007        Value::Longitude(v) => Some(ColumnValue::Int(i64::from(*v))),
1008        // Other variants (Null, Blob, Boolean, IpAddr, MacAddr,
1009        // Vector, Json, Uuid, NodeRef, EdgeRef, vector ref...) are
1010        // not orderable in a histogram-meaningful way; the planner
1011        // falls through to the heuristic for these.
1012        _ => None,
1013    }
1014}
1015
1016/// Resolve a `FieldRef` to a bare column name when it refers to `table`.
1017/// Returns `None` when the field targets another relation — in that case
1018/// Extract the first plain column name from a filter for index-stat lookup.
1019/// Walks AND nodes; stops at OR/NOT (too complex for simple correlation lookup).
1020fn first_filter_column<'a>(filter: &'a AstFilter, table: &str) -> Option<&'a str> {
1021    match filter {
1022        AstFilter::Compare { field, .. } => column_name_for_table(field, table),
1023        AstFilter::Between { field, .. } => column_name_for_table(field, table),
1024        AstFilter::And(l, r) => {
1025            first_filter_column(l, table).or_else(|| first_filter_column(r, table))
1026        }
1027        _ => None,
1028    }
1029}
1030
1031/// the legacy heuristic still applies.
1032fn column_name_for_table<'a>(field: &'a FieldRef, table: &str) -> Option<&'a str> {
1033    match field {
1034        FieldRef::TableColumn { table: t, column } if t == table || t.is_empty() => {
1035            Some(column.as_str())
1036        }
1037        // Node / edge property refs don't map to table-level stats.
1038        _ => None,
1039    }
1040}
1041
1042#[cfg(test)]
1043mod tests {
1044    use super::super::stats_provider::StaticProvider;
1045    use super::*;
1046    use crate::storage::index::{IndexKind, IndexStats};
1047    use reddb_rql::ast::{FieldRef, Projection};
1048    use reddb_types::Value;
1049
1050    fn eq_filter(table: &str, column: &str, value: i64) -> AstFilter {
1051        AstFilter::Compare {
1052            field: FieldRef::column(table, column),
1053            op: CompareOp::Eq,
1054            value: Value::Integer(value),
1055        }
1056    }
1057
1058    fn table_query(name: &str, filter: Option<AstFilter>) -> TableQuery {
1059        TableQuery {
1060            table: name.to_string(),
1061            source: None,
1062            alias: None,
1063            select_items: Vec::new(),
1064            columns: vec![Projection::All],
1065            where_expr: None,
1066            filter,
1067            group_by_exprs: Vec::new(),
1068            group_by: Vec::new(),
1069            having_expr: None,
1070            having: None,
1071            order_by: vec![],
1072            limit: None,
1073            limit_param: None,
1074            offset: None,
1075            offset_param: None,
1076            expand: None,
1077            as_of: None,
1078            sessionize: None,
1079            distinct: false,
1080        }
1081    }
1082
1083    #[test]
1084    fn injected_row_count_overrides_default() {
1085        let provider = Arc::new(StaticProvider::new().with_table(
1086            "users",
1087            TableStats {
1088                row_count: 50_000,
1089                avg_row_size: 256,
1090                page_count: 500,
1091                columns: vec![],
1092            },
1093        ));
1094        let estimator = CostEstimator::with_stats(provider);
1095        let q = table_query("users", None);
1096        let card = estimator.estimate_table_cardinality(&q);
1097        // Default would be 1000; provider says 50_000.
1098        assert_eq!(card.rows, 50_000.0);
1099    }
1100
1101    #[test]
1102    fn stats_aware_eq_selectivity_beats_default() {
1103        let provider = Arc::new(
1104            StaticProvider::new()
1105                .with_table(
1106                    "users",
1107                    TableStats {
1108                        row_count: 1_000_000,
1109                        avg_row_size: 256,
1110                        page_count: 10_000,
1111                        columns: vec![],
1112                    },
1113                )
1114                .with_index(
1115                    "users",
1116                    "email",
1117                    IndexStats {
1118                        entries: 1_000_000,
1119                        distinct_keys: 1_000_000,
1120                        approx_bytes: 0,
1121                        kind: IndexKind::Hash,
1122                        has_bloom: true,
1123                        index_correlation: 0.0,
1124                    },
1125                ),
1126        );
1127        let estimator = CostEstimator::with_stats(provider);
1128        let q = table_query("users", Some(eq_filter("users", "email", 0)));
1129        let card = estimator.estimate_table_cardinality(&q);
1130        // 1M rows × (1 / 1M distinct) ≈ 1 row
1131        assert!(card.rows < 2.0, "expected ~1 row, got {}", card.rows);
1132    }
1133
1134    #[test]
1135    fn fallback_when_no_index_stats() {
1136        let provider = Arc::new(StaticProvider::new().with_table(
1137            "users",
1138            TableStats {
1139                row_count: 1_000_000,
1140                avg_row_size: 256,
1141                page_count: 10_000,
1142                columns: vec![],
1143            },
1144        ));
1145        let estimator = CostEstimator::with_stats(provider);
1146        let q = table_query("users", Some(eq_filter("users", "email", 0)));
1147        let card = estimator.estimate_table_cardinality(&q);
1148        // Heuristic 0.01 on 1M rows = 10_000
1149        assert!((card.rows - 10_000.0).abs() < 1.0);
1150    }
1151
1152    #[test]
1153    fn null_provider_keeps_legacy_behaviour() {
1154        let estimator = CostEstimator::new();
1155        let q = table_query("whatever", Some(eq_filter("whatever", "id", 1)));
1156        let card = estimator.estimate_table_cardinality(&q);
1157        // Default 1000 rows × 0.01 eq selectivity = 10
1158        assert!((card.rows - 10.0).abs() < 1.0);
1159    }
1160
1161    #[test]
1162    fn and_combines_stats_selectivities() {
1163        let provider = Arc::new(
1164            StaticProvider::new()
1165                .with_table(
1166                    "t",
1167                    TableStats {
1168                        row_count: 100_000,
1169                        avg_row_size: 64,
1170                        page_count: 100,
1171                        columns: vec![],
1172                    },
1173                )
1174                .with_index(
1175                    "t",
1176                    "a",
1177                    IndexStats {
1178                        entries: 100_000,
1179                        distinct_keys: 10,
1180                        approx_bytes: 0,
1181                        kind: IndexKind::BTree,
1182                        has_bloom: false,
1183                        index_correlation: 0.0,
1184                    },
1185                )
1186                .with_index(
1187                    "t",
1188                    "b",
1189                    IndexStats {
1190                        entries: 100_000,
1191                        distinct_keys: 1000,
1192                        approx_bytes: 0,
1193                        kind: IndexKind::BTree,
1194                        has_bloom: false,
1195                        index_correlation: 0.0,
1196                    },
1197                ),
1198        );
1199        let estimator = CostEstimator::with_stats(provider);
1200        let filter = AstFilter::And(
1201            Box::new(eq_filter("t", "a", 1)),
1202            Box::new(eq_filter("t", "b", 1)),
1203        );
1204        let q = table_query("t", Some(filter));
1205        let card = estimator.estimate_table_cardinality(&q);
1206        // 100_000 × (1/10) × (1/1000) = 10
1207        assert!(card.rows < 15.0, "got {}", card.rows);
1208    }
1209
1210    #[test]
1211    fn test_table_cost_estimation() {
1212        let estimator = CostEstimator::new();
1213
1214        let query = QueryExpr::Table(TableQuery {
1215            table: "hosts".to_string(),
1216            source: None,
1217            alias: None,
1218            select_items: Vec::new(),
1219            columns: vec![Projection::All],
1220            where_expr: None,
1221            filter: None,
1222            group_by_exprs: Vec::new(),
1223            group_by: Vec::new(),
1224            having_expr: None,
1225            having: None,
1226            order_by: vec![],
1227            limit: None,
1228            limit_param: None,
1229            offset: None,
1230            offset_param: None,
1231            expand: None,
1232            as_of: None,
1233            sessionize: None,
1234            distinct: false,
1235        });
1236
1237        let cost = estimator.estimate(&query);
1238        assert!(cost.cpu > 0.0);
1239        assert!(cost.total > 0.0);
1240    }
1241
1242    #[test]
1243    fn test_filter_selectivity() {
1244        let estimator = CostEstimator::new();
1245
1246        let eq_filter = AstFilter::Compare {
1247            field: FieldRef::column("hosts", "id"),
1248            op: CompareOp::Eq,
1249            value: Value::Integer(1),
1250        };
1251        assert!(CostEstimator::estimate_filter_selectivity(&eq_filter) < 0.1);
1252
1253        let ne_filter = AstFilter::Compare {
1254            field: FieldRef::column("hosts", "id"),
1255            op: CompareOp::Ne,
1256            value: Value::Integer(1),
1257        };
1258        assert!(CostEstimator::estimate_filter_selectivity(&ne_filter) > 0.9);
1259    }
1260
1261    #[test]
1262    fn test_and_selectivity() {
1263        let estimator = CostEstimator::new();
1264
1265        let and_filter = AstFilter::And(
1266            Box::new(AstFilter::Compare {
1267                field: FieldRef::column("hosts", "a"),
1268                op: CompareOp::Eq,
1269                value: Value::Integer(1),
1270            }),
1271            Box::new(AstFilter::Compare {
1272                field: FieldRef::column("hosts", "b"),
1273                op: CompareOp::Eq,
1274                value: Value::Integer(2),
1275            }),
1276        );
1277
1278        let selectivity = CostEstimator::estimate_filter_selectivity(&and_filter);
1279        assert!(selectivity < 0.01); // AND should be very selective
1280    }
1281
1282    #[test]
1283    fn test_cardinality_with_limit() {
1284        let estimator = CostEstimator::new();
1285
1286        let query = TableQuery {
1287            table: "hosts".to_string(),
1288            source: None,
1289            alias: None,
1290            select_items: Vec::new(),
1291            columns: vec![Projection::All],
1292            where_expr: None,
1293            filter: None,
1294            group_by_exprs: Vec::new(),
1295            group_by: Vec::new(),
1296            having_expr: None,
1297            having: None,
1298            order_by: vec![],
1299            limit: Some(10),
1300            limit_param: None,
1301            offset: None,
1302            offset_param: None,
1303            expand: None,
1304            as_of: None,
1305            sessionize: None,
1306            distinct: false,
1307        };
1308
1309        let card = estimator.estimate_table_cardinality(&query);
1310        assert!(card.rows <= 10.0);
1311    }
1312
1313    // ---------------------------------------------------------------
1314    // Target 2: startup_cost vs total_cost split
1315    // ---------------------------------------------------------------
1316
1317    #[test]
1318    fn startup_zero_for_full_scan() {
1319        // estimate_table is implemented as a streaming sequential scan
1320        // (no startup cost — the first row is producible as soon as the
1321        // first page is read).
1322        let estimator = CostEstimator::new();
1323        let q = table_query("any_table", None);
1324        let cost = estimator.estimate(&QueryExpr::Table(q));
1325        assert_eq!(cost.startup_cost, 0.0, "full scan must have zero startup");
1326        assert!(cost.total > 0.0);
1327    }
1328
1329    #[test]
1330    fn startup_nonzero_for_blocking_combine() {
1331        // combine_blocking models a sort or hash build: the input must
1332        // be fully consumed before the blocker can emit its first row.
1333        let input = PlanCost::new(100.0, 10.0, 50.0); // cost = 100 + 100 + 5 = 205
1334        let blocker = PlanCost::new(20.0, 0.0, 10.0); // cost = 20 + 0 + 1 = 21
1335        let composed = input.combine_blocking(&blocker);
1336        // Blocking startup absorbs all of input.total
1337        assert_eq!(composed.startup_cost, input.total);
1338        // Total is input.total + blocker.total
1339        assert_eq!(composed.total, input.total + blocker.total);
1340        assert!(composed.startup_cost > 0.0);
1341    }
1342
1343    #[test]
1344    fn pipelined_combine_adds_startup_directly() {
1345        let upstream = PlanCost::with_startup(50.0, 5.0, 10.0, 30.0);
1346        let downstream = PlanCost::with_startup(20.0, 0.0, 0.0, 5.0);
1347        let composed = upstream.combine_pipelined(&downstream);
1348        assert_eq!(composed.startup_cost, 30.0 + 5.0);
1349        assert_eq!(composed.total, upstream.total + downstream.total);
1350    }
1351
1352    #[test]
1353    fn cost_prefers_low_startup_when_limit_small() {
1354        // Two plans with the same total but different startup. With a
1355        // small LIMIT, the planner must pick the low-startup plan.
1356        let fast_first = PlanCost {
1357            cpu: 100.0,
1358            io: 10.0,
1359            network: 0.0,
1360            memory: 50.0,
1361            startup_cost: 5.0,
1362            total: 200.0,
1363        };
1364        let slow_first = PlanCost {
1365            cpu: 100.0,
1366            io: 10.0,
1367            network: 0.0,
1368            memory: 50.0,
1369            startup_cost: 150.0,
1370            total: 200.0,
1371        };
1372        // Cardinality 10_000, LIMIT 10 → 10 < 0.1 * 10_000 = 1000 → use startup.
1373        assert_eq!(
1374            fast_first.prefer_over(&slow_first, Some(10), 10_000.0),
1375            std::cmp::Ordering::Less
1376        );
1377    }
1378
1379    #[test]
1380    fn cost_prefers_low_total_when_no_limit() {
1381        // Same two plans, no LIMIT — total wins.
1382        let low_total = PlanCost {
1383            cpu: 50.0,
1384            io: 5.0,
1385            network: 0.0,
1386            memory: 0.0,
1387            startup_cost: 30.0,
1388            total: 100.0,
1389        };
1390        let high_total = PlanCost {
1391            cpu: 100.0,
1392            io: 10.0,
1393            network: 0.0,
1394            memory: 0.0,
1395            startup_cost: 5.0,
1396            total: 200.0,
1397        };
1398        assert_eq!(
1399            low_total.prefer_over(&high_total, None, 10_000.0),
1400            std::cmp::Ordering::Less
1401        );
1402    }
1403
1404    #[test]
1405    fn limit_threshold_falls_back_to_total_when_limit_large() {
1406        // LIMIT 5000 vs cardinality 10_000 → 5000 > 1000 → use total.
1407        let low_total = PlanCost {
1408            cpu: 50.0,
1409            io: 5.0,
1410            network: 0.0,
1411            memory: 0.0,
1412            startup_cost: 30.0,
1413            total: 100.0,
1414        };
1415        let low_startup = PlanCost {
1416            cpu: 100.0,
1417            io: 10.0,
1418            network: 0.0,
1419            memory: 0.0,
1420            startup_cost: 5.0,
1421            total: 200.0,
1422        };
1423        assert_eq!(
1424            low_total.prefer_over(&low_startup, Some(5000), 10_000.0),
1425            std::cmp::Ordering::Less
1426        );
1427    }
1428
1429    #[test]
1430    fn hash_join_startup_includes_build_cost() {
1431        // Direct combine_blocking semantics: a hash join must drain the
1432        // left input and build the hash table before producing the first
1433        // probe result.
1434        let left = PlanCost::new(80.0, 8.0, 100.0); // table scan
1435        let build = PlanCost::with_startup(50.0, 0.0, 200.0, 50.0); // build op
1436        let after_build = left.combine_blocking(&build);
1437        assert!(
1438            after_build.startup_cost >= left.total,
1439            "after-build startup ({}) must absorb left.total ({})",
1440            after_build.startup_cost,
1441            left.total
1442        );
1443        assert!(after_build.total >= after_build.startup_cost);
1444    }
1445
1446    #[test]
1447    fn vector_search_reports_nonzero_startup() {
1448        // estimate_vector now uses with_startup so HNSW descent shows
1449        // up as startup_cost > 0 (and < total — subsequent neighbours
1450        // are essentially free).
1451        let estimator = CostEstimator::new();
1452        // We can't easily build a VectorQuery without the AST helpers,
1453        // so test the direct cost surface with_startup uses.
1454        let v = PlanCost::with_startup(150.0, 20.0, 1320.0, 50.0);
1455        assert!(v.startup_cost > 0.0);
1456        assert!(v.startup_cost < v.total);
1457        let _ = estimator; // suppress unused
1458    }
1459
1460    #[test]
1461    fn with_startup_clamps_total_below_startup() {
1462        // If a caller asks for total < startup, with_startup raises total.
1463        let cost = PlanCost::with_startup(1.0, 0.0, 0.0, 100.0);
1464        assert!(cost.total >= cost.startup_cost);
1465    }
1466
1467    #[test]
1468    fn default_plancost_has_zero_startup() {
1469        let c = PlanCost::default();
1470        assert_eq!(c.startup_cost, 0.0);
1471        assert_eq!(c.total, 0.0);
1472    }
1473
1474    // ---------------------------------------------------------------
1475    // Perf 1.3: histogram + MCV plug-in into filter_selectivity
1476    // ---------------------------------------------------------------
1477
1478    use super::super::histogram::{ColumnValue, Histogram, MostCommonValues};
1479
1480    fn provider_with_skew() -> Arc<StaticProvider> {
1481        // Build a histogram where 80 of 100 values fall in [0, 9]
1482        // and the rest spread sparsely up to 1000. range_selectivity
1483        // for `<= 9` should be ~0.8, vastly beating the heuristic 0.3.
1484        let mut sample: Vec<ColumnValue> = Vec::new();
1485        for i in 0..80 {
1486            sample.push(ColumnValue::Int(i % 10));
1487        }
1488        for i in 0..20 {
1489            sample.push(ColumnValue::Int(10 + i * 50));
1490        }
1491        let h = Histogram::equi_depth_from_sample(sample, 10);
1492
1493        let mcv = MostCommonValues::new(vec![
1494            (ColumnValue::Text("boss".to_string()), 0.5),
1495            (ColumnValue::Text("intern".to_string()), 0.05),
1496        ]);
1497
1498        Arc::new(
1499            StaticProvider::new()
1500                .with_table(
1501                    "people",
1502                    TableStats {
1503                        row_count: 100_000,
1504                        avg_row_size: 64,
1505                        page_count: 100,
1506                        columns: vec![],
1507                    },
1508                )
1509                .with_histogram("people", "score", h)
1510                .with_mcv("people", "role", mcv),
1511        )
1512    }
1513
1514    #[test]
1515    fn eq_uses_mcv_when_value_is_tracked() {
1516        let provider = provider_with_skew();
1517        let estimator = CostEstimator::with_stats(provider);
1518        let filter = AstFilter::Compare {
1519            field: FieldRef::column("people", "role"),
1520            op: CompareOp::Eq,
1521            value: Value::text("boss".to_string()),
1522        };
1523        // MCV says "boss" is 50% of the table → selectivity 0.5,
1524        // not the 0.01 heuristic.
1525        let s = estimator.filter_selectivity(&filter, "people");
1526        assert!(
1527            (s - 0.5).abs() < 1e-9,
1528            "MCV-tracked equality should report exact frequency, got {s}"
1529        );
1530    }
1531
1532    #[test]
1533    fn eq_uses_residual_for_non_mcv_value() {
1534        let provider = provider_with_skew();
1535        let estimator = CostEstimator::with_stats(provider);
1536        let filter = AstFilter::Compare {
1537            field: FieldRef::column("people", "role"),
1538            op: CompareOp::Eq,
1539            value: Value::text("staff".to_string()),
1540        };
1541        // 1 - 0.55 (mcv totals) = 0.45 spread across (distinct - 2)
1542        // distinct values. We don't have an exact distinct count, so
1543        // the planner uses the default 100 → 0.45 / 98 ≈ 0.0046.
1544        let s = estimator.filter_selectivity(&filter, "people");
1545        assert!(s > 0.0 && s < 0.01, "residual eq should be tiny, got {s}");
1546    }
1547
1548    #[test]
1549    fn ne_is_one_minus_eq_under_mcv() {
1550        let provider = provider_with_skew();
1551        let estimator = CostEstimator::with_stats(provider);
1552        let filter = AstFilter::Compare {
1553            field: FieldRef::column("people", "role"),
1554            op: CompareOp::Ne,
1555            value: Value::text("boss".to_string()),
1556        };
1557        let s = estimator.filter_selectivity(&filter, "people");
1558        // 1 - 0.5 == 0.5
1559        assert!((s - 0.5).abs() < 1e-9, "Ne selectivity = 0.5, got {s}");
1560    }
1561
1562    #[test]
1563    fn range_uses_histogram_when_present() {
1564        let provider = provider_with_skew();
1565        let estimator = CostEstimator::with_stats(provider);
1566        let filter = AstFilter::Compare {
1567            field: FieldRef::column("people", "score"),
1568            op: CompareOp::Le,
1569            value: Value::Integer(9),
1570        };
1571        // Histogram says ~80% of values are in [0, 9], heuristic
1572        // would have said 0.3.
1573        let s = estimator.filter_selectivity(&filter, "people");
1574        assert!(
1575            s > 0.5,
1576            "histogram-based range selectivity should beat 0.3, got {s}"
1577        );
1578    }
1579
1580    #[test]
1581    fn between_uses_histogram() {
1582        let provider = provider_with_skew();
1583        let estimator = CostEstimator::with_stats(provider);
1584        let filter = AstFilter::Between {
1585            field: FieldRef::column("people", "score"),
1586            low: Value::Integer(0),
1587            high: Value::Integer(9),
1588        };
1589        let s = estimator.filter_selectivity(&filter, "people");
1590        assert!(s > 0.5, "BETWEEN should use histogram too, got {s}");
1591    }
1592
1593    #[test]
1594    fn graceful_fallback_when_histogram_absent() {
1595        // Provider has no histogram on `unknown_col` — must fall
1596        // through to the 0.3 heuristic without panicking.
1597        let provider = Arc::new(StaticProvider::new().with_table(
1598            "people",
1599            TableStats {
1600                row_count: 1000,
1601                avg_row_size: 64,
1602                page_count: 10,
1603                columns: vec![],
1604            },
1605        ));
1606        let estimator = CostEstimator::with_stats(provider);
1607        let filter = AstFilter::Compare {
1608            field: FieldRef::column("people", "unknown_col"),
1609            op: CompareOp::Lt,
1610            value: Value::Integer(50),
1611        };
1612        let s = estimator.filter_selectivity(&filter, "people");
1613        assert!((s - 0.3).abs() < 1e-9, "fallback heuristic 0.3, got {s}");
1614    }
1615}