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