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