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