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
21#[derive(Debug, Clone, Default)]
23pub struct CardinalityEstimate {
24 pub rows: f64,
26 pub selectivity: f64,
28 pub confidence: f64,
30}
31
32impl CardinalityEstimate {
33 pub fn new(rows: f64, selectivity: f64) -> Self {
35 Self {
36 rows,
37 selectivity,
38 confidence: 1.0,
39 }
40 }
41
42 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 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; self
57 }
58}
59
60#[derive(Debug, Clone, Default)]
70pub struct PlanCost {
71 pub cpu: f64,
73 pub io: f64,
75 pub network: f64,
77 pub memory: f64,
79 pub startup_cost: f64,
85 pub total: f64,
87}
88
89impl PlanCost {
90 pub fn new(cpu: f64, io: f64, memory: f64) -> Self {
92 let total = cpu + io * 10.0 + memory * 0.1; Self {
94 cpu,
95 io,
96 network: 0.0,
97 memory,
98 startup_cost: 0.0,
99 total,
100 }
101 }
102
103 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 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 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 pub fn combine(&self, other: &PlanCost) -> PlanCost {
156 self.combine_pipelined(other)
157 }
158
159 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, startup_cost: self.startup_cost, total: self.total * factor,
168 }
169 }
170
171 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#[derive(Debug, Clone, Default)]
200pub struct TableStats {
201 pub row_count: u64,
203 pub avg_row_size: u32,
205 pub page_count: u64,
207 pub columns: Vec<ColumnStats>,
209}
210
211#[derive(Debug, Clone, Default)]
213pub struct ColumnStats {
214 pub name: String,
216 pub distinct_count: u64,
218 pub null_count: u64,
220 pub min_value: Option<String>,
222 pub max_value: Option<String>,
224 pub has_index: bool,
226}
227
228pub struct CostEstimator {
230 default_row_count: f64,
232 row_scan_cost: f64,
234 index_lookup_cost: f64,
236 hash_probe_cost: f64,
238 nested_loop_cost: f64,
240 edge_traversal_cost: f64,
242 stats: Arc<dyn StatsProvider>,
247}
248
249impl CostEstimator {
250 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 pub fn with_stats(provider: Arc<dyn StatsProvider>) -> Self {
268 Self {
269 stats: provider,
270 ..Self::new()
271 }
272 }
273
274 pub fn set_stats(&mut self, provider: Arc<dyn StatsProvider>) {
278 self.stats = provider;
279 }
280
281 pub fn estimate(&self, query: &QueryExpr) -> PlanCost {
283 match query {
284 QueryExpr::Table(tq) => self.estimate_table(tq),
285 QueryExpr::Graph(gq) => self.estimate_graph(gq),
286 QueryExpr::Join(jq) => self.estimate_join(jq),
287 QueryExpr::Path(pq) => self.estimate_path(pq),
288 QueryExpr::Vector(vq) => self.estimate_vector(vq),
289 QueryExpr::Hybrid(hq) => self.estimate_hybrid(hq),
290 QueryExpr::Explain(explain) => self.estimate(&explain.inner),
291 QueryExpr::Insert(_)
293 | QueryExpr::Update(_)
294 | QueryExpr::Delete(_)
295 | QueryExpr::Function(_)
296 | QueryExpr::CreateTable(_)
297 | QueryExpr::CreateCollection(_)
298 | QueryExpr::CreateVector(_)
299 | QueryExpr::DropTable(_)
300 | QueryExpr::DropGraph(_)
301 | QueryExpr::DropVector(_)
302 | QueryExpr::DropDocument(_)
303 | QueryExpr::DropKv(_)
304 | QueryExpr::DropCollection(_)
305 | QueryExpr::Truncate(_)
306 | QueryExpr::AlterTable(_)
307 | QueryExpr::CreateVcsRef(_)
308 | QueryExpr::DropVcsRef(_)
309 | QueryExpr::ForkStore(_)
310 | QueryExpr::PromoteFork(_)
311 | QueryExpr::DropFork(_)
312 | QueryExpr::VcsCommand(_)
313 | QueryExpr::GraphCommand(_)
314 | QueryExpr::SearchCommand(_)
315 | QueryExpr::CreateIndex(_)
316 | QueryExpr::DropIndex(_)
317 | QueryExpr::ProbabilisticCommand(_)
318 | QueryExpr::Ask(_)
319 | QueryExpr::SetConfig { .. }
320 | QueryExpr::ShowConfig { .. }
321 | QueryExpr::Scrub { .. }
322 | QueryExpr::SetSecret { .. }
323 | QueryExpr::DeleteSecret { .. }
324 | QueryExpr::SetKv { .. }
325 | QueryExpr::DeleteKv { .. }
326 | QueryExpr::ShowSecrets { .. }
327 | QueryExpr::SetTenant(_)
328 | QueryExpr::ShowTenant
329 | QueryExpr::CreateTimeSeries(_)
330 | QueryExpr::CreateMetric(_)
331 | QueryExpr::AlterMetric(_)
332 | QueryExpr::CreateSlo(_)
333 | QueryExpr::DropTimeSeries(_)
334 | QueryExpr::CreateQueue(_)
335 | QueryExpr::AlterQueue(_)
336 | QueryExpr::DropQueue(_)
337 | QueryExpr::QueueSelect(_)
338 | QueryExpr::QueueCommand(_)
339 | QueryExpr::KvCommand(_)
340 | QueryExpr::ConfigCommand(_)
341 | QueryExpr::CreateTree(_)
342 | QueryExpr::DropTree(_)
343 | QueryExpr::TreeCommand(_)
344 | QueryExpr::ExplainAlter(_)
345 | QueryExpr::TransactionControl(_)
346 | QueryExpr::MaintenanceCommand(_)
347 | QueryExpr::CreateSchema(_)
348 | QueryExpr::DropSchema(_)
349 | QueryExpr::CreateSequence(_)
350 | QueryExpr::DropSequence(_)
351 | QueryExpr::CopyFrom(_)
352 | QueryExpr::CreateView(_)
353 | QueryExpr::DropView(_)
354 | QueryExpr::RefreshMaterializedView(_)
355 | QueryExpr::CreatePolicy(_)
356 | QueryExpr::DropPolicy(_)
357 | QueryExpr::CreateServer(_)
358 | QueryExpr::DropServer(_)
359 | QueryExpr::CreateForeignTable(_)
360 | QueryExpr::DropForeignTable(_)
361 | QueryExpr::Grant(_)
362 | QueryExpr::Revoke(_)
363 | QueryExpr::AlterUser(_)
364 | QueryExpr::CreateUser(_)
365 | QueryExpr::CreateIamPolicy { .. }
366 | QueryExpr::DropIamPolicy { .. }
367 | QueryExpr::AttachPolicy { .. }
368 | QueryExpr::DetachPolicy { .. }
369 | QueryExpr::ShowPolicies { .. }
370 | QueryExpr::ShowEffectivePermissions { .. }
371 | QueryExpr::RankOf(_)
372 | QueryExpr::ApproxRankOf(_)
373 | QueryExpr::RankRange(_)
374 | QueryExpr::SimulatePolicy { .. }
375 | QueryExpr::LintPolicy { .. }
376 | QueryExpr::MigratePolicyMode { .. }
377 | QueryExpr::CreateMigration(_)
378 | QueryExpr::ApplyMigration(_)
379 | QueryExpr::RollbackMigration(_)
380 | QueryExpr::ExplainMigration(_)
381 | QueryExpr::EventsBackfill(_)
382 | QueryExpr::EventsBackfillStatus { .. } => PlanCost::new(1.0, 1.0, 0.0),
383 }
384 }
385
386 pub fn estimate_cardinality(&self, query: &QueryExpr) -> CardinalityEstimate {
388 match query {
389 QueryExpr::Table(tq) => self.estimate_table_cardinality(tq),
390 QueryExpr::Graph(gq) => self.estimate_graph_cardinality(gq),
391 QueryExpr::Join(jq) => self.estimate_join_cardinality(jq),
392 QueryExpr::Path(pq) => self.estimate_path_cardinality(pq),
393 QueryExpr::Vector(vq) => self.estimate_vector_cardinality(vq),
394 QueryExpr::Hybrid(hq) => self.estimate_hybrid_cardinality(hq),
395 QueryExpr::Explain(explain) => self.estimate_cardinality(&explain.inner),
396 QueryExpr::Insert(_)
398 | QueryExpr::Update(_)
399 | QueryExpr::Delete(_)
400 | QueryExpr::Function(_)
401 | QueryExpr::CreateTable(_)
402 | QueryExpr::CreateCollection(_)
403 | QueryExpr::CreateVector(_)
404 | QueryExpr::DropTable(_)
405 | QueryExpr::DropGraph(_)
406 | QueryExpr::DropVector(_)
407 | QueryExpr::DropDocument(_)
408 | QueryExpr::DropKv(_)
409 | QueryExpr::DropCollection(_)
410 | QueryExpr::Truncate(_)
411 | QueryExpr::AlterTable(_)
412 | QueryExpr::CreateVcsRef(_)
413 | QueryExpr::DropVcsRef(_)
414 | QueryExpr::ForkStore(_)
415 | QueryExpr::PromoteFork(_)
416 | QueryExpr::DropFork(_)
417 | QueryExpr::VcsCommand(_)
418 | QueryExpr::GraphCommand(_)
419 | QueryExpr::SearchCommand(_)
420 | QueryExpr::CreateIndex(_)
421 | QueryExpr::DropIndex(_)
422 | QueryExpr::ProbabilisticCommand(_)
423 | QueryExpr::Ask(_)
424 | QueryExpr::SetConfig { .. }
425 | QueryExpr::ShowConfig { .. }
426 | QueryExpr::Scrub { .. }
427 | QueryExpr::SetSecret { .. }
428 | QueryExpr::DeleteSecret { .. }
429 | QueryExpr::SetKv { .. }
430 | QueryExpr::DeleteKv { .. }
431 | QueryExpr::ShowSecrets { .. }
432 | QueryExpr::SetTenant(_)
433 | QueryExpr::ShowTenant
434 | QueryExpr::CreateTimeSeries(_)
435 | QueryExpr::CreateMetric(_)
436 | QueryExpr::AlterMetric(_)
437 | QueryExpr::CreateSlo(_)
438 | QueryExpr::DropTimeSeries(_)
439 | QueryExpr::CreateQueue(_)
440 | QueryExpr::AlterQueue(_)
441 | QueryExpr::DropQueue(_)
442 | QueryExpr::QueueSelect(_)
443 | QueryExpr::QueueCommand(_)
444 | QueryExpr::KvCommand(_)
445 | QueryExpr::ConfigCommand(_)
446 | QueryExpr::CreateTree(_)
447 | QueryExpr::DropTree(_)
448 | QueryExpr::TreeCommand(_)
449 | QueryExpr::ExplainAlter(_)
450 | QueryExpr::TransactionControl(_)
451 | QueryExpr::MaintenanceCommand(_)
452 | QueryExpr::CreateSchema(_)
453 | QueryExpr::DropSchema(_)
454 | QueryExpr::CreateSequence(_)
455 | QueryExpr::DropSequence(_)
456 | QueryExpr::CopyFrom(_)
457 | QueryExpr::CreateView(_)
458 | QueryExpr::DropView(_)
459 | QueryExpr::RefreshMaterializedView(_)
460 | QueryExpr::CreatePolicy(_)
461 | QueryExpr::DropPolicy(_)
462 | QueryExpr::CreateServer(_)
463 | QueryExpr::DropServer(_)
464 | QueryExpr::CreateForeignTable(_)
465 | QueryExpr::DropForeignTable(_)
466 | QueryExpr::Grant(_)
467 | QueryExpr::Revoke(_)
468 | QueryExpr::AlterUser(_)
469 | QueryExpr::CreateUser(_)
470 | QueryExpr::CreateIamPolicy { .. }
471 | QueryExpr::DropIamPolicy { .. }
472 | QueryExpr::AttachPolicy { .. }
473 | QueryExpr::DetachPolicy { .. }
474 | QueryExpr::ShowPolicies { .. }
475 | QueryExpr::ShowEffectivePermissions { .. }
476 | QueryExpr::RankOf(_)
477 | QueryExpr::ApproxRankOf(_)
478 | QueryExpr::RankRange(_)
479 | QueryExpr::SimulatePolicy { .. }
480 | QueryExpr::LintPolicy { .. }
481 | QueryExpr::MigratePolicyMode { .. }
482 | QueryExpr::CreateMigration(_)
483 | QueryExpr::ApplyMigration(_)
484 | QueryExpr::RollbackMigration(_)
485 | QueryExpr::ExplainMigration(_)
486 | QueryExpr::EventsBackfill(_)
487 | QueryExpr::EventsBackfillStatus { .. } => CardinalityEstimate::new(1.0, 1.0),
488 }
489 }
490
491 fn estimate_table(&self, query: &TableQuery) -> PlanCost {
496 let cardinality = self.estimate_table_cardinality(query);
497
498 let cpu = cardinality.rows * self.row_scan_cost;
499
500 let io = self.estimate_table_io(query, cardinality.rows);
503
504 let memory = cardinality.rows * 100.0; PlanCost::new(cpu, io, memory)
507 }
508
509 fn estimate_table_io(&self, query: &TableQuery, result_rows: f64) -> f64 {
516 const ROWS_PER_PAGE: f64 = 100.0;
517
518 let table_stats = self.stats.table_stats(&query.table);
520 let heap_pages = table_stats
521 .map(|s| s.page_count as f64)
522 .unwrap_or_else(|| (result_rows / ROWS_PER_PAGE).max(1.0));
523
524 if let Some(filter) = reddb_rql::sql_lowering::effective_table_filter(query) {
527 if let Some(col) = first_filter_column(&filter, &query.table) {
528 if let Some(idx) = self.stats.index_stats(&query.table, col) {
529 return idx.correlated_io_cost(result_rows, heap_pages);
530 }
531 }
532 }
533
534 (result_rows / ROWS_PER_PAGE).ceil()
536 }
537
538 fn estimate_table_cardinality(&self, query: &TableQuery) -> CardinalityEstimate {
539 let base_rows = self
542 .stats
543 .table_stats(&query.table)
544 .map(|s| s.row_count as f64)
545 .unwrap_or(self.default_row_count);
546
547 let mut estimate = CardinalityEstimate::full_scan(base_rows);
548
549 if let Some(filter) = reddb_rql::sql_lowering::effective_table_filter(query) {
552 let selectivity = self.filter_selectivity(&filter, &query.table);
553 estimate = estimate.with_filter(selectivity);
554 }
555
556 if let Some(limit) = query.limit {
558 estimate.rows = estimate.rows.min(limit as f64);
559 }
560
561 estimate
562 }
563
564 fn filter_selectivity(&self, filter: &AstFilter, table: &str) -> f64 {
577 match filter {
578 AstFilter::Compare { field, op, value } => {
579 let column = column_name_for_table(field, table);
580 match op {
581 CompareOp::Eq => self.eq_selectivity(table, column, value),
582 CompareOp::Ne => 1.0 - self.eq_selectivity(table, column, value),
583 CompareOp::Lt | CompareOp::Le => {
584 self.range_selectivity(table, column, None, Some(value))
585 }
586 CompareOp::Gt | CompareOp::Ge => {
587 self.range_selectivity(table, column, Some(value), None)
588 }
589 }
590 }
591 AstFilter::Between {
592 field, low, high, ..
593 } => {
594 let column = column_name_for_table(field, table);
595 self.range_selectivity(table, column, Some(low), Some(high))
596 }
597 AstFilter::In { field, values, .. } => {
598 let column = column_name_for_table(field, table);
599 if let Some(c) = column {
603 if let Some(mcv) = self.stats.column_mcv(table, c) {
604 let mut hits: f64 = 0.0;
605 let mut residual_count = 0usize;
606 for v in values {
607 if let Some(cv) = column_value_from(v) {
608 if let Some(freq) = mcv.frequency_of(&cv) {
609 hits += freq;
610 } else {
611 residual_count += 1;
612 }
613 } else {
614 residual_count += 1;
615 }
616 }
617 let total = mcv.total_frequency();
618 let distinct = self.stats.distinct_values(table, c).unwrap_or(100);
619 let non_mcv_distinct =
620 distinct.saturating_sub(mcv.values.len() as u64).max(1);
621 let per_residual = (1.0 - total) / non_mcv_distinct as f64;
622 let estimate = hits + (residual_count as f64) * per_residual;
623 return estimate.clamp(0.0, 1.0).min(0.5);
624 }
625 if let Some(s) = self.stats.index_stats(table, c) {
626 return (s.point_selectivity() * values.len() as f64).min(0.5);
627 }
628 }
629 (values.len() as f64 * 0.01).min(0.5)
630 }
631 AstFilter::Like { .. } => 0.1,
632 AstFilter::StartsWith { .. } => 0.15,
633 AstFilter::EndsWith { .. } => 0.15,
634 AstFilter::Contains { .. } => 0.1,
635 AstFilter::IsNull { .. } => 0.01,
636 AstFilter::IsNotNull { .. } => 0.99,
637 AstFilter::And(left, right) => {
638 self.filter_selectivity(left, table) * self.filter_selectivity(right, table)
639 }
640 AstFilter::Or(left, right) => {
641 let s1 = self.filter_selectivity(left, table);
642 let s2 = self.filter_selectivity(right, table);
643 s1 + s2 - (s1 * s2)
644 }
645 AstFilter::Not(inner) => 1.0 - self.filter_selectivity(inner, table),
646 AstFilter::CompareFields { .. } => {
647 0.1
651 }
652 AstFilter::CompareExpr { .. } => {
653 0.1
657 }
658 }
659 }
660
661 fn estimate_graph(&self, query: &GraphQuery) -> PlanCost {
666 let cardinality = self.estimate_graph_cardinality(query);
667
668 let nodes = query.pattern.nodes.len() as f64;
670 let edges = query.pattern.edges.len() as f64;
671
672 let cpu = cardinality.rows * self.edge_traversal_cost * (nodes + edges);
673 let io = cardinality.rows * 0.1; let memory = cardinality.rows * 200.0; PlanCost::new(cpu, io, memory)
677 }
678
679 fn estimate_graph_cardinality(&self, query: &GraphQuery) -> CardinalityEstimate {
680 let nodes = query.pattern.nodes.len() as f64;
681 let edges = query.pattern.edges.len() as f64;
682
683 let base_rows = self.default_row_count;
685 let edge_factor = 0.1_f64.powf(edges); let mut estimate = CardinalityEstimate::new(base_rows * nodes * edge_factor, edge_factor);
688 estimate.confidence = 0.5; if let Some(ref filter) = query.filter {
692 let selectivity = Self::estimate_filter_selectivity(filter);
693 estimate = estimate.with_filter(selectivity);
694 }
695
696 estimate
697 }
698
699 fn estimate_join(&self, query: &JoinQuery) -> PlanCost {
704 let left_cost = self.estimate(&query.left);
705 let right_cost = self.estimate(&query.right);
706
707 let left_card = self.estimate_cardinality(&query.left);
708 let right_card = self.estimate_cardinality(&query.right);
709
710 let build_cpu = left_card.rows * self.hash_probe_cost;
717 let probe_cpu = right_card.rows * self.hash_probe_cost;
718 let join_memory = left_card.rows * 100.0; let build_op = PlanCost::with_startup(build_cpu, 0.0, join_memory, build_cpu);
722 let probe_op = PlanCost::new(probe_cpu, 0.0, 0.0);
724
725 let after_build = left_cost.combine_blocking(&build_op);
727 after_build
728 .combine_pipelined(&right_cost)
729 .combine_pipelined(&probe_op)
730 }
731
732 fn estimate_join_cardinality(&self, query: &JoinQuery) -> CardinalityEstimate {
733 let left = self.estimate_cardinality(&query.left);
734 let right = self.estimate_cardinality(&query.right);
735
736 let selectivity = match query.join_type {
738 JoinType::Inner => 0.1, JoinType::LeftOuter => 1.0, JoinType::RightOuter => 1.0, JoinType::FullOuter => 1.0, JoinType::Cross => 1.0, };
744
745 CardinalityEstimate::new(
746 left.rows * right.rows * selectivity,
747 left.selectivity * right.selectivity * selectivity,
748 )
749 }
750
751 fn estimate_path(&self, query: &PathQuery) -> PlanCost {
756 let cardinality = self.estimate_path_cardinality(query);
757
758 let max_hops = query.max_length;
760 let branching_factor: f64 = 5.0; let nodes_visited = branching_factor.powf(max_hops as f64).min(10000.0);
763 let cpu = nodes_visited * self.edge_traversal_cost;
764 let io = nodes_visited * 0.1;
765 let memory = nodes_visited * 50.0; PlanCost::new(cpu, io, memory)
768 }
769
770 fn estimate_path_cardinality(&self, query: &PathQuery) -> CardinalityEstimate {
771 let max_paths = 10.0;
773 CardinalityEstimate::new(max_paths, 0.001)
774 }
775
776 fn estimate_vector(&self, query: &VectorQuery) -> PlanCost {
781 let k = query.k as f64;
784
785 let hnsw_cost = 100.0 * (1.0 + k.ln()); let filter_cost = if reddb_rql::sql_lowering::effective_vector_filter(query).is_some() {
792 50.0
793 } else {
794 0.0
795 };
796
797 let cpu = hnsw_cost + filter_cost;
798 let io = 20.0; let memory = k * 32.0 + 1000.0; PlanCost::with_startup(cpu, io, memory, hnsw_cost * 0.5)
806 }
807
808 fn estimate_vector_cardinality(&self, query: &VectorQuery) -> CardinalityEstimate {
809 let k = query.k as f64;
811 CardinalityEstimate::new(k, 0.1)
812 }
813
814 fn estimate_hybrid(&self, query: &HybridQuery) -> PlanCost {
819 let structured_cost = self.estimate(&query.structured);
821 let vector_cost = self.estimate_vector(&query.vector);
822
823 let fusion_overhead = match &query.fusion {
825 reddb_rql::ast::FusionStrategy::Rerank { .. } => 50.0,
826 reddb_rql::ast::FusionStrategy::FilterThenSearch => 10.0,
827 reddb_rql::ast::FusionStrategy::SearchThenFilter => 10.0,
828 reddb_rql::ast::FusionStrategy::RRF { .. } => 30.0,
829 reddb_rql::ast::FusionStrategy::Intersection => 20.0,
830 reddb_rql::ast::FusionStrategy::Union { .. } => 40.0,
831 };
832
833 PlanCost::new(
834 structured_cost.cpu + vector_cost.cpu + fusion_overhead,
835 structured_cost.io + vector_cost.io,
836 structured_cost.memory + vector_cost.memory,
837 )
838 }
839
840 fn estimate_hybrid_cardinality(&self, query: &HybridQuery) -> CardinalityEstimate {
841 let structured_card = self.estimate_cardinality(&query.structured);
842 let vector_card = self.estimate_vector_cardinality(&query.vector);
843
844 let rows = match &query.fusion {
846 reddb_rql::ast::FusionStrategy::Intersection => {
847 structured_card.rows.min(vector_card.rows)
848 }
849 reddb_rql::ast::FusionStrategy::Union { .. } => structured_card.rows + vector_card.rows,
850 _ => vector_card.rows, };
852
853 CardinalityEstimate::new(rows, 0.2)
854 }
855
856 fn estimate_filter_selectivity(filter: &AstFilter) -> f64 {
861 match filter {
862 AstFilter::Compare { op, .. } => {
863 match op {
864 CompareOp::Eq => 0.01, CompareOp::Ne => 0.99, CompareOp::Lt | CompareOp::Le => 0.3,
867 CompareOp::Gt | CompareOp::Ge => 0.3,
868 }
869 }
870 AstFilter::Between { .. } => 0.25,
871 AstFilter::In { values, .. } => {
872 (values.len() as f64 * 0.01).min(0.5)
874 }
875 AstFilter::Like { .. } => 0.1,
876 AstFilter::StartsWith { .. } => 0.15,
877 AstFilter::EndsWith { .. } => 0.15,
878 AstFilter::Contains { .. } => 0.1,
879 AstFilter::IsNull { .. } => 0.01,
880 AstFilter::IsNotNull { .. } => 0.99,
881 AstFilter::And(left, right) => {
882 Self::estimate_filter_selectivity(left) * Self::estimate_filter_selectivity(right)
883 }
884 AstFilter::Or(left, right) => {
885 let s1 = Self::estimate_filter_selectivity(left);
886 let s2 = Self::estimate_filter_selectivity(right);
887 s1 + s2 - (s1 * s2) }
889 AstFilter::Not(inner) => 1.0 - Self::estimate_filter_selectivity(inner),
890 AstFilter::CompareFields { .. } => 0.1,
891 AstFilter::CompareExpr { .. } => 0.1,
892 }
893 }
894}
895
896impl CostEstimator {
897 fn eq_selectivity(&self, table: &str, column: Option<&str>, value: &Value) -> f64 {
905 if let Some(col) = column {
906 if let Some(mcv) = self.stats.column_mcv(table, col) {
908 if let Some(cv) = column_value_from(value) {
909 if let Some(freq) = mcv.frequency_of(&cv) {
910 return freq;
911 }
912 let total = mcv.total_frequency();
914 let distinct = self.stats.distinct_values(table, col).unwrap_or(100);
915 let non_mcv_distinct = distinct.saturating_sub(mcv.values.len() as u64).max(1);
916 return ((1.0 - total) / non_mcv_distinct as f64).clamp(0.0, 1.0);
917 }
918 }
919 if let Some(s) = self.stats.index_stats(table, col) {
921 return s.point_selectivity();
922 }
923 }
924 0.01
926 }
927
928 fn range_selectivity(
939 &self,
940 table: &str,
941 column: Option<&str>,
942 lo: Option<&Value>,
943 hi: Option<&Value>,
944 ) -> f64 {
945 if let Some(col) = column {
946 if let Some(h) = self.stats.column_histogram(table, col) {
948 let lo_cv = lo.and_then(column_value_from);
949 let hi_cv = hi.and_then(column_value_from);
950 return h.range_selectivity(lo_cv.as_ref(), hi_cv.as_ref());
951 }
952 if let Some(s) = self.stats.index_stats(table, col) {
954 let cap = if lo.is_some() && hi.is_some() {
955 0.25
956 } else {
957 0.3
958 };
959 return (s.point_selectivity() * (s.distinct_keys as f64 / 2.0)).min(cap);
960 }
961 }
962 if lo.is_some() && hi.is_some() {
964 0.25
965 } else {
966 0.3
967 }
968 }
969}
970
971impl Default for CostEstimator {
972 fn default() -> Self {
973 Self::new()
974 }
975}
976
977fn column_value_from(v: &reddb_types::Value) -> Option<super::histogram::ColumnValue> {
982 use super::histogram::ColumnValue;
983 use reddb_types::Value;
984 match v {
985 Value::Integer(i) | Value::BigInt(i) => Some(ColumnValue::Int(*i)),
986 Value::UnsignedInteger(u) => Some(ColumnValue::Int(*u as i64)),
987 Value::Float(f) if f.is_finite() => Some(ColumnValue::Float(*f)),
988 Value::Text(s) => Some(ColumnValue::Text(s.to_string())),
989 Value::Email(s)
990 | Value::Url(s)
991 | Value::NodeRef(s)
992 | Value::EdgeRef(s)
993 | Value::TableRef(s)
994 | Value::Password(s) => Some(ColumnValue::Text(s.clone())),
995 Value::Timestamp(t) => Some(ColumnValue::Int(*t)),
996 Value::Duration(d) => Some(ColumnValue::Int(*d)),
997 Value::TimestampMs(t) => Some(ColumnValue::Int(*t)),
998 Value::Decimal(d) => Some(ColumnValue::Int(*d)),
999 Value::Date(d) => Some(ColumnValue::Int(i64::from(*d))),
1000 Value::Time(t) => Some(ColumnValue::Int(i64::from(*t))),
1001 Value::Phone(p) => Some(ColumnValue::Int(*p as i64)),
1002 Value::Semver(v) => Some(ColumnValue::Int(i64::from(*v))),
1003 Value::Port(v) => Some(ColumnValue::Int(i64::from(*v))),
1004 Value::PageRef(v) => Some(ColumnValue::Int(i64::from(*v))),
1005 Value::EnumValue(v) => Some(ColumnValue::Int(i64::from(*v))),
1006 Value::Latitude(v) => Some(ColumnValue::Int(i64::from(*v))),
1007 Value::Longitude(v) => Some(ColumnValue::Int(i64::from(*v))),
1008 _ => None,
1013 }
1014}
1015
1016fn first_filter_column<'a>(filter: &'a AstFilter, table: &str) -> Option<&'a str> {
1021 match filter {
1022 AstFilter::Compare { field, .. } => column_name_for_table(field, table),
1023 AstFilter::Between { field, .. } => column_name_for_table(field, table),
1024 AstFilter::And(l, r) => {
1025 first_filter_column(l, table).or_else(|| first_filter_column(r, table))
1026 }
1027 _ => None,
1028 }
1029}
1030
1031fn column_name_for_table<'a>(field: &'a FieldRef, table: &str) -> Option<&'a str> {
1033 match field {
1034 FieldRef::TableColumn { table: t, column } if t == table || t.is_empty() => {
1035 Some(column.as_str())
1036 }
1037 _ => None,
1039 }
1040}
1041
1042#[cfg(test)]
1043mod tests {
1044 use super::super::stats_provider::StaticProvider;
1045 use super::*;
1046 use crate::storage::index::{IndexKind, IndexStats};
1047 use reddb_rql::ast::{FieldRef, Projection};
1048 use reddb_types::Value;
1049
1050 fn eq_filter(table: &str, column: &str, value: i64) -> AstFilter {
1051 AstFilter::Compare {
1052 field: FieldRef::column(table, column),
1053 op: CompareOp::Eq,
1054 value: Value::Integer(value),
1055 }
1056 }
1057
1058 fn table_query(name: &str, filter: Option<AstFilter>) -> TableQuery {
1059 TableQuery {
1060 table: name.to_string(),
1061 source: None,
1062 alias: None,
1063 select_items: Vec::new(),
1064 columns: vec![Projection::All],
1065 where_expr: None,
1066 filter,
1067 group_by_exprs: Vec::new(),
1068 group_by: Vec::new(),
1069 having_expr: None,
1070 having: None,
1071 order_by: vec![],
1072 limit: None,
1073 limit_param: None,
1074 offset: None,
1075 offset_param: None,
1076 expand: None,
1077 as_of: None,
1078 sessionize: None,
1079 distinct: false,
1080 }
1081 }
1082
1083 #[test]
1084 fn injected_row_count_overrides_default() {
1085 let provider = Arc::new(StaticProvider::new().with_table(
1086 "users",
1087 TableStats {
1088 row_count: 50_000,
1089 avg_row_size: 256,
1090 page_count: 500,
1091 columns: vec![],
1092 },
1093 ));
1094 let estimator = CostEstimator::with_stats(provider);
1095 let q = table_query("users", None);
1096 let card = estimator.estimate_table_cardinality(&q);
1097 assert_eq!(card.rows, 50_000.0);
1099 }
1100
1101 #[test]
1102 fn stats_aware_eq_selectivity_beats_default() {
1103 let provider = Arc::new(
1104 StaticProvider::new()
1105 .with_table(
1106 "users",
1107 TableStats {
1108 row_count: 1_000_000,
1109 avg_row_size: 256,
1110 page_count: 10_000,
1111 columns: vec![],
1112 },
1113 )
1114 .with_index(
1115 "users",
1116 "email",
1117 IndexStats {
1118 entries: 1_000_000,
1119 distinct_keys: 1_000_000,
1120 approx_bytes: 0,
1121 kind: IndexKind::Hash,
1122 has_bloom: true,
1123 index_correlation: 0.0,
1124 },
1125 ),
1126 );
1127 let estimator = CostEstimator::with_stats(provider);
1128 let q = table_query("users", Some(eq_filter("users", "email", 0)));
1129 let card = estimator.estimate_table_cardinality(&q);
1130 assert!(card.rows < 2.0, "expected ~1 row, got {}", card.rows);
1132 }
1133
1134 #[test]
1135 fn fallback_when_no_index_stats() {
1136 let provider = Arc::new(StaticProvider::new().with_table(
1137 "users",
1138 TableStats {
1139 row_count: 1_000_000,
1140 avg_row_size: 256,
1141 page_count: 10_000,
1142 columns: vec![],
1143 },
1144 ));
1145 let estimator = CostEstimator::with_stats(provider);
1146 let q = table_query("users", Some(eq_filter("users", "email", 0)));
1147 let card = estimator.estimate_table_cardinality(&q);
1148 assert!((card.rows - 10_000.0).abs() < 1.0);
1150 }
1151
1152 #[test]
1153 fn null_provider_keeps_legacy_behaviour() {
1154 let estimator = CostEstimator::new();
1155 let q = table_query("whatever", Some(eq_filter("whatever", "id", 1)));
1156 let card = estimator.estimate_table_cardinality(&q);
1157 assert!((card.rows - 10.0).abs() < 1.0);
1159 }
1160
1161 #[test]
1162 fn and_combines_stats_selectivities() {
1163 let provider = Arc::new(
1164 StaticProvider::new()
1165 .with_table(
1166 "t",
1167 TableStats {
1168 row_count: 100_000,
1169 avg_row_size: 64,
1170 page_count: 100,
1171 columns: vec![],
1172 },
1173 )
1174 .with_index(
1175 "t",
1176 "a",
1177 IndexStats {
1178 entries: 100_000,
1179 distinct_keys: 10,
1180 approx_bytes: 0,
1181 kind: IndexKind::BTree,
1182 has_bloom: false,
1183 index_correlation: 0.0,
1184 },
1185 )
1186 .with_index(
1187 "t",
1188 "b",
1189 IndexStats {
1190 entries: 100_000,
1191 distinct_keys: 1000,
1192 approx_bytes: 0,
1193 kind: IndexKind::BTree,
1194 has_bloom: false,
1195 index_correlation: 0.0,
1196 },
1197 ),
1198 );
1199 let estimator = CostEstimator::with_stats(provider);
1200 let filter = AstFilter::And(
1201 Box::new(eq_filter("t", "a", 1)),
1202 Box::new(eq_filter("t", "b", 1)),
1203 );
1204 let q = table_query("t", Some(filter));
1205 let card = estimator.estimate_table_cardinality(&q);
1206 assert!(card.rows < 15.0, "got {}", card.rows);
1208 }
1209
1210 #[test]
1211 fn test_table_cost_estimation() {
1212 let estimator = CostEstimator::new();
1213
1214 let query = QueryExpr::Table(TableQuery {
1215 table: "hosts".to_string(),
1216 source: None,
1217 alias: None,
1218 select_items: Vec::new(),
1219 columns: vec![Projection::All],
1220 where_expr: None,
1221 filter: None,
1222 group_by_exprs: Vec::new(),
1223 group_by: Vec::new(),
1224 having_expr: None,
1225 having: None,
1226 order_by: vec![],
1227 limit: None,
1228 limit_param: None,
1229 offset: None,
1230 offset_param: None,
1231 expand: None,
1232 as_of: None,
1233 sessionize: None,
1234 distinct: false,
1235 });
1236
1237 let cost = estimator.estimate(&query);
1238 assert!(cost.cpu > 0.0);
1239 assert!(cost.total > 0.0);
1240 }
1241
1242 #[test]
1243 fn test_filter_selectivity() {
1244 let estimator = CostEstimator::new();
1245
1246 let eq_filter = AstFilter::Compare {
1247 field: FieldRef::column("hosts", "id"),
1248 op: CompareOp::Eq,
1249 value: Value::Integer(1),
1250 };
1251 assert!(CostEstimator::estimate_filter_selectivity(&eq_filter) < 0.1);
1252
1253 let ne_filter = AstFilter::Compare {
1254 field: FieldRef::column("hosts", "id"),
1255 op: CompareOp::Ne,
1256 value: Value::Integer(1),
1257 };
1258 assert!(CostEstimator::estimate_filter_selectivity(&ne_filter) > 0.9);
1259 }
1260
1261 #[test]
1262 fn test_and_selectivity() {
1263 let estimator = CostEstimator::new();
1264
1265 let and_filter = AstFilter::And(
1266 Box::new(AstFilter::Compare {
1267 field: FieldRef::column("hosts", "a"),
1268 op: CompareOp::Eq,
1269 value: Value::Integer(1),
1270 }),
1271 Box::new(AstFilter::Compare {
1272 field: FieldRef::column("hosts", "b"),
1273 op: CompareOp::Eq,
1274 value: Value::Integer(2),
1275 }),
1276 );
1277
1278 let selectivity = CostEstimator::estimate_filter_selectivity(&and_filter);
1279 assert!(selectivity < 0.01); }
1281
1282 #[test]
1283 fn test_cardinality_with_limit() {
1284 let estimator = CostEstimator::new();
1285
1286 let query = TableQuery {
1287 table: "hosts".to_string(),
1288 source: None,
1289 alias: None,
1290 select_items: Vec::new(),
1291 columns: vec![Projection::All],
1292 where_expr: None,
1293 filter: None,
1294 group_by_exprs: Vec::new(),
1295 group_by: Vec::new(),
1296 having_expr: None,
1297 having: None,
1298 order_by: vec![],
1299 limit: Some(10),
1300 limit_param: None,
1301 offset: None,
1302 offset_param: None,
1303 expand: None,
1304 as_of: None,
1305 sessionize: None,
1306 distinct: false,
1307 };
1308
1309 let card = estimator.estimate_table_cardinality(&query);
1310 assert!(card.rows <= 10.0);
1311 }
1312
1313 #[test]
1318 fn startup_zero_for_full_scan() {
1319 let estimator = CostEstimator::new();
1323 let q = table_query("any_table", None);
1324 let cost = estimator.estimate(&QueryExpr::Table(q));
1325 assert_eq!(cost.startup_cost, 0.0, "full scan must have zero startup");
1326 assert!(cost.total > 0.0);
1327 }
1328
1329 #[test]
1330 fn startup_nonzero_for_blocking_combine() {
1331 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);
1336 assert_eq!(composed.startup_cost, input.total);
1338 assert_eq!(composed.total, input.total + blocker.total);
1340 assert!(composed.startup_cost > 0.0);
1341 }
1342
1343 #[test]
1344 fn pipelined_combine_adds_startup_directly() {
1345 let upstream = PlanCost::with_startup(50.0, 5.0, 10.0, 30.0);
1346 let downstream = PlanCost::with_startup(20.0, 0.0, 0.0, 5.0);
1347 let composed = upstream.combine_pipelined(&downstream);
1348 assert_eq!(composed.startup_cost, 30.0 + 5.0);
1349 assert_eq!(composed.total, upstream.total + downstream.total);
1350 }
1351
1352 #[test]
1353 fn cost_prefers_low_startup_when_limit_small() {
1354 let fast_first = PlanCost {
1357 cpu: 100.0,
1358 io: 10.0,
1359 network: 0.0,
1360 memory: 50.0,
1361 startup_cost: 5.0,
1362 total: 200.0,
1363 };
1364 let slow_first = PlanCost {
1365 cpu: 100.0,
1366 io: 10.0,
1367 network: 0.0,
1368 memory: 50.0,
1369 startup_cost: 150.0,
1370 total: 200.0,
1371 };
1372 assert_eq!(
1374 fast_first.prefer_over(&slow_first, Some(10), 10_000.0),
1375 std::cmp::Ordering::Less
1376 );
1377 }
1378
1379 #[test]
1380 fn cost_prefers_low_total_when_no_limit() {
1381 let low_total = PlanCost {
1383 cpu: 50.0,
1384 io: 5.0,
1385 network: 0.0,
1386 memory: 0.0,
1387 startup_cost: 30.0,
1388 total: 100.0,
1389 };
1390 let high_total = PlanCost {
1391 cpu: 100.0,
1392 io: 10.0,
1393 network: 0.0,
1394 memory: 0.0,
1395 startup_cost: 5.0,
1396 total: 200.0,
1397 };
1398 assert_eq!(
1399 low_total.prefer_over(&high_total, None, 10_000.0),
1400 std::cmp::Ordering::Less
1401 );
1402 }
1403
1404 #[test]
1405 fn limit_threshold_falls_back_to_total_when_limit_large() {
1406 let low_total = PlanCost {
1408 cpu: 50.0,
1409 io: 5.0,
1410 network: 0.0,
1411 memory: 0.0,
1412 startup_cost: 30.0,
1413 total: 100.0,
1414 };
1415 let low_startup = PlanCost {
1416 cpu: 100.0,
1417 io: 10.0,
1418 network: 0.0,
1419 memory: 0.0,
1420 startup_cost: 5.0,
1421 total: 200.0,
1422 };
1423 assert_eq!(
1424 low_total.prefer_over(&low_startup, Some(5000), 10_000.0),
1425 std::cmp::Ordering::Less
1426 );
1427 }
1428
1429 #[test]
1430 fn hash_join_startup_includes_build_cost() {
1431 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);
1437 assert!(
1438 after_build.startup_cost >= left.total,
1439 "after-build startup ({}) must absorb left.total ({})",
1440 after_build.startup_cost,
1441 left.total
1442 );
1443 assert!(after_build.total >= after_build.startup_cost);
1444 }
1445
1446 #[test]
1447 fn vector_search_reports_nonzero_startup() {
1448 let estimator = CostEstimator::new();
1452 let v = PlanCost::with_startup(150.0, 20.0, 1320.0, 50.0);
1455 assert!(v.startup_cost > 0.0);
1456 assert!(v.startup_cost < v.total);
1457 let _ = estimator; }
1459
1460 #[test]
1461 fn with_startup_clamps_total_below_startup() {
1462 let cost = PlanCost::with_startup(1.0, 0.0, 0.0, 100.0);
1464 assert!(cost.total >= cost.startup_cost);
1465 }
1466
1467 #[test]
1468 fn default_plancost_has_zero_startup() {
1469 let c = PlanCost::default();
1470 assert_eq!(c.startup_cost, 0.0);
1471 assert_eq!(c.total, 0.0);
1472 }
1473
1474 use super::super::histogram::{ColumnValue, Histogram, MostCommonValues};
1479
1480 fn provider_with_skew() -> Arc<StaticProvider> {
1481 let mut sample: Vec<ColumnValue> = Vec::new();
1485 for i in 0..80 {
1486 sample.push(ColumnValue::Int(i % 10));
1487 }
1488 for i in 0..20 {
1489 sample.push(ColumnValue::Int(10 + i * 50));
1490 }
1491 let h = Histogram::equi_depth_from_sample(sample, 10);
1492
1493 let mcv = MostCommonValues::new(vec![
1494 (ColumnValue::Text("boss".to_string()), 0.5),
1495 (ColumnValue::Text("intern".to_string()), 0.05),
1496 ]);
1497
1498 Arc::new(
1499 StaticProvider::new()
1500 .with_table(
1501 "people",
1502 TableStats {
1503 row_count: 100_000,
1504 avg_row_size: 64,
1505 page_count: 100,
1506 columns: vec![],
1507 },
1508 )
1509 .with_histogram("people", "score", h)
1510 .with_mcv("people", "role", mcv),
1511 )
1512 }
1513
1514 #[test]
1515 fn eq_uses_mcv_when_value_is_tracked() {
1516 let provider = provider_with_skew();
1517 let estimator = CostEstimator::with_stats(provider);
1518 let filter = AstFilter::Compare {
1519 field: FieldRef::column("people", "role"),
1520 op: CompareOp::Eq,
1521 value: Value::text("boss".to_string()),
1522 };
1523 let s = estimator.filter_selectivity(&filter, "people");
1526 assert!(
1527 (s - 0.5).abs() < 1e-9,
1528 "MCV-tracked equality should report exact frequency, got {s}"
1529 );
1530 }
1531
1532 #[test]
1533 fn eq_uses_residual_for_non_mcv_value() {
1534 let provider = provider_with_skew();
1535 let estimator = CostEstimator::with_stats(provider);
1536 let filter = AstFilter::Compare {
1537 field: FieldRef::column("people", "role"),
1538 op: CompareOp::Eq,
1539 value: Value::text("staff".to_string()),
1540 };
1541 let s = estimator.filter_selectivity(&filter, "people");
1545 assert!(s > 0.0 && s < 0.01, "residual eq should be tiny, got {s}");
1546 }
1547
1548 #[test]
1549 fn ne_is_one_minus_eq_under_mcv() {
1550 let provider = provider_with_skew();
1551 let estimator = CostEstimator::with_stats(provider);
1552 let filter = AstFilter::Compare {
1553 field: FieldRef::column("people", "role"),
1554 op: CompareOp::Ne,
1555 value: Value::text("boss".to_string()),
1556 };
1557 let s = estimator.filter_selectivity(&filter, "people");
1558 assert!((s - 0.5).abs() < 1e-9, "Ne selectivity = 0.5, got {s}");
1560 }
1561
1562 #[test]
1563 fn range_uses_histogram_when_present() {
1564 let provider = provider_with_skew();
1565 let estimator = CostEstimator::with_stats(provider);
1566 let filter = AstFilter::Compare {
1567 field: FieldRef::column("people", "score"),
1568 op: CompareOp::Le,
1569 value: Value::Integer(9),
1570 };
1571 let s = estimator.filter_selectivity(&filter, "people");
1574 assert!(
1575 s > 0.5,
1576 "histogram-based range selectivity should beat 0.3, got {s}"
1577 );
1578 }
1579
1580 #[test]
1581 fn between_uses_histogram() {
1582 let provider = provider_with_skew();
1583 let estimator = CostEstimator::with_stats(provider);
1584 let filter = AstFilter::Between {
1585 field: FieldRef::column("people", "score"),
1586 low: Value::Integer(0),
1587 high: Value::Integer(9),
1588 };
1589 let s = estimator.filter_selectivity(&filter, "people");
1590 assert!(s > 0.5, "BETWEEN should use histogram too, got {s}");
1591 }
1592
1593 #[test]
1594 fn graceful_fallback_when_histogram_absent() {
1595 let provider = Arc::new(StaticProvider::new().with_table(
1598 "people",
1599 TableStats {
1600 row_count: 1000,
1601 avg_row_size: 64,
1602 page_count: 10,
1603 columns: vec![],
1604 },
1605 ));
1606 let estimator = CostEstimator::with_stats(provider);
1607 let filter = AstFilter::Compare {
1608 field: FieldRef::column("people", "unknown_col"),
1609 op: CompareOp::Lt,
1610 value: Value::Integer(50),
1611 };
1612 let s = estimator.filter_selectivity(&filter, "people");
1613 assert!((s - 0.3).abs() < 1e-9, "fallback heuristic 0.3, got {s}");
1614 }
1615}