1use std::sync::Arc;
13
14use super::stats_provider::{NullProvider, StatsProvider};
15use reddb_rql::ast::{
16 CompareOp, FieldRef, Filter as AstFilter, GraphQuery, HybridQuery, JoinQuery, JoinType,
17 PathQuery, QueryExpr, TableQuery, VectorQuery,
18};
19use reddb_types::Value;
20
21pub use reddb_engine::query::logical_plan::CardinalityEstimate;
22
23#[derive(Debug, Clone, Default)]
33pub struct PlanCost {
34 pub cpu: f64,
36 pub io: f64,
38 pub network: f64,
40 pub memory: f64,
42 pub startup_cost: f64,
48 pub total: f64,
50}
51
52impl PlanCost {
53 pub fn new(cpu: f64, io: f64, memory: f64) -> Self {
55 let total = cpu + io * 10.0 + memory * 0.1; Self {
57 cpu,
58 io,
59 network: 0.0,
60 memory,
61 startup_cost: 0.0,
62 total,
63 }
64 }
65
66 pub fn with_startup(cpu: f64, io: f64, memory: f64, startup_cost: f64) -> Self {
70 let total = cpu + io * 10.0 + memory * 0.1;
71 Self {
72 cpu,
73 io,
74 network: 0.0,
75 memory,
76 startup_cost: startup_cost.max(0.0),
77 total: total.max(startup_cost),
78 }
79 }
80
81 pub fn combine_pipelined(&self, other: &PlanCost) -> PlanCost {
87 PlanCost {
88 cpu: self.cpu + other.cpu,
89 io: self.io + other.io,
90 network: self.network + other.network,
91 memory: self.memory.max(other.memory),
92 startup_cost: self.startup_cost + other.startup_cost,
93 total: self.total + other.total,
94 }
95 }
96
97 pub fn combine_blocking(&self, blocker: &PlanCost) -> PlanCost {
104 PlanCost {
105 cpu: self.cpu + blocker.cpu,
106 io: self.io + blocker.io,
107 network: self.network + blocker.network,
108 memory: self.memory.max(blocker.memory),
109 startup_cost: self.total + blocker.startup_cost,
110 total: self.total + blocker.total,
111 }
112 }
113
114 pub fn combine(&self, other: &PlanCost) -> PlanCost {
119 self.combine_pipelined(other)
120 }
121
122 pub fn scale(&self, factor: f64) -> PlanCost {
124 PlanCost {
125 cpu: self.cpu * factor,
126 io: self.io * factor,
127 network: self.network * factor,
128 memory: self.memory, startup_cost: self.startup_cost, total: self.total * factor,
131 }
132 }
133
134 pub fn prefer_over(
146 &self,
147 other: &PlanCost,
148 limit: Option<u64>,
149 cardinality: f64,
150 ) -> std::cmp::Ordering {
151 let use_startup = matches!(limit, Some(k) if (k as f64) < 0.1 * cardinality.max(1.0));
152 let (lhs, rhs) = if use_startup {
153 (self.startup_cost, other.startup_cost)
154 } else {
155 (self.total, other.total)
156 };
157 lhs.partial_cmp(&rhs).unwrap_or(std::cmp::Ordering::Equal)
158 }
159}
160
161#[derive(Debug, Clone, Default)]
163pub struct TableStats {
164 pub row_count: u64,
166 pub avg_row_size: u32,
168 pub page_count: u64,
170 pub columns: Vec<ColumnStats>,
172}
173
174#[derive(Debug, Clone, Default)]
176pub struct ColumnStats {
177 pub name: String,
179 pub distinct_count: u64,
181 pub null_count: u64,
183 pub min_value: Option<String>,
185 pub max_value: Option<String>,
187 pub has_index: bool,
189}
190
191pub struct CostEstimator {
193 default_row_count: f64,
195 row_scan_cost: f64,
197 index_lookup_cost: f64,
199 hash_probe_cost: f64,
201 nested_loop_cost: f64,
203 edge_traversal_cost: f64,
205 stats: Arc<dyn StatsProvider>,
210}
211
212impl CostEstimator {
213 pub fn new() -> Self {
216 Self {
217 default_row_count: 1000.0,
218 row_scan_cost: 1.0,
219 index_lookup_cost: 0.1,
220 hash_probe_cost: 0.5,
221 nested_loop_cost: 2.0,
222 edge_traversal_cost: 1.5,
223 stats: Arc::new(NullProvider),
224 }
225 }
226
227 pub fn with_stats(provider: Arc<dyn StatsProvider>) -> Self {
231 Self {
232 stats: provider,
233 ..Self::new()
234 }
235 }
236
237 pub fn set_stats(&mut self, provider: Arc<dyn StatsProvider>) {
241 self.stats = provider;
242 }
243
244 pub fn estimate(&self, query: &QueryExpr) -> PlanCost {
246 match query {
247 QueryExpr::Table(tq) => self.estimate_table(tq),
248 QueryExpr::Graph(gq) => self.estimate_graph(gq),
249 QueryExpr::Join(jq) => self.estimate_join(jq),
250 QueryExpr::Path(pq) => self.estimate_path(pq),
251 QueryExpr::Vector(vq) => self.estimate_vector(vq),
252 QueryExpr::Hybrid(hq) => self.estimate_hybrid(hq),
253 QueryExpr::Explain(explain) => self.estimate(&explain.inner),
254 QueryExpr::Insert(_)
256 | QueryExpr::Update(_)
257 | QueryExpr::Delete(_)
258 | QueryExpr::Function(_)
259 | QueryExpr::CreateTable(_)
260 | QueryExpr::CreateCollection(_)
261 | QueryExpr::CreateVector(_)
262 | QueryExpr::DropTable(_)
263 | QueryExpr::DropGraph(_)
264 | QueryExpr::DropVector(_)
265 | QueryExpr::DropDocument(_)
266 | QueryExpr::DropKv(_)
267 | QueryExpr::DropCollection(_)
268 | QueryExpr::Truncate(_)
269 | QueryExpr::AlterTable(_)
270 | QueryExpr::CreateVcsRef(_)
271 | QueryExpr::DropVcsRef(_)
272 | QueryExpr::ForkStore(_)
273 | QueryExpr::PromoteFork(_)
274 | QueryExpr::DropFork(_)
275 | QueryExpr::VcsCommand(_)
276 | QueryExpr::GraphCommand(_)
277 | QueryExpr::SearchCommand(_)
278 | QueryExpr::CreateIndex(_)
279 | QueryExpr::DropIndex(_)
280 | QueryExpr::ProbabilisticCommand(_)
281 | QueryExpr::Ask(_)
282 | QueryExpr::SetConfig { .. }
283 | QueryExpr::ShowConfig { .. }
284 | QueryExpr::Scrub { .. }
285 | QueryExpr::SetSecret { .. }
286 | QueryExpr::DeleteSecret { .. }
287 | QueryExpr::SetKv { .. }
288 | QueryExpr::DeleteKv { .. }
289 | QueryExpr::ShowSecrets { .. }
290 | QueryExpr::SetTenant(_)
291 | QueryExpr::ShowTenant
292 | QueryExpr::CreateTimeSeries(_)
293 | QueryExpr::CreateMetric(_)
294 | QueryExpr::AlterMetric(_)
295 | QueryExpr::CreateSlo(_)
296 | QueryExpr::DropTimeSeries(_)
297 | QueryExpr::CreateQueue(_)
298 | QueryExpr::AlterQueue(_)
299 | QueryExpr::DropQueue(_)
300 | QueryExpr::QueueSelect(_)
301 | QueryExpr::QueueCommand(_)
302 | QueryExpr::KvCommand(_)
303 | QueryExpr::ConfigCommand(_)
304 | QueryExpr::CreateTree(_)
305 | QueryExpr::DropTree(_)
306 | QueryExpr::TreeCommand(_)
307 | QueryExpr::ExplainAlter(_)
308 | QueryExpr::TransactionControl(_)
309 | QueryExpr::MaintenanceCommand(_)
310 | QueryExpr::CreateSchema(_)
311 | QueryExpr::DropSchema(_)
312 | QueryExpr::CreateSequence(_)
313 | QueryExpr::DropSequence(_)
314 | QueryExpr::CopyFrom(_)
315 | QueryExpr::CreateView(_)
316 | QueryExpr::DropView(_)
317 | QueryExpr::RefreshMaterializedView(_)
318 | QueryExpr::CreatePolicy(_)
319 | QueryExpr::DropPolicy(_)
320 | QueryExpr::CreateServer(_)
321 | QueryExpr::DropServer(_)
322 | QueryExpr::CreateForeignTable(_)
323 | QueryExpr::DropForeignTable(_)
324 | QueryExpr::Grant(_)
325 | QueryExpr::Revoke(_)
326 | QueryExpr::AlterUser(_)
327 | QueryExpr::CreateUser(_)
328 | QueryExpr::CreateIamPolicy { .. }
329 | QueryExpr::DropIamPolicy { .. }
330 | QueryExpr::AttachPolicy { .. }
331 | QueryExpr::DetachPolicy { .. }
332 | QueryExpr::ShowPolicies { .. }
333 | QueryExpr::ShowEffectivePermissions { .. }
334 | QueryExpr::RankOf(_)
335 | QueryExpr::ApproxRankOf(_)
336 | QueryExpr::RankRange(_)
337 | QueryExpr::SimulatePolicy { .. }
338 | QueryExpr::LintPolicy { .. }
339 | QueryExpr::MigratePolicyMode { .. }
340 | QueryExpr::CreateMigration(_)
341 | QueryExpr::ApplyMigration(_)
342 | QueryExpr::RollbackMigration(_)
343 | QueryExpr::ExplainMigration(_)
344 | QueryExpr::EventsBackfill(_)
345 | QueryExpr::EventsBackfillStatus { .. } => PlanCost::new(1.0, 1.0, 0.0),
346 }
347 }
348
349 pub fn estimate_cardinality(&self, query: &QueryExpr) -> CardinalityEstimate {
351 match query {
352 QueryExpr::Table(tq) => self.estimate_table_cardinality(tq),
353 QueryExpr::Graph(gq) => self.estimate_graph_cardinality(gq),
354 QueryExpr::Join(jq) => self.estimate_join_cardinality(jq),
355 QueryExpr::Path(pq) => self.estimate_path_cardinality(pq),
356 QueryExpr::Vector(vq) => self.estimate_vector_cardinality(vq),
357 QueryExpr::Hybrid(hq) => self.estimate_hybrid_cardinality(hq),
358 QueryExpr::Explain(explain) => self.estimate_cardinality(&explain.inner),
359 QueryExpr::Insert(_)
361 | QueryExpr::Update(_)
362 | QueryExpr::Delete(_)
363 | QueryExpr::Function(_)
364 | QueryExpr::CreateTable(_)
365 | QueryExpr::CreateCollection(_)
366 | QueryExpr::CreateVector(_)
367 | QueryExpr::DropTable(_)
368 | QueryExpr::DropGraph(_)
369 | QueryExpr::DropVector(_)
370 | QueryExpr::DropDocument(_)
371 | QueryExpr::DropKv(_)
372 | QueryExpr::DropCollection(_)
373 | QueryExpr::Truncate(_)
374 | QueryExpr::AlterTable(_)
375 | QueryExpr::CreateVcsRef(_)
376 | QueryExpr::DropVcsRef(_)
377 | QueryExpr::ForkStore(_)
378 | QueryExpr::PromoteFork(_)
379 | QueryExpr::DropFork(_)
380 | QueryExpr::VcsCommand(_)
381 | QueryExpr::GraphCommand(_)
382 | QueryExpr::SearchCommand(_)
383 | QueryExpr::CreateIndex(_)
384 | QueryExpr::DropIndex(_)
385 | QueryExpr::ProbabilisticCommand(_)
386 | QueryExpr::Ask(_)
387 | QueryExpr::SetConfig { .. }
388 | QueryExpr::ShowConfig { .. }
389 | QueryExpr::Scrub { .. }
390 | QueryExpr::SetSecret { .. }
391 | QueryExpr::DeleteSecret { .. }
392 | QueryExpr::SetKv { .. }
393 | QueryExpr::DeleteKv { .. }
394 | QueryExpr::ShowSecrets { .. }
395 | QueryExpr::SetTenant(_)
396 | QueryExpr::ShowTenant
397 | QueryExpr::CreateTimeSeries(_)
398 | QueryExpr::CreateMetric(_)
399 | QueryExpr::AlterMetric(_)
400 | QueryExpr::CreateSlo(_)
401 | QueryExpr::DropTimeSeries(_)
402 | QueryExpr::CreateQueue(_)
403 | QueryExpr::AlterQueue(_)
404 | QueryExpr::DropQueue(_)
405 | QueryExpr::QueueSelect(_)
406 | QueryExpr::QueueCommand(_)
407 | QueryExpr::KvCommand(_)
408 | QueryExpr::ConfigCommand(_)
409 | QueryExpr::CreateTree(_)
410 | QueryExpr::DropTree(_)
411 | QueryExpr::TreeCommand(_)
412 | QueryExpr::ExplainAlter(_)
413 | QueryExpr::TransactionControl(_)
414 | QueryExpr::MaintenanceCommand(_)
415 | QueryExpr::CreateSchema(_)
416 | QueryExpr::DropSchema(_)
417 | QueryExpr::CreateSequence(_)
418 | QueryExpr::DropSequence(_)
419 | QueryExpr::CopyFrom(_)
420 | QueryExpr::CreateView(_)
421 | QueryExpr::DropView(_)
422 | QueryExpr::RefreshMaterializedView(_)
423 | QueryExpr::CreatePolicy(_)
424 | QueryExpr::DropPolicy(_)
425 | QueryExpr::CreateServer(_)
426 | QueryExpr::DropServer(_)
427 | QueryExpr::CreateForeignTable(_)
428 | QueryExpr::DropForeignTable(_)
429 | QueryExpr::Grant(_)
430 | QueryExpr::Revoke(_)
431 | QueryExpr::AlterUser(_)
432 | QueryExpr::CreateUser(_)
433 | QueryExpr::CreateIamPolicy { .. }
434 | QueryExpr::DropIamPolicy { .. }
435 | QueryExpr::AttachPolicy { .. }
436 | QueryExpr::DetachPolicy { .. }
437 | QueryExpr::ShowPolicies { .. }
438 | QueryExpr::ShowEffectivePermissions { .. }
439 | QueryExpr::RankOf(_)
440 | QueryExpr::ApproxRankOf(_)
441 | QueryExpr::RankRange(_)
442 | QueryExpr::SimulatePolicy { .. }
443 | QueryExpr::LintPolicy { .. }
444 | QueryExpr::MigratePolicyMode { .. }
445 | QueryExpr::CreateMigration(_)
446 | QueryExpr::ApplyMigration(_)
447 | QueryExpr::RollbackMigration(_)
448 | QueryExpr::ExplainMigration(_)
449 | QueryExpr::EventsBackfill(_)
450 | QueryExpr::EventsBackfillStatus { .. } => CardinalityEstimate::new(1.0, 1.0),
451 }
452 }
453
454 fn estimate_table(&self, query: &TableQuery) -> PlanCost {
459 let cardinality = self.estimate_table_cardinality(query);
460
461 let cpu = cardinality.rows * self.row_scan_cost;
462
463 let io = self.estimate_table_io(query, cardinality.rows);
466
467 let memory = cardinality.rows * 100.0; PlanCost::new(cpu, io, memory)
470 }
471
472 fn estimate_table_io(&self, query: &TableQuery, result_rows: f64) -> f64 {
479 const ROWS_PER_PAGE: f64 = 100.0;
480
481 let table_stats = self.stats.table_stats(&query.table);
483 let heap_pages = table_stats
484 .map(|s| s.page_count as f64)
485 .unwrap_or_else(|| (result_rows / ROWS_PER_PAGE).max(1.0));
486
487 if let Some(filter) = reddb_rql::sql_lowering::effective_table_filter(query) {
490 if let Some(col) = first_filter_column(&filter, &query.table) {
491 if let Some(idx) = self.stats.index_stats(&query.table, col) {
492 return idx.correlated_io_cost(result_rows, heap_pages);
493 }
494 }
495 }
496
497 (result_rows / ROWS_PER_PAGE).ceil()
499 }
500
501 fn estimate_table_cardinality(&self, query: &TableQuery) -> CardinalityEstimate {
502 let base_rows = self
505 .stats
506 .table_stats(&query.table)
507 .map(|s| s.row_count as f64)
508 .unwrap_or(self.default_row_count);
509
510 let mut estimate = CardinalityEstimate::full_scan(base_rows);
511
512 if let Some(filter) = reddb_rql::sql_lowering::effective_table_filter(query) {
515 let selectivity = self.filter_selectivity(&filter, &query.table);
516 estimate = estimate.with_filter(selectivity);
517 }
518
519 if let Some(limit) = query.limit {
521 estimate.rows = estimate.rows.min(limit as f64);
522 }
523
524 estimate
525 }
526
527 fn filter_selectivity(&self, filter: &AstFilter, table: &str) -> f64 {
540 match filter {
541 AstFilter::Compare { field, op, value } => {
542 let column = column_name_for_table(field, table);
543 match op {
544 CompareOp::Eq => self.eq_selectivity(table, column, value),
545 CompareOp::Ne => 1.0 - self.eq_selectivity(table, column, value),
546 CompareOp::Lt | CompareOp::Le => {
547 self.range_selectivity(table, column, None, Some(value))
548 }
549 CompareOp::Gt | CompareOp::Ge => {
550 self.range_selectivity(table, column, Some(value), None)
551 }
552 }
553 }
554 AstFilter::Between {
555 field, low, high, ..
556 } => {
557 let column = column_name_for_table(field, table);
558 self.range_selectivity(table, column, Some(low), Some(high))
559 }
560 AstFilter::In { field, values, .. } => {
561 let column = column_name_for_table(field, table);
562 if let Some(c) = column {
566 if let Some(mcv) = self.stats.column_mcv(table, c) {
567 let mut hits: f64 = 0.0;
568 let mut residual_count = 0usize;
569 for v in values {
570 if let Some(cv) = column_value_from(v) {
571 if let Some(freq) = mcv.frequency_of(&cv) {
572 hits += freq;
573 } else {
574 residual_count += 1;
575 }
576 } else {
577 residual_count += 1;
578 }
579 }
580 let total = mcv.total_frequency();
581 let distinct = self.stats.distinct_values(table, c).unwrap_or(100);
582 let non_mcv_distinct =
583 distinct.saturating_sub(mcv.values.len() as u64).max(1);
584 let per_residual = (1.0 - total) / non_mcv_distinct as f64;
585 let estimate = hits + (residual_count as f64) * per_residual;
586 return estimate.clamp(0.0, 1.0).min(0.5);
587 }
588 if let Some(s) = self.stats.index_stats(table, c) {
589 return (s.point_selectivity() * values.len() as f64).min(0.5);
590 }
591 }
592 (values.len() as f64 * 0.01).min(0.5)
593 }
594 AstFilter::Like { .. } => 0.1,
595 AstFilter::StartsWith { .. } => 0.15,
596 AstFilter::EndsWith { .. } => 0.15,
597 AstFilter::Contains { .. } => 0.1,
598 AstFilter::IsNull { .. } => 0.01,
599 AstFilter::IsNotNull { .. } => 0.99,
600 AstFilter::And(left, right) => {
601 self.filter_selectivity(left, table) * self.filter_selectivity(right, table)
602 }
603 AstFilter::Or(left, right) => {
604 let s1 = self.filter_selectivity(left, table);
605 let s2 = self.filter_selectivity(right, table);
606 s1 + s2 - (s1 * s2)
607 }
608 AstFilter::Not(inner) => 1.0 - self.filter_selectivity(inner, table),
609 AstFilter::CompareFields { .. } => {
610 0.1
614 }
615 AstFilter::CompareExpr { .. } => {
616 0.1
620 }
621 }
622 }
623
624 fn estimate_graph(&self, query: &GraphQuery) -> PlanCost {
629 let cardinality = self.estimate_graph_cardinality(query);
630
631 let nodes = query.pattern.nodes.len() as f64;
633 let edges = query.pattern.edges.len() as f64;
634
635 let cpu = cardinality.rows * self.edge_traversal_cost * (nodes + edges);
636 let io = cardinality.rows * 0.1; let memory = cardinality.rows * 200.0; PlanCost::new(cpu, io, memory)
640 }
641
642 fn estimate_graph_cardinality(&self, query: &GraphQuery) -> CardinalityEstimate {
643 let nodes = query.pattern.nodes.len() as f64;
644 let edges = query.pattern.edges.len() as f64;
645
646 let base_rows = self.default_row_count;
648 let edge_factor = 0.1_f64.powf(edges); let mut estimate = CardinalityEstimate::new(base_rows * nodes * edge_factor, edge_factor);
651 estimate.confidence = 0.5; if let Some(ref filter) = query.filter {
655 let selectivity = Self::estimate_filter_selectivity(filter);
656 estimate = estimate.with_filter(selectivity);
657 }
658
659 estimate
660 }
661
662 fn estimate_join(&self, query: &JoinQuery) -> PlanCost {
667 let left_cost = self.estimate(&query.left);
668 let right_cost = self.estimate(&query.right);
669
670 let left_card = self.estimate_cardinality(&query.left);
671 let right_card = self.estimate_cardinality(&query.right);
672
673 let build_cpu = left_card.rows * self.hash_probe_cost;
680 let probe_cpu = right_card.rows * self.hash_probe_cost;
681 let join_memory = left_card.rows * 100.0; let build_op = PlanCost::with_startup(build_cpu, 0.0, join_memory, build_cpu);
685 let probe_op = PlanCost::new(probe_cpu, 0.0, 0.0);
687
688 let after_build = left_cost.combine_blocking(&build_op);
690 after_build
691 .combine_pipelined(&right_cost)
692 .combine_pipelined(&probe_op)
693 }
694
695 fn estimate_join_cardinality(&self, query: &JoinQuery) -> CardinalityEstimate {
696 let left = self.estimate_cardinality(&query.left);
697 let right = self.estimate_cardinality(&query.right);
698
699 let selectivity = match query.join_type {
701 JoinType::Inner => 0.1, JoinType::LeftOuter => 1.0, JoinType::RightOuter => 1.0, JoinType::FullOuter => 1.0, JoinType::Cross => 1.0, };
707
708 CardinalityEstimate::new(
709 left.rows * right.rows * selectivity,
710 left.selectivity * right.selectivity * selectivity,
711 )
712 }
713
714 fn estimate_path(&self, query: &PathQuery) -> PlanCost {
719 let max_hops = query.max_length;
721 let branching_factor: f64 = 5.0; let nodes_visited = branching_factor.powf(max_hops as f64).min(10000.0);
724 let cpu = nodes_visited * self.edge_traversal_cost;
725 let io = nodes_visited * 0.1;
726 let memory = nodes_visited * 50.0; PlanCost::new(cpu, io, memory)
729 }
730
731 fn estimate_path_cardinality(&self, _query: &PathQuery) -> CardinalityEstimate {
732 let max_paths = 10.0;
734 CardinalityEstimate::new(max_paths, 0.001)
735 }
736
737 fn estimate_vector(&self, query: &VectorQuery) -> PlanCost {
742 let k = query.k as f64;
745
746 let hnsw_cost = 100.0 * (1.0 + k.ln()); let filter_cost = if reddb_rql::sql_lowering::effective_vector_filter(query).is_some() {
753 50.0
754 } else {
755 0.0
756 };
757
758 let cpu = hnsw_cost + filter_cost;
759 let io = 20.0; let memory = k * 32.0 + 1000.0; PlanCost::with_startup(cpu, io, memory, hnsw_cost * 0.5)
767 }
768
769 fn estimate_vector_cardinality(&self, query: &VectorQuery) -> CardinalityEstimate {
770 let k = query.k as f64;
772 CardinalityEstimate::new(k, 0.1)
773 }
774
775 fn estimate_hybrid(&self, query: &HybridQuery) -> PlanCost {
780 let structured_cost = self.estimate(&query.structured);
782 let vector_cost = self.estimate_vector(&query.vector);
783
784 let fusion_overhead = match &query.fusion {
786 reddb_rql::ast::FusionStrategy::Rerank { .. } => 50.0,
787 reddb_rql::ast::FusionStrategy::FilterThenSearch => 10.0,
788 reddb_rql::ast::FusionStrategy::SearchThenFilter => 10.0,
789 reddb_rql::ast::FusionStrategy::RRF { .. } => 30.0,
790 reddb_rql::ast::FusionStrategy::Intersection => 20.0,
791 reddb_rql::ast::FusionStrategy::Union { .. } => 40.0,
792 };
793
794 PlanCost::new(
795 structured_cost.cpu + vector_cost.cpu + fusion_overhead,
796 structured_cost.io + vector_cost.io,
797 structured_cost.memory + vector_cost.memory,
798 )
799 }
800
801 fn estimate_hybrid_cardinality(&self, query: &HybridQuery) -> CardinalityEstimate {
802 let structured_card = self.estimate_cardinality(&query.structured);
803 let vector_card = self.estimate_vector_cardinality(&query.vector);
804
805 let rows = match &query.fusion {
807 reddb_rql::ast::FusionStrategy::Intersection => {
808 structured_card.rows.min(vector_card.rows)
809 }
810 reddb_rql::ast::FusionStrategy::Union { .. } => structured_card.rows + vector_card.rows,
811 _ => vector_card.rows, };
813
814 CardinalityEstimate::new(rows, 0.2)
815 }
816
817 fn estimate_filter_selectivity(filter: &AstFilter) -> f64 {
822 match filter {
823 AstFilter::Compare { op, .. } => {
824 match op {
825 CompareOp::Eq => 0.01, CompareOp::Ne => 0.99, CompareOp::Lt | CompareOp::Le => 0.3,
828 CompareOp::Gt | CompareOp::Ge => 0.3,
829 }
830 }
831 AstFilter::Between { .. } => 0.25,
832 AstFilter::In { values, .. } => {
833 (values.len() as f64 * 0.01).min(0.5)
835 }
836 AstFilter::Like { .. } => 0.1,
837 AstFilter::StartsWith { .. } => 0.15,
838 AstFilter::EndsWith { .. } => 0.15,
839 AstFilter::Contains { .. } => 0.1,
840 AstFilter::IsNull { .. } => 0.01,
841 AstFilter::IsNotNull { .. } => 0.99,
842 AstFilter::And(left, right) => {
843 Self::estimate_filter_selectivity(left) * Self::estimate_filter_selectivity(right)
844 }
845 AstFilter::Or(left, right) => {
846 let s1 = Self::estimate_filter_selectivity(left);
847 let s2 = Self::estimate_filter_selectivity(right);
848 s1 + s2 - (s1 * s2) }
850 AstFilter::Not(inner) => 1.0 - Self::estimate_filter_selectivity(inner),
851 AstFilter::CompareFields { .. } => 0.1,
852 AstFilter::CompareExpr { .. } => 0.1,
853 }
854 }
855}
856
857impl CostEstimator {
858 fn eq_selectivity(&self, table: &str, column: Option<&str>, value: &Value) -> f64 {
866 if let Some(col) = column {
867 if let Some(mcv) = self.stats.column_mcv(table, col) {
869 if let Some(cv) = column_value_from(value) {
870 if let Some(freq) = mcv.frequency_of(&cv) {
871 return freq;
872 }
873 let total = mcv.total_frequency();
875 let distinct = self.stats.distinct_values(table, col).unwrap_or(100);
876 let non_mcv_distinct = distinct.saturating_sub(mcv.values.len() as u64).max(1);
877 return ((1.0 - total) / non_mcv_distinct as f64).clamp(0.0, 1.0);
878 }
879 }
880 if let Some(s) = self.stats.index_stats(table, col) {
882 return s.point_selectivity();
883 }
884 }
885 0.01
887 }
888
889 fn range_selectivity(
900 &self,
901 table: &str,
902 column: Option<&str>,
903 lo: Option<&Value>,
904 hi: Option<&Value>,
905 ) -> f64 {
906 if let Some(col) = column {
907 if let Some(h) = self.stats.column_histogram(table, col) {
909 let lo_cv = lo.and_then(column_value_from);
910 let hi_cv = hi.and_then(column_value_from);
911 return h.range_selectivity(lo_cv.as_ref(), hi_cv.as_ref());
912 }
913 if let Some(s) = self.stats.index_stats(table, col) {
915 let cap = if lo.is_some() && hi.is_some() {
916 0.25
917 } else {
918 0.3
919 };
920 return (s.point_selectivity() * (s.distinct_keys as f64 / 2.0)).min(cap);
921 }
922 }
923 if lo.is_some() && hi.is_some() {
925 0.25
926 } else {
927 0.3
928 }
929 }
930}
931
932impl Default for CostEstimator {
933 fn default() -> Self {
934 Self::new()
935 }
936}
937
938fn column_value_from(v: &reddb_types::Value) -> Option<super::histogram::ColumnValue> {
943 use super::histogram::ColumnValue;
944 use reddb_types::Value;
945 match v {
946 Value::Integer(i) | Value::BigInt(i) => Some(ColumnValue::Int(*i)),
947 Value::UnsignedInteger(u) => Some(ColumnValue::Int(*u as i64)),
948 Value::Float(f) if f.is_finite() => Some(ColumnValue::Float(*f)),
949 Value::Text(s) => Some(ColumnValue::Text(s.to_string())),
950 Value::Email(s)
951 | Value::Url(s)
952 | Value::NodeRef(s)
953 | Value::EdgeRef(s)
954 | Value::TableRef(s)
955 | Value::Password(s) => Some(ColumnValue::Text(s.clone())),
956 Value::Timestamp(t) => Some(ColumnValue::Int(*t)),
957 Value::Duration(d) => Some(ColumnValue::Int(*d)),
958 Value::TimestampMs(t) => Some(ColumnValue::Int(*t)),
959 Value::Decimal(d) => Some(ColumnValue::Int(*d)),
960 Value::Date(d) => Some(ColumnValue::Int(i64::from(*d))),
961 Value::Time(t) => Some(ColumnValue::Int(i64::from(*t))),
962 Value::Phone(p) => Some(ColumnValue::Int(*p as i64)),
963 Value::Semver(v) => Some(ColumnValue::Int(i64::from(*v))),
964 Value::Port(v) => Some(ColumnValue::Int(i64::from(*v))),
965 Value::PageRef(v) => Some(ColumnValue::Int(i64::from(*v))),
966 Value::EnumValue(v) => Some(ColumnValue::Int(i64::from(*v))),
967 Value::Latitude(v) => Some(ColumnValue::Int(i64::from(*v))),
968 Value::Longitude(v) => Some(ColumnValue::Int(i64::from(*v))),
969 _ => None,
974 }
975}
976
977fn first_filter_column<'a>(filter: &'a AstFilter, table: &str) -> Option<&'a str> {
982 match filter {
983 AstFilter::Compare { field, .. } => column_name_for_table(field, table),
984 AstFilter::Between { field, .. } => column_name_for_table(field, table),
985 AstFilter::And(l, r) => {
986 first_filter_column(l, table).or_else(|| first_filter_column(r, table))
987 }
988 _ => None,
989 }
990}
991
992fn column_name_for_table<'a>(field: &'a FieldRef, table: &str) -> Option<&'a str> {
994 match field {
995 FieldRef::TableColumn { table: t, column } if t == table || t.is_empty() => {
996 Some(column.as_str())
997 }
998 _ => None,
1000 }
1001}
1002
1003#[cfg(test)]
1004mod tests {
1005 use super::super::stats_provider::StaticProvider;
1006 use super::*;
1007 use crate::storage::index::{IndexKind, IndexStats};
1008 use reddb_rql::ast::{FieldRef, Projection};
1009 use reddb_types::Value;
1010
1011 fn eq_filter(table: &str, column: &str, value: i64) -> AstFilter {
1012 AstFilter::Compare {
1013 field: FieldRef::column(table, column),
1014 op: CompareOp::Eq,
1015 value: Value::Integer(value),
1016 }
1017 }
1018
1019 fn table_query(name: &str, filter: Option<AstFilter>) -> TableQuery {
1020 TableQuery {
1021 table: name.to_string(),
1022 source: None,
1023 alias: None,
1024 select_items: Vec::new(),
1025 columns: vec![Projection::All],
1026 where_expr: None,
1027 filter,
1028 group_by_exprs: Vec::new(),
1029 group_by: Vec::new(),
1030 having_expr: None,
1031 having: None,
1032 order_by: vec![],
1033 limit: None,
1034 limit_param: None,
1035 offset: None,
1036 offset_param: None,
1037 expand: None,
1038 as_of: None,
1039 sessionize: None,
1040 distinct: false,
1041 }
1042 }
1043
1044 #[test]
1045 fn injected_row_count_overrides_default() {
1046 let provider = Arc::new(StaticProvider::new().with_table(
1047 "users",
1048 TableStats {
1049 row_count: 50_000,
1050 avg_row_size: 256,
1051 page_count: 500,
1052 columns: vec![],
1053 },
1054 ));
1055 let estimator = CostEstimator::with_stats(provider);
1056 let q = table_query("users", None);
1057 let card = estimator.estimate_table_cardinality(&q);
1058 assert_eq!(card.rows, 50_000.0);
1060 }
1061
1062 #[test]
1063 fn stats_aware_eq_selectivity_beats_default() {
1064 let provider = Arc::new(
1065 StaticProvider::new()
1066 .with_table(
1067 "users",
1068 TableStats {
1069 row_count: 1_000_000,
1070 avg_row_size: 256,
1071 page_count: 10_000,
1072 columns: vec![],
1073 },
1074 )
1075 .with_index(
1076 "users",
1077 "email",
1078 IndexStats {
1079 entries: 1_000_000,
1080 distinct_keys: 1_000_000,
1081 approx_bytes: 0,
1082 kind: IndexKind::Hash,
1083 has_bloom: true,
1084 index_correlation: 0.0,
1085 },
1086 ),
1087 );
1088 let estimator = CostEstimator::with_stats(provider);
1089 let q = table_query("users", Some(eq_filter("users", "email", 0)));
1090 let card = estimator.estimate_table_cardinality(&q);
1091 assert!(card.rows < 2.0, "expected ~1 row, got {}", card.rows);
1093 }
1094
1095 #[test]
1096 fn fallback_when_no_index_stats() {
1097 let provider = Arc::new(StaticProvider::new().with_table(
1098 "users",
1099 TableStats {
1100 row_count: 1_000_000,
1101 avg_row_size: 256,
1102 page_count: 10_000,
1103 columns: vec![],
1104 },
1105 ));
1106 let estimator = CostEstimator::with_stats(provider);
1107 let q = table_query("users", Some(eq_filter("users", "email", 0)));
1108 let card = estimator.estimate_table_cardinality(&q);
1109 assert!((card.rows - 10_000.0).abs() < 1.0);
1111 }
1112
1113 #[test]
1114 fn null_provider_keeps_legacy_behaviour() {
1115 let estimator = CostEstimator::new();
1116 let q = table_query("whatever", Some(eq_filter("whatever", "id", 1)));
1117 let card = estimator.estimate_table_cardinality(&q);
1118 assert!((card.rows - 10.0).abs() < 1.0);
1120 }
1121
1122 #[test]
1123 fn and_combines_stats_selectivities() {
1124 let provider = Arc::new(
1125 StaticProvider::new()
1126 .with_table(
1127 "t",
1128 TableStats {
1129 row_count: 100_000,
1130 avg_row_size: 64,
1131 page_count: 100,
1132 columns: vec![],
1133 },
1134 )
1135 .with_index(
1136 "t",
1137 "a",
1138 IndexStats {
1139 entries: 100_000,
1140 distinct_keys: 10,
1141 approx_bytes: 0,
1142 kind: IndexKind::BTree,
1143 has_bloom: false,
1144 index_correlation: 0.0,
1145 },
1146 )
1147 .with_index(
1148 "t",
1149 "b",
1150 IndexStats {
1151 entries: 100_000,
1152 distinct_keys: 1000,
1153 approx_bytes: 0,
1154 kind: IndexKind::BTree,
1155 has_bloom: false,
1156 index_correlation: 0.0,
1157 },
1158 ),
1159 );
1160 let estimator = CostEstimator::with_stats(provider);
1161 let filter = AstFilter::And(
1162 Box::new(eq_filter("t", "a", 1)),
1163 Box::new(eq_filter("t", "b", 1)),
1164 );
1165 let q = table_query("t", Some(filter));
1166 let card = estimator.estimate_table_cardinality(&q);
1167 assert!(card.rows < 15.0, "got {}", card.rows);
1169 }
1170
1171 #[test]
1172 fn test_table_cost_estimation() {
1173 let estimator = CostEstimator::new();
1174
1175 let query = QueryExpr::Table(TableQuery {
1176 table: "hosts".to_string(),
1177 source: None,
1178 alias: None,
1179 select_items: Vec::new(),
1180 columns: vec![Projection::All],
1181 where_expr: None,
1182 filter: None,
1183 group_by_exprs: Vec::new(),
1184 group_by: Vec::new(),
1185 having_expr: None,
1186 having: None,
1187 order_by: vec![],
1188 limit: None,
1189 limit_param: None,
1190 offset: None,
1191 offset_param: None,
1192 expand: None,
1193 as_of: None,
1194 sessionize: None,
1195 distinct: false,
1196 });
1197
1198 let cost = estimator.estimate(&query);
1199 assert!(cost.cpu > 0.0);
1200 assert!(cost.total > 0.0);
1201 }
1202
1203 #[test]
1204 fn test_filter_selectivity() {
1205 let eq_filter = AstFilter::Compare {
1206 field: FieldRef::column("hosts", "id"),
1207 op: CompareOp::Eq,
1208 value: Value::Integer(1),
1209 };
1210 assert!(CostEstimator::estimate_filter_selectivity(&eq_filter) < 0.1);
1211
1212 let ne_filter = AstFilter::Compare {
1213 field: FieldRef::column("hosts", "id"),
1214 op: CompareOp::Ne,
1215 value: Value::Integer(1),
1216 };
1217 assert!(CostEstimator::estimate_filter_selectivity(&ne_filter) > 0.9);
1218 }
1219
1220 #[test]
1221 fn test_and_selectivity() {
1222 let and_filter = AstFilter::And(
1223 Box::new(AstFilter::Compare {
1224 field: FieldRef::column("hosts", "a"),
1225 op: CompareOp::Eq,
1226 value: Value::Integer(1),
1227 }),
1228 Box::new(AstFilter::Compare {
1229 field: FieldRef::column("hosts", "b"),
1230 op: CompareOp::Eq,
1231 value: Value::Integer(2),
1232 }),
1233 );
1234
1235 let selectivity = CostEstimator::estimate_filter_selectivity(&and_filter);
1236 assert!(selectivity < 0.01); }
1238
1239 #[test]
1240 fn test_cardinality_with_limit() {
1241 let estimator = CostEstimator::new();
1242
1243 let query = TableQuery {
1244 table: "hosts".to_string(),
1245 source: None,
1246 alias: None,
1247 select_items: Vec::new(),
1248 columns: vec![Projection::All],
1249 where_expr: None,
1250 filter: None,
1251 group_by_exprs: Vec::new(),
1252 group_by: Vec::new(),
1253 having_expr: None,
1254 having: None,
1255 order_by: vec![],
1256 limit: Some(10),
1257 limit_param: None,
1258 offset: None,
1259 offset_param: None,
1260 expand: None,
1261 as_of: None,
1262 sessionize: None,
1263 distinct: false,
1264 };
1265
1266 let card = estimator.estimate_table_cardinality(&query);
1267 assert!(card.rows <= 10.0);
1268 }
1269
1270 #[test]
1275 fn startup_zero_for_full_scan() {
1276 let estimator = CostEstimator::new();
1280 let q = table_query("any_table", None);
1281 let cost = estimator.estimate(&QueryExpr::Table(q));
1282 assert_eq!(cost.startup_cost, 0.0, "full scan must have zero startup");
1283 assert!(cost.total > 0.0);
1284 }
1285
1286 #[test]
1287 fn startup_nonzero_for_blocking_combine() {
1288 let input = PlanCost::new(100.0, 10.0, 50.0); let blocker = PlanCost::new(20.0, 0.0, 10.0); let composed = input.combine_blocking(&blocker);
1293 assert_eq!(composed.startup_cost, input.total);
1295 assert_eq!(composed.total, input.total + blocker.total);
1297 assert!(composed.startup_cost > 0.0);
1298 }
1299
1300 #[test]
1301 fn pipelined_combine_adds_startup_directly() {
1302 let upstream = PlanCost::with_startup(50.0, 5.0, 10.0, 30.0);
1303 let downstream = PlanCost::with_startup(20.0, 0.0, 0.0, 5.0);
1304 let composed = upstream.combine_pipelined(&downstream);
1305 assert_eq!(composed.startup_cost, 30.0 + 5.0);
1306 assert_eq!(composed.total, upstream.total + downstream.total);
1307 }
1308
1309 #[test]
1310 fn cost_prefers_low_startup_when_limit_small() {
1311 let fast_first = PlanCost {
1314 cpu: 100.0,
1315 io: 10.0,
1316 network: 0.0,
1317 memory: 50.0,
1318 startup_cost: 5.0,
1319 total: 200.0,
1320 };
1321 let slow_first = PlanCost {
1322 cpu: 100.0,
1323 io: 10.0,
1324 network: 0.0,
1325 memory: 50.0,
1326 startup_cost: 150.0,
1327 total: 200.0,
1328 };
1329 assert_eq!(
1331 fast_first.prefer_over(&slow_first, Some(10), 10_000.0),
1332 std::cmp::Ordering::Less
1333 );
1334 }
1335
1336 #[test]
1337 fn cost_prefers_low_total_when_no_limit() {
1338 let low_total = PlanCost {
1340 cpu: 50.0,
1341 io: 5.0,
1342 network: 0.0,
1343 memory: 0.0,
1344 startup_cost: 30.0,
1345 total: 100.0,
1346 };
1347 let high_total = PlanCost {
1348 cpu: 100.0,
1349 io: 10.0,
1350 network: 0.0,
1351 memory: 0.0,
1352 startup_cost: 5.0,
1353 total: 200.0,
1354 };
1355 assert_eq!(
1356 low_total.prefer_over(&high_total, None, 10_000.0),
1357 std::cmp::Ordering::Less
1358 );
1359 }
1360
1361 #[test]
1362 fn limit_threshold_falls_back_to_total_when_limit_large() {
1363 let low_total = PlanCost {
1365 cpu: 50.0,
1366 io: 5.0,
1367 network: 0.0,
1368 memory: 0.0,
1369 startup_cost: 30.0,
1370 total: 100.0,
1371 };
1372 let low_startup = PlanCost {
1373 cpu: 100.0,
1374 io: 10.0,
1375 network: 0.0,
1376 memory: 0.0,
1377 startup_cost: 5.0,
1378 total: 200.0,
1379 };
1380 assert_eq!(
1381 low_total.prefer_over(&low_startup, Some(5000), 10_000.0),
1382 std::cmp::Ordering::Less
1383 );
1384 }
1385
1386 #[test]
1387 fn hash_join_startup_includes_build_cost() {
1388 let left = PlanCost::new(80.0, 8.0, 100.0); let build = PlanCost::with_startup(50.0, 0.0, 200.0, 50.0); let after_build = left.combine_blocking(&build);
1394 assert!(
1395 after_build.startup_cost >= left.total,
1396 "after-build startup ({}) must absorb left.total ({})",
1397 after_build.startup_cost,
1398 left.total
1399 );
1400 assert!(after_build.total >= after_build.startup_cost);
1401 }
1402
1403 #[test]
1404 fn vector_search_reports_nonzero_startup() {
1405 let estimator = CostEstimator::new();
1409 let v = PlanCost::with_startup(150.0, 20.0, 1320.0, 50.0);
1412 assert!(v.startup_cost > 0.0);
1413 assert!(v.startup_cost < v.total);
1414 let _ = estimator; }
1416
1417 #[test]
1418 fn with_startup_clamps_total_below_startup() {
1419 let cost = PlanCost::with_startup(1.0, 0.0, 0.0, 100.0);
1421 assert!(cost.total >= cost.startup_cost);
1422 }
1423
1424 #[test]
1425 fn default_plancost_has_zero_startup() {
1426 let c = PlanCost::default();
1427 assert_eq!(c.startup_cost, 0.0);
1428 assert_eq!(c.total, 0.0);
1429 }
1430
1431 use super::super::histogram::{ColumnValue, Histogram, MostCommonValues};
1436
1437 fn provider_with_skew() -> Arc<StaticProvider> {
1438 let mut sample: Vec<ColumnValue> = Vec::new();
1442 for i in 0..80 {
1443 sample.push(ColumnValue::Int(i % 10));
1444 }
1445 for i in 0..20 {
1446 sample.push(ColumnValue::Int(10 + i * 50));
1447 }
1448 let h = Histogram::equi_depth_from_sample(sample, 10);
1449
1450 let mcv = MostCommonValues::new(vec![
1451 (ColumnValue::Text("boss".to_string()), 0.5),
1452 (ColumnValue::Text("intern".to_string()), 0.05),
1453 ]);
1454
1455 Arc::new(
1456 StaticProvider::new()
1457 .with_table(
1458 "people",
1459 TableStats {
1460 row_count: 100_000,
1461 avg_row_size: 64,
1462 page_count: 100,
1463 columns: vec![],
1464 },
1465 )
1466 .with_histogram("people", "score", h)
1467 .with_mcv("people", "role", mcv),
1468 )
1469 }
1470
1471 #[test]
1472 fn eq_uses_mcv_when_value_is_tracked() {
1473 let provider = provider_with_skew();
1474 let estimator = CostEstimator::with_stats(provider);
1475 let filter = AstFilter::Compare {
1476 field: FieldRef::column("people", "role"),
1477 op: CompareOp::Eq,
1478 value: Value::text("boss".to_string()),
1479 };
1480 let s = estimator.filter_selectivity(&filter, "people");
1483 assert!(
1484 (s - 0.5).abs() < 1e-9,
1485 "MCV-tracked equality should report exact frequency, got {s}"
1486 );
1487 }
1488
1489 #[test]
1490 fn eq_uses_residual_for_non_mcv_value() {
1491 let provider = provider_with_skew();
1492 let estimator = CostEstimator::with_stats(provider);
1493 let filter = AstFilter::Compare {
1494 field: FieldRef::column("people", "role"),
1495 op: CompareOp::Eq,
1496 value: Value::text("staff".to_string()),
1497 };
1498 let s = estimator.filter_selectivity(&filter, "people");
1502 assert!(s > 0.0 && s < 0.01, "residual eq should be tiny, got {s}");
1503 }
1504
1505 #[test]
1506 fn ne_is_one_minus_eq_under_mcv() {
1507 let provider = provider_with_skew();
1508 let estimator = CostEstimator::with_stats(provider);
1509 let filter = AstFilter::Compare {
1510 field: FieldRef::column("people", "role"),
1511 op: CompareOp::Ne,
1512 value: Value::text("boss".to_string()),
1513 };
1514 let s = estimator.filter_selectivity(&filter, "people");
1515 assert!((s - 0.5).abs() < 1e-9, "Ne selectivity = 0.5, got {s}");
1517 }
1518
1519 #[test]
1520 fn range_uses_histogram_when_present() {
1521 let provider = provider_with_skew();
1522 let estimator = CostEstimator::with_stats(provider);
1523 let filter = AstFilter::Compare {
1524 field: FieldRef::column("people", "score"),
1525 op: CompareOp::Le,
1526 value: Value::Integer(9),
1527 };
1528 let s = estimator.filter_selectivity(&filter, "people");
1531 assert!(
1532 s > 0.5,
1533 "histogram-based range selectivity should beat 0.3, got {s}"
1534 );
1535 }
1536
1537 #[test]
1538 fn between_uses_histogram() {
1539 let provider = provider_with_skew();
1540 let estimator = CostEstimator::with_stats(provider);
1541 let filter = AstFilter::Between {
1542 field: FieldRef::column("people", "score"),
1543 low: Value::Integer(0),
1544 high: Value::Integer(9),
1545 };
1546 let s = estimator.filter_selectivity(&filter, "people");
1547 assert!(s > 0.5, "BETWEEN should use histogram too, got {s}");
1548 }
1549
1550 #[test]
1551 fn graceful_fallback_when_histogram_absent() {
1552 let provider = Arc::new(StaticProvider::new().with_table(
1555 "people",
1556 TableStats {
1557 row_count: 1000,
1558 avg_row_size: 64,
1559 page_count: 10,
1560 columns: vec![],
1561 },
1562 ));
1563 let estimator = CostEstimator::with_stats(provider);
1564 let filter = AstFilter::Compare {
1565 field: FieldRef::column("people", "unknown_col"),
1566 op: CompareOp::Lt,
1567 value: Value::Integer(50),
1568 };
1569 let s = estimator.filter_selectivity(&filter, "people");
1570 assert!((s - 0.3).abs() < 1e-9, "fallback heuristic 0.3, got {s}");
1571 }
1572}