1use crate::query::plan::{
6 AggregateOp, DistinctOp, ExpandDirection, ExpandOp, FilterOp, JoinOp, JoinType, LeftJoinOp,
7 LimitOp, LogicalOperator, MultiWayJoinOp, NodeScanOp, ProjectOp, ReturnOp, SkipOp, SortOp,
8 VectorJoinOp, VectorScanOp,
9};
10use std::collections::HashMap;
11
12#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct Cost {
17 pub cpu: f64,
19 pub io: f64,
21 pub memory: f64,
23 pub network: f64,
25}
26
27impl Cost {
28 #[must_use]
30 pub fn zero() -> Self {
31 Self {
32 cpu: 0.0,
33 io: 0.0,
34 memory: 0.0,
35 network: 0.0,
36 }
37 }
38
39 #[must_use]
41 pub fn cpu(cpu: f64) -> Self {
42 Self {
43 cpu,
44 io: 0.0,
45 memory: 0.0,
46 network: 0.0,
47 }
48 }
49
50 #[must_use]
52 pub fn with_io(mut self, io: f64) -> Self {
53 self.io = io;
54 self
55 }
56
57 #[must_use]
59 pub fn with_memory(mut self, memory: f64) -> Self {
60 self.memory = memory;
61 self
62 }
63
64 #[must_use]
68 pub fn total(&self) -> f64 {
69 self.cpu + self.io * 10.0 + self.memory * 0.1 + self.network * 100.0
70 }
71
72 #[must_use]
74 pub fn total_weighted(&self, cpu_weight: f64, io_weight: f64, mem_weight: f64) -> f64 {
75 self.cpu * cpu_weight + self.io * io_weight + self.memory * mem_weight
76 }
77}
78
79impl std::ops::Add for Cost {
80 type Output = Self;
81
82 fn add(self, other: Self) -> Self {
83 Self {
84 cpu: self.cpu + other.cpu,
85 io: self.io + other.io,
86 memory: self.memory + other.memory,
87 network: self.network + other.network,
88 }
89 }
90}
91
92impl std::ops::AddAssign for Cost {
93 fn add_assign(&mut self, other: Self) {
94 self.cpu += other.cpu;
95 self.io += other.io;
96 self.memory += other.memory;
97 self.network += other.network;
98 }
99}
100
101pub struct CostModel {
109 cpu_tuple_cost: f64,
111 hash_lookup_cost: f64,
113 sort_comparison_cost: f64,
115 avg_tuple_size: f64,
117 page_size: f64,
119 avg_fanout: f64,
121 edge_type_degrees: HashMap<String, (f64, f64)>,
123 label_cardinalities: HashMap<String, u64>,
125 total_nodes: u64,
127 total_edges: u64,
129}
130
131impl CostModel {
132 #[must_use]
134 pub fn new() -> Self {
135 Self {
136 cpu_tuple_cost: 0.01,
137 hash_lookup_cost: 0.03,
138 sort_comparison_cost: 0.02,
139 avg_tuple_size: 100.0,
140 page_size: 8192.0,
141 avg_fanout: 10.0,
142 edge_type_degrees: HashMap::new(),
143 label_cardinalities: HashMap::new(),
144 total_nodes: 0,
145 total_edges: 0,
146 }
147 }
148
149 #[must_use]
151 pub fn with_avg_fanout(mut self, avg_fanout: f64) -> Self {
152 self.avg_fanout = if avg_fanout > 0.0 { avg_fanout } else { 10.0 };
153 self
154 }
155
156 #[must_use]
160 pub fn with_edge_type_degrees(mut self, degrees: HashMap<String, (f64, f64)>) -> Self {
161 self.edge_type_degrees = degrees;
162 self
163 }
164
165 #[must_use]
167 pub fn with_label_cardinalities(mut self, cardinalities: HashMap<String, u64>) -> Self {
168 self.label_cardinalities = cardinalities;
169 self
170 }
171
172 #[must_use]
174 pub fn with_graph_totals(mut self, total_nodes: u64, total_edges: u64) -> Self {
175 self.total_nodes = total_nodes;
176 self.total_edges = total_edges;
177 self
178 }
179
180 fn fanout_for_expand(&self, expand: &ExpandOp) -> f64 {
185 if expand.edge_types.is_empty() {
186 return self.avg_fanout;
187 }
188
189 let mut total_fanout = 0.0;
190 let mut all_found = true;
191
192 for edge_type in &expand.edge_types {
193 if let Some(&(out_deg, in_deg)) = self.edge_type_degrees.get(edge_type) {
194 total_fanout += match expand.direction {
195 ExpandDirection::Outgoing => out_deg,
196 ExpandDirection::Incoming => in_deg,
197 ExpandDirection::Both => out_deg + in_deg,
198 };
199 } else {
200 all_found = false;
201 break;
202 }
203 }
204
205 if all_found {
206 total_fanout
207 } else {
208 self.avg_fanout
209 }
210 }
211
212 #[must_use]
214 pub fn estimate(&self, op: &LogicalOperator, cardinality: f64) -> Cost {
215 match op {
216 LogicalOperator::NodeScan(scan) => self.node_scan_cost(scan, cardinality),
217 LogicalOperator::Filter(filter) => self.filter_cost(filter, cardinality),
218 LogicalOperator::Project(project) => self.project_cost(project, cardinality),
219 LogicalOperator::Expand(expand) => self.expand_cost(expand, cardinality),
220 LogicalOperator::Join(join) => self.join_cost(join, cardinality),
221 LogicalOperator::Aggregate(agg) => self.aggregate_cost(agg, cardinality),
222 LogicalOperator::Sort(sort) => self.sort_cost(sort, cardinality),
223 LogicalOperator::Distinct(distinct) => self.distinct_cost(distinct, cardinality),
224 LogicalOperator::Limit(limit) => self.limit_cost(limit, cardinality),
225 LogicalOperator::Skip(skip) => self.skip_cost(skip, cardinality),
226 LogicalOperator::Return(ret) => self.return_cost(ret, cardinality),
227 LogicalOperator::Empty => Cost::zero(),
228 LogicalOperator::VectorScan(scan) => self.vector_scan_cost(scan, cardinality),
229 LogicalOperator::VectorJoin(join) => self.vector_join_cost(join, cardinality),
230 LogicalOperator::MultiWayJoin(mwj) => self.multi_way_join_cost(mwj, cardinality),
231 LogicalOperator::LeftJoin(lj) => {
232 let left_card = self.estimate_child_cardinality(&lj.left);
233 let right_card = self.estimate_child_cardinality(&lj.right);
234 self.left_join_cost(lj, cardinality, left_card, right_card)
235 }
236 _ => Cost::cpu(cardinality * self.cpu_tuple_cost),
237 }
238 }
239
240 fn node_scan_cost(&self, scan: &NodeScanOp, cardinality: f64) -> Cost {
246 let scan_size = if let Some(label) = &scan.label {
248 self.label_cardinalities
249 .get(label)
250 .map_or(cardinality, |&count| count as f64)
251 } else if self.total_nodes > 0 {
252 self.total_nodes as f64
253 } else {
254 cardinality
255 };
256 let pages = (scan_size * self.avg_tuple_size) / self.page_size;
257 Cost::cpu(cardinality * self.cpu_tuple_cost).with_io(pages)
259 }
260
261 fn filter_cost(&self, _filter: &FilterOp, cardinality: f64) -> Cost {
263 Cost::cpu(cardinality * self.cpu_tuple_cost * 1.5)
265 }
266
267 fn project_cost(&self, project: &ProjectOp, cardinality: f64) -> Cost {
269 let expr_count = project.projections.len() as f64;
271 Cost::cpu(cardinality * self.cpu_tuple_cost * expr_count)
272 }
273
274 fn expand_cost(&self, expand: &ExpandOp, cardinality: f64) -> Cost {
279 let fanout = self.fanout_for_expand(expand);
280 let lookup_cost = cardinality * self.hash_lookup_cost;
282 let output_cost = cardinality * fanout * self.cpu_tuple_cost;
284 Cost::cpu(lookup_cost + output_cost)
285 }
286
287 fn join_cost(&self, join: &JoinOp, cardinality: f64) -> Cost {
292 self.join_cost_with_children(join, cardinality, None, None)
293 }
294
295 fn join_cost_with_children(
297 &self,
298 join: &JoinOp,
299 cardinality: f64,
300 left_cardinality: Option<f64>,
301 right_cardinality: Option<f64>,
302 ) -> Cost {
303 match join.join_type {
304 JoinType::Cross => Cost::cpu(cardinality * self.cpu_tuple_cost),
305 JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
306 let build_cardinality = left_cardinality.unwrap_or_else(|| cardinality.sqrt());
308 let probe_cardinality = right_cardinality.unwrap_or_else(|| cardinality.sqrt());
309
310 let build_cost = build_cardinality * self.hash_lookup_cost;
311 let memory_cost = build_cardinality * self.avg_tuple_size;
312 let probe_cost = probe_cardinality * self.hash_lookup_cost;
313 let output_cost = cardinality * self.cpu_tuple_cost;
314
315 Cost::cpu(build_cost + probe_cost + output_cost).with_memory(memory_cost)
316 }
317 JoinType::Semi | JoinType::Anti => {
318 let build_cardinality = left_cardinality.unwrap_or_else(|| cardinality.sqrt());
319 let probe_cardinality = right_cardinality.unwrap_or_else(|| cardinality.sqrt());
320
321 let build_cost = build_cardinality * self.hash_lookup_cost;
322 let probe_cost = probe_cardinality * self.hash_lookup_cost;
323
324 Cost::cpu(build_cost + probe_cost)
325 .with_memory(build_cardinality * self.avg_tuple_size)
326 }
327 }
328 }
329
330 fn left_join_cost(
336 &self,
337 _lj: &LeftJoinOp,
338 cardinality: f64,
339 left_card: f64,
340 right_card: f64,
341 ) -> Cost {
342 let build_cost = right_card * self.hash_lookup_cost;
343 let memory_cost = right_card * self.avg_tuple_size;
344 let probe_cost = left_card * self.hash_lookup_cost;
345 let output_cost = cardinality * self.cpu_tuple_cost;
346
347 Cost::cpu(build_cost + probe_cost + output_cost).with_memory(memory_cost)
348 }
349
350 fn estimate_child_cardinality(&self, op: &LogicalOperator) -> f64 {
356 match op {
357 LogicalOperator::NodeScan(scan) => if let Some(label) = &scan.label {
358 self.label_cardinalities
359 .get(label)
360 .map_or(self.total_nodes as f64, |&c| c as f64)
361 } else {
362 self.total_nodes as f64
363 }
364 .max(1.0),
365 LogicalOperator::Expand(expand) => {
366 let input_card = self.estimate_child_cardinality(&expand.input);
367 let fanout = if expand.edge_types.is_empty() {
368 self.avg_fanout
369 } else {
370 self.fanout_for_expand(expand)
371 };
372 (input_card * fanout).max(1.0)
373 }
374 LogicalOperator::Filter(filter) => {
375 (self.estimate_child_cardinality(&filter.input) * 0.1).max(1.0)
377 }
378 LogicalOperator::Return(ret) => self.estimate_child_cardinality(&ret.input),
379 LogicalOperator::Limit(limit) => {
380 let input = self.estimate_child_cardinality(&limit.input);
381 input.min(100.0)
383 }
384 _ => (self.total_nodes as f64).max(1.0),
385 }
386 }
387
388 fn multi_way_join_cost(&self, mwj: &MultiWayJoinOp, cardinality: f64) -> Cost {
393 let n = mwj.inputs.len();
394 if n == 0 {
395 return Cost::zero();
396 }
397 let per_input = cardinality.powf(1.0 / n as f64).max(1.0);
400 let cardinalities: Vec<f64> = (0..n).map(|_| per_input).collect();
401 self.leapfrog_join_cost(n, &cardinalities, cardinality)
402 }
403
404 fn aggregate_cost(&self, agg: &AggregateOp, cardinality: f64) -> Cost {
406 let hash_cost = cardinality * self.hash_lookup_cost;
408
409 let agg_count = agg.aggregates.len() as f64;
411 let agg_cost = cardinality * self.cpu_tuple_cost * agg_count;
412
413 let distinct_groups = (cardinality / 10.0).max(1.0); let memory_cost = distinct_groups * self.avg_tuple_size;
416
417 Cost::cpu(hash_cost + agg_cost).with_memory(memory_cost)
418 }
419
420 fn sort_cost(&self, sort: &SortOp, cardinality: f64) -> Cost {
422 if cardinality <= 1.0 {
423 return Cost::zero();
424 }
425
426 let comparisons = cardinality * cardinality.log2();
428 let key_count = sort.keys.len() as f64;
429
430 let memory_cost = cardinality * self.avg_tuple_size;
432
433 Cost::cpu(comparisons * self.sort_comparison_cost * key_count).with_memory(memory_cost)
434 }
435
436 fn distinct_cost(&self, _distinct: &DistinctOp, cardinality: f64) -> Cost {
438 let hash_cost = cardinality * self.hash_lookup_cost;
440 let memory_cost = cardinality * self.avg_tuple_size * 0.5; Cost::cpu(hash_cost).with_memory(memory_cost)
443 }
444
445 fn limit_cost(&self, limit: &LimitOp, _cardinality: f64) -> Cost {
447 Cost::cpu(limit.count.estimate() * self.cpu_tuple_cost * 0.1)
449 }
450
451 fn skip_cost(&self, skip: &SkipOp, _cardinality: f64) -> Cost {
453 Cost::cpu(skip.count.estimate() * self.cpu_tuple_cost)
455 }
456
457 fn return_cost(&self, ret: &ReturnOp, cardinality: f64) -> Cost {
459 let expr_count = ret.items.len() as f64;
461 Cost::cpu(cardinality * self.cpu_tuple_cost * expr_count)
462 }
463
464 fn vector_scan_cost(&self, scan: &VectorScanOp, cardinality: f64) -> Cost {
469 let k = scan.k as f64;
471
472 let ef = 64.0;
475 let n = cardinality.max(1.0);
476 let search_cost = if scan.index_name.is_some() {
477 ef * n.ln() * self.cpu_tuple_cost * 10.0 } else {
480 n * self.cpu_tuple_cost * 10.0
482 };
483
484 let memory = k * self.avg_tuple_size * 2.0;
486
487 Cost::cpu(search_cost).with_memory(memory)
488 }
489
490 fn vector_join_cost(&self, join: &VectorJoinOp, cardinality: f64) -> Cost {
494 let k = join.k as f64;
495
496 let per_row_search_cost = if join.index_name.is_some() {
499 let ef = 64.0;
501 let n = cardinality.max(1.0);
502 ef * n.ln() * self.cpu_tuple_cost * 10.0
503 } else {
504 cardinality * self.cpu_tuple_cost * 10.0
506 };
507
508 let input_cardinality = (cardinality / k).max(1.0);
511 let total_search_cost = input_cardinality * per_row_search_cost;
512
513 let memory = cardinality * self.avg_tuple_size;
515
516 Cost::cpu(total_search_cost).with_memory(memory)
517 }
518
519 #[must_use]
525 pub fn estimate_tree(
526 &self,
527 op: &LogicalOperator,
528 card_estimator: &super::CardinalityEstimator,
529 ) -> Cost {
530 self.estimate_tree_inner(op, card_estimator)
531 }
532
533 fn estimate_tree_inner(
534 &self,
535 op: &LogicalOperator,
536 card_est: &super::CardinalityEstimator,
537 ) -> Cost {
538 let cardinality = card_est.estimate(op);
539
540 match op {
541 LogicalOperator::NodeScan(scan) => self.node_scan_cost(scan, cardinality),
542 LogicalOperator::Filter(filter) => {
543 let child_cost = self.estimate_tree_inner(&filter.input, card_est);
544 child_cost + self.filter_cost(filter, cardinality)
545 }
546 LogicalOperator::Project(project) => {
547 let child_cost = self.estimate_tree_inner(&project.input, card_est);
548 child_cost + self.project_cost(project, cardinality)
549 }
550 LogicalOperator::Expand(expand) => {
551 let child_cost = self.estimate_tree_inner(&expand.input, card_est);
552 child_cost + self.expand_cost(expand, cardinality)
553 }
554 LogicalOperator::Join(join) => {
555 let left_cost = self.estimate_tree_inner(&join.left, card_est);
556 let right_cost = self.estimate_tree_inner(&join.right, card_est);
557 let left_card = card_est.estimate(&join.left);
558 let right_card = card_est.estimate(&join.right);
559 let join_cost = self.join_cost_with_children(
560 join,
561 cardinality,
562 Some(left_card),
563 Some(right_card),
564 );
565 left_cost + right_cost + join_cost
566 }
567 LogicalOperator::LeftJoin(lj) => {
568 let left_cost = self.estimate_tree_inner(&lj.left, card_est);
569 let right_cost = self.estimate_tree_inner(&lj.right, card_est);
570 let left_card = card_est.estimate(&lj.left);
571 let right_card = card_est.estimate(&lj.right);
572 let join_cost = self.left_join_cost(lj, cardinality, left_card, right_card);
573 left_cost + right_cost + join_cost
574 }
575 LogicalOperator::Aggregate(agg) => {
576 let child_cost = self.estimate_tree_inner(&agg.input, card_est);
577 child_cost + self.aggregate_cost(agg, cardinality)
578 }
579 LogicalOperator::Sort(sort) => {
580 let child_cost = self.estimate_tree_inner(&sort.input, card_est);
581 child_cost + self.sort_cost(sort, cardinality)
582 }
583 LogicalOperator::Distinct(distinct) => {
584 let child_cost = self.estimate_tree_inner(&distinct.input, card_est);
585 child_cost + self.distinct_cost(distinct, cardinality)
586 }
587 LogicalOperator::Limit(limit) => {
588 let child_cost = self.estimate_tree_inner(&limit.input, card_est);
589 child_cost + self.limit_cost(limit, cardinality)
590 }
591 LogicalOperator::Skip(skip) => {
592 let child_cost = self.estimate_tree_inner(&skip.input, card_est);
593 child_cost + self.skip_cost(skip, cardinality)
594 }
595 LogicalOperator::Return(ret) => {
596 let child_cost = self.estimate_tree_inner(&ret.input, card_est);
597 child_cost + self.return_cost(ret, cardinality)
598 }
599 LogicalOperator::VectorScan(scan) => self.vector_scan_cost(scan, cardinality),
600 LogicalOperator::VectorJoin(join) => {
601 let child_cost = self.estimate_tree_inner(&join.input, card_est);
602 child_cost + self.vector_join_cost(join, cardinality)
603 }
604 LogicalOperator::MultiWayJoin(mwj) => {
605 let mut children_cost = Cost::zero();
606 for input in &mwj.inputs {
607 children_cost += self.estimate_tree_inner(input, card_est);
608 }
609 children_cost + self.multi_way_join_cost(mwj, cardinality)
610 }
611 LogicalOperator::Empty => Cost::zero(),
612 _ => Cost::cpu(cardinality * self.cpu_tuple_cost),
613 }
614 }
615
616 #[must_use]
618 pub fn cheaper<'a>(&self, a: &'a Cost, b: &'a Cost) -> &'a Cost {
619 if a.total() <= b.total() { a } else { b }
620 }
621
622 #[must_use]
638 pub fn leapfrog_join_cost(
639 &self,
640 num_relations: usize,
641 cardinalities: &[f64],
642 output_cardinality: f64,
643 ) -> Cost {
644 if cardinalities.is_empty() {
645 return Cost::zero();
646 }
647
648 let total_input: f64 = cardinalities.iter().sum();
649 let min_card = cardinalities.iter().copied().fold(f64::INFINITY, f64::min);
650
651 let materialize_cost = total_input * self.cpu_tuple_cost * 2.0; let seek_cost = if min_card > 1.0 {
656 output_cardinality * (num_relations as f64) * min_card.log2() * self.hash_lookup_cost
657 } else {
658 output_cardinality * self.cpu_tuple_cost
659 };
660
661 let output_cost = output_cardinality * self.cpu_tuple_cost;
663
664 let memory = total_input * self.avg_tuple_size * 2.0;
666
667 Cost::cpu(materialize_cost + seek_cost + output_cost).with_memory(memory)
668 }
669
670 #[must_use]
674 pub fn prefer_leapfrog_join(
675 &self,
676 num_relations: usize,
677 cardinalities: &[f64],
678 output_cardinality: f64,
679 ) -> bool {
680 if num_relations < 3 || cardinalities.len() < 3 {
681 return false;
683 }
684
685 let leapfrog_cost =
686 self.leapfrog_join_cost(num_relations, cardinalities, output_cardinality);
687
688 let mut hash_cascade_cost = Cost::zero();
692 let mut intermediate_cardinality = cardinalities[0];
693
694 for card in &cardinalities[1..] {
695 let join_output = (intermediate_cardinality * card).sqrt(); let join = JoinOp {
698 left: Box::new(LogicalOperator::Empty),
699 right: Box::new(LogicalOperator::Empty),
700 join_type: JoinType::Inner,
701 conditions: vec![],
702 };
703 hash_cascade_cost += self.join_cost(&join, join_output);
704 intermediate_cardinality = join_output;
705 }
706
707 leapfrog_cost.total() < hash_cascade_cost.total()
708 }
709
710 #[must_use]
718 pub fn factorized_benefit(&self, avg_fanout: f64, num_hops: usize) -> f64 {
719 if num_hops <= 1 || avg_fanout <= 1.0 {
720 return 1.0; }
722
723 let full_size = avg_fanout.powi(num_hops as i32);
729 let factorized_size = if avg_fanout > 1.0 {
730 (avg_fanout.powi(num_hops as i32 + 1) - 1.0) / (avg_fanout - 1.0)
731 } else {
732 num_hops as f64
733 };
734
735 (factorized_size / full_size).min(1.0)
736 }
737}
738
739impl Default for CostModel {
740 fn default() -> Self {
741 Self::new()
742 }
743}
744
745#[cfg(test)]
746mod tests {
747 use super::*;
748 use crate::query::plan::{
749 AggregateExpr, AggregateFunction, ExpandDirection, JoinCondition, LogicalExpression,
750 PathMode, Projection, ReturnItem, SortOrder,
751 };
752
753 #[test]
754 fn test_cost_addition() {
755 let a = Cost::cpu(10.0).with_io(5.0);
756 let b = Cost::cpu(20.0).with_memory(100.0);
757 let c = a + b;
758
759 assert!((c.cpu - 30.0).abs() < 0.001);
760 assert!((c.io - 5.0).abs() < 0.001);
761 assert!((c.memory - 100.0).abs() < 0.001);
762 }
763
764 #[test]
765 fn test_cost_total() {
766 let cost = Cost::cpu(10.0).with_io(1.0).with_memory(100.0);
767 assert!((cost.total() - 30.0).abs() < 0.001);
769 }
770
771 #[test]
772 fn test_cost_model_node_scan() {
773 let model = CostModel::new();
774 let scan = NodeScanOp {
775 variable: "n".to_string(),
776 label: Some("Person".to_string()),
777 input: None,
778 };
779 let cost = model.node_scan_cost(&scan, 1000.0);
780
781 assert!(cost.cpu > 0.0);
782 assert!(cost.io > 0.0);
783 }
784
785 #[test]
786 fn test_cost_model_sort() {
787 let model = CostModel::new();
788 let sort = SortOp {
789 keys: vec![],
790 input: Box::new(LogicalOperator::Empty),
791 };
792
793 let cost_100 = model.sort_cost(&sort, 100.0);
794 let cost_1000 = model.sort_cost(&sort, 1000.0);
795
796 assert!(cost_1000.total() > cost_100.total());
798 }
799
800 #[test]
801 fn test_cost_zero() {
802 let cost = Cost::zero();
803 assert!((cost.cpu).abs() < 0.001);
804 assert!((cost.io).abs() < 0.001);
805 assert!((cost.memory).abs() < 0.001);
806 assert!((cost.network).abs() < 0.001);
807 assert!((cost.total()).abs() < 0.001);
808 }
809
810 #[test]
811 fn test_cost_add_assign() {
812 let mut cost = Cost::cpu(10.0);
813 cost += Cost::cpu(5.0).with_io(2.0);
814 assert!((cost.cpu - 15.0).abs() < 0.001);
815 assert!((cost.io - 2.0).abs() < 0.001);
816 }
817
818 #[test]
819 fn test_cost_total_weighted() {
820 let cost = Cost::cpu(10.0).with_io(2.0).with_memory(100.0);
821 let total = cost.total_weighted(2.0, 5.0, 0.5);
823 assert!((total - 80.0).abs() < 0.001);
824 }
825
826 #[test]
827 fn test_cost_model_filter() {
828 let model = CostModel::new();
829 let filter = FilterOp {
830 predicate: LogicalExpression::Literal(grafeo_common::types::Value::Bool(true)),
831 input: Box::new(LogicalOperator::Empty),
832 pushdown_hint: None,
833 };
834 let cost = model.filter_cost(&filter, 1000.0);
835
836 assert!(cost.cpu > 0.0);
838 assert!((cost.io).abs() < 0.001);
839 }
840
841 #[test]
842 fn test_cost_model_project() {
843 let model = CostModel::new();
844 let project = ProjectOp {
845 projections: vec![
846 Projection {
847 expression: LogicalExpression::Variable("a".to_string()),
848 alias: None,
849 },
850 Projection {
851 expression: LogicalExpression::Variable("b".to_string()),
852 alias: None,
853 },
854 ],
855 input: Box::new(LogicalOperator::Empty),
856 pass_through_input: false,
857 };
858 let cost = model.project_cost(&project, 1000.0);
859
860 assert!(cost.cpu > 0.0);
862 }
863
864 #[test]
865 fn test_cost_model_expand() {
866 let model = CostModel::new();
867 let expand = ExpandOp {
868 from_variable: "a".to_string(),
869 to_variable: "b".to_string(),
870 edge_variable: None,
871 direction: ExpandDirection::Outgoing,
872 edge_types: vec![],
873 min_hops: 1,
874 max_hops: Some(1),
875 input: Box::new(LogicalOperator::Empty),
876 path_alias: None,
877 path_mode: PathMode::Walk,
878 };
879 let cost = model.expand_cost(&expand, 1000.0);
880
881 assert!(cost.cpu > 0.0);
883 }
884
885 #[test]
886 fn test_cost_model_expand_with_edge_type_stats() {
887 let mut degrees = std::collections::HashMap::new();
888 degrees.insert("KNOWS".to_string(), (5.0, 5.0)); degrees.insert("WORKS_AT".to_string(), (1.0, 50.0)); let model = CostModel::new().with_edge_type_degrees(degrees);
892
893 let knows_out = ExpandOp {
895 from_variable: "a".to_string(),
896 to_variable: "b".to_string(),
897 edge_variable: None,
898 direction: ExpandDirection::Outgoing,
899 edge_types: vec!["KNOWS".to_string()],
900 min_hops: 1,
901 max_hops: Some(1),
902 input: Box::new(LogicalOperator::Empty),
903 path_alias: None,
904 path_mode: PathMode::Walk,
905 };
906 let cost_knows = model.expand_cost(&knows_out, 1000.0);
907
908 let works_out = ExpandOp {
910 from_variable: "a".to_string(),
911 to_variable: "b".to_string(),
912 edge_variable: None,
913 direction: ExpandDirection::Outgoing,
914 edge_types: vec!["WORKS_AT".to_string()],
915 min_hops: 1,
916 max_hops: Some(1),
917 input: Box::new(LogicalOperator::Empty),
918 path_alias: None,
919 path_mode: PathMode::Walk,
920 };
921 let cost_works = model.expand_cost(&works_out, 1000.0);
922
923 assert!(
925 cost_knows.cpu > cost_works.cpu,
926 "KNOWS(5) should cost more than WORKS_AT(1)"
927 );
928
929 let works_in = ExpandOp {
931 from_variable: "c".to_string(),
932 to_variable: "p".to_string(),
933 edge_variable: None,
934 direction: ExpandDirection::Incoming,
935 edge_types: vec!["WORKS_AT".to_string()],
936 min_hops: 1,
937 max_hops: Some(1),
938 input: Box::new(LogicalOperator::Empty),
939 path_alias: None,
940 path_mode: PathMode::Walk,
941 };
942 let cost_works_in = model.expand_cost(&works_in, 1000.0);
943
944 assert!(
946 cost_works_in.cpu > cost_knows.cpu,
947 "Incoming WORKS_AT(50) should cost more than KNOWS(5)"
948 );
949 }
950
951 #[test]
952 fn test_cost_model_expand_unknown_edge_type_uses_global_fanout() {
953 let model = CostModel::new().with_avg_fanout(7.0);
954 let expand = ExpandOp {
955 from_variable: "a".to_string(),
956 to_variable: "b".to_string(),
957 edge_variable: None,
958 direction: ExpandDirection::Outgoing,
959 edge_types: vec!["UNKNOWN_TYPE".to_string()],
960 min_hops: 1,
961 max_hops: Some(1),
962 input: Box::new(LogicalOperator::Empty),
963 path_alias: None,
964 path_mode: PathMode::Walk,
965 };
966 let cost_unknown = model.expand_cost(&expand, 1000.0);
967
968 let expand_no_type = ExpandOp {
970 from_variable: "a".to_string(),
971 to_variable: "b".to_string(),
972 edge_variable: None,
973 direction: ExpandDirection::Outgoing,
974 edge_types: vec![],
975 min_hops: 1,
976 max_hops: Some(1),
977 input: Box::new(LogicalOperator::Empty),
978 path_alias: None,
979 path_mode: PathMode::Walk,
980 };
981 let cost_no_type = model.expand_cost(&expand_no_type, 1000.0);
982
983 assert!(
985 (cost_unknown.cpu - cost_no_type.cpu).abs() < 0.001,
986 "Unknown edge type should use global fanout"
987 );
988 }
989
990 #[test]
991 fn test_cost_model_hash_join() {
992 let model = CostModel::new();
993 let join = JoinOp {
994 left: Box::new(LogicalOperator::Empty),
995 right: Box::new(LogicalOperator::Empty),
996 join_type: JoinType::Inner,
997 conditions: vec![JoinCondition {
998 left: LogicalExpression::Variable("a".to_string()),
999 right: LogicalExpression::Variable("b".to_string()),
1000 }],
1001 };
1002 let cost = model.join_cost(&join, 10000.0);
1003
1004 assert!(cost.cpu > 0.0);
1006 assert!(cost.memory > 0.0);
1007 }
1008
1009 #[test]
1010 fn test_cost_model_cross_join() {
1011 let model = CostModel::new();
1012 let join = JoinOp {
1013 left: Box::new(LogicalOperator::Empty),
1014 right: Box::new(LogicalOperator::Empty),
1015 join_type: JoinType::Cross,
1016 conditions: vec![],
1017 };
1018 let cost = model.join_cost(&join, 1000000.0);
1019
1020 assert!(cost.cpu > 0.0);
1022 }
1023
1024 #[test]
1025 fn test_cost_model_semi_join() {
1026 let model = CostModel::new();
1027 let join = JoinOp {
1028 left: Box::new(LogicalOperator::Empty),
1029 right: Box::new(LogicalOperator::Empty),
1030 join_type: JoinType::Semi,
1031 conditions: vec![],
1032 };
1033 let cost_semi = model.join_cost(&join, 1000.0);
1034
1035 let inner_join = JoinOp {
1036 left: Box::new(LogicalOperator::Empty),
1037 right: Box::new(LogicalOperator::Empty),
1038 join_type: JoinType::Inner,
1039 conditions: vec![],
1040 };
1041 let cost_inner = model.join_cost(&inner_join, 1000.0);
1042
1043 assert!(cost_semi.cpu > 0.0);
1045 assert!(cost_inner.cpu > 0.0);
1046 }
1047
1048 #[test]
1049 fn test_cost_model_aggregate() {
1050 let model = CostModel::new();
1051 let agg = AggregateOp {
1052 group_by: vec![],
1053 aggregates: vec![
1054 AggregateExpr {
1055 function: AggregateFunction::Count,
1056 expression: None,
1057 expression2: None,
1058 distinct: false,
1059 alias: Some("cnt".to_string()),
1060 percentile: None,
1061 separator: None,
1062 },
1063 AggregateExpr {
1064 function: AggregateFunction::Sum,
1065 expression: Some(LogicalExpression::Variable("x".to_string())),
1066 expression2: None,
1067 distinct: false,
1068 alias: Some("total".to_string()),
1069 percentile: None,
1070 separator: None,
1071 },
1072 ],
1073 input: Box::new(LogicalOperator::Empty),
1074 having: None,
1075 };
1076 let cost = model.aggregate_cost(&agg, 1000.0);
1077
1078 assert!(cost.cpu > 0.0);
1080 assert!(cost.memory > 0.0);
1081 }
1082
1083 #[test]
1084 fn test_cost_model_distinct() {
1085 let model = CostModel::new();
1086 let distinct = DistinctOp {
1087 input: Box::new(LogicalOperator::Empty),
1088 columns: None,
1089 };
1090 let cost = model.distinct_cost(&distinct, 1000.0);
1091
1092 assert!(cost.cpu > 0.0);
1094 assert!(cost.memory > 0.0);
1095 }
1096
1097 #[test]
1098 fn test_cost_model_limit() {
1099 let model = CostModel::new();
1100 let limit = LimitOp {
1101 count: 10.into(),
1102 input: Box::new(LogicalOperator::Empty),
1103 };
1104 let cost = model.limit_cost(&limit, 1000.0);
1105
1106 assert!(cost.cpu > 0.0);
1108 assert!(cost.cpu < 1.0); }
1110
1111 #[test]
1112 fn test_cost_model_skip() {
1113 let model = CostModel::new();
1114 let skip = SkipOp {
1115 count: 100.into(),
1116 input: Box::new(LogicalOperator::Empty),
1117 };
1118 let cost = model.skip_cost(&skip, 1000.0);
1119
1120 assert!(cost.cpu > 0.0);
1122 }
1123
1124 #[test]
1125 fn test_cost_model_return() {
1126 let model = CostModel::new();
1127 let ret = ReturnOp {
1128 items: vec![
1129 ReturnItem {
1130 expression: LogicalExpression::Variable("a".to_string()),
1131 alias: None,
1132 },
1133 ReturnItem {
1134 expression: LogicalExpression::Variable("b".to_string()),
1135 alias: None,
1136 },
1137 ],
1138 distinct: false,
1139 input: Box::new(LogicalOperator::Empty),
1140 };
1141 let cost = model.return_cost(&ret, 1000.0);
1142
1143 assert!(cost.cpu > 0.0);
1145 }
1146
1147 #[test]
1148 fn test_cost_cheaper() {
1149 let model = CostModel::new();
1150 let cheap = Cost::cpu(10.0);
1151 let expensive = Cost::cpu(100.0);
1152
1153 assert_eq!(model.cheaper(&cheap, &expensive).total(), cheap.total());
1154 assert_eq!(model.cheaper(&expensive, &cheap).total(), cheap.total());
1155 }
1156
1157 #[test]
1158 fn test_cost_comparison_prefers_lower_total() {
1159 let model = CostModel::new();
1160 let cpu_heavy = Cost::cpu(100.0).with_io(1.0);
1162 let io_heavy = Cost::cpu(10.0).with_io(20.0);
1164
1165 assert!(cpu_heavy.total() < io_heavy.total());
1167 assert_eq!(
1168 model.cheaper(&cpu_heavy, &io_heavy).total(),
1169 cpu_heavy.total()
1170 );
1171 }
1172
1173 #[test]
1174 fn test_cost_model_sort_with_keys() {
1175 let model = CostModel::new();
1176 let sort_single = SortOp {
1177 keys: vec![crate::query::plan::SortKey {
1178 expression: LogicalExpression::Variable("a".to_string()),
1179 order: SortOrder::Ascending,
1180 nulls: None,
1181 }],
1182 input: Box::new(LogicalOperator::Empty),
1183 };
1184 let sort_multi = SortOp {
1185 keys: vec![
1186 crate::query::plan::SortKey {
1187 expression: LogicalExpression::Variable("a".to_string()),
1188 order: SortOrder::Ascending,
1189 nulls: None,
1190 },
1191 crate::query::plan::SortKey {
1192 expression: LogicalExpression::Variable("b".to_string()),
1193 order: SortOrder::Descending,
1194 nulls: None,
1195 },
1196 ],
1197 input: Box::new(LogicalOperator::Empty),
1198 };
1199
1200 let cost_single = model.sort_cost(&sort_single, 1000.0);
1201 let cost_multi = model.sort_cost(&sort_multi, 1000.0);
1202
1203 assert!(cost_multi.cpu > cost_single.cpu);
1205 }
1206
1207 #[test]
1208 fn test_cost_model_empty_operator() {
1209 let model = CostModel::new();
1210 let cost = model.estimate(&LogicalOperator::Empty, 0.0);
1211 assert!((cost.total()).abs() < 0.001);
1212 }
1213
1214 #[test]
1215 fn test_cost_model_default() {
1216 let model = CostModel::default();
1217 let scan = NodeScanOp {
1218 variable: "n".to_string(),
1219 label: None,
1220 input: None,
1221 };
1222 let cost = model.estimate(&LogicalOperator::NodeScan(scan), 100.0);
1223 assert!(cost.total() > 0.0);
1224 }
1225
1226 #[test]
1227 fn test_leapfrog_join_cost() {
1228 let model = CostModel::new();
1229
1230 let cardinalities = vec![1000.0, 1000.0, 1000.0];
1232 let cost = model.leapfrog_join_cost(3, &cardinalities, 100.0);
1233
1234 assert!(cost.cpu > 0.0);
1236 assert!(cost.memory > 0.0);
1238 }
1239
1240 #[test]
1241 fn test_leapfrog_join_cost_empty() {
1242 let model = CostModel::new();
1243 let cost = model.leapfrog_join_cost(0, &[], 0.0);
1244 assert!((cost.total()).abs() < 0.001);
1245 }
1246
1247 #[test]
1248 fn test_prefer_leapfrog_join_for_triangles() {
1249 let model = CostModel::new();
1250
1251 let cardinalities = vec![10000.0, 10000.0, 10000.0];
1253 let output = 1000.0;
1254
1255 let leapfrog_cost = model.leapfrog_join_cost(3, &cardinalities, output);
1256
1257 assert!(leapfrog_cost.cpu > 0.0);
1259 assert!(leapfrog_cost.memory > 0.0);
1260
1261 let _prefer = model.prefer_leapfrog_join(3, &cardinalities, output);
1264 }
1266
1267 #[test]
1268 fn test_prefer_leapfrog_join_binary_case() {
1269 let model = CostModel::new();
1270
1271 let cardinalities = vec![1000.0, 1000.0];
1273 let prefer = model.prefer_leapfrog_join(2, &cardinalities, 500.0);
1274 assert!(!prefer, "Binary joins should use hash join, not leapfrog");
1275 }
1276
1277 #[test]
1278 fn test_factorized_benefit_single_hop() {
1279 let model = CostModel::new();
1280
1281 let benefit = model.factorized_benefit(10.0, 1);
1283 assert!(
1284 (benefit - 1.0).abs() < 0.001,
1285 "Single hop should have no benefit"
1286 );
1287 }
1288
1289 #[test]
1290 fn test_factorized_benefit_multi_hop() {
1291 let model = CostModel::new();
1292
1293 let benefit = model.factorized_benefit(10.0, 3);
1295
1296 assert!(benefit <= 1.0, "Benefit should be <= 1.0");
1300 assert!(benefit > 0.0, "Benefit should be positive");
1301 }
1302
1303 #[test]
1304 fn test_factorized_benefit_low_fanout() {
1305 let model = CostModel::new();
1306
1307 let benefit = model.factorized_benefit(1.5, 2);
1309 assert!(
1310 benefit <= 1.0,
1311 "Low fanout still benefits from factorization"
1312 );
1313 }
1314
1315 #[test]
1316 fn test_node_scan_uses_label_cardinality_for_io() {
1317 let mut label_cards = std::collections::HashMap::new();
1318 label_cards.insert("Person".to_string(), 500_u64);
1319 label_cards.insert("Company".to_string(), 50_u64);
1320
1321 let model = CostModel::new()
1322 .with_label_cardinalities(label_cards)
1323 .with_graph_totals(550, 1000);
1324
1325 let person_scan = NodeScanOp {
1326 variable: "n".to_string(),
1327 label: Some("Person".to_string()),
1328 input: None,
1329 };
1330 let company_scan = NodeScanOp {
1331 variable: "n".to_string(),
1332 label: Some("Company".to_string()),
1333 input: None,
1334 };
1335
1336 let person_cost = model.node_scan_cost(&person_scan, 500.0);
1337 let company_cost = model.node_scan_cost(&company_scan, 50.0);
1338
1339 assert!(
1341 person_cost.io > company_cost.io * 5.0,
1342 "Person ({}) should have much higher IO than Company ({})",
1343 person_cost.io,
1344 company_cost.io
1345 );
1346 }
1347
1348 #[test]
1349 fn test_node_scan_unlabeled_uses_total_nodes() {
1350 let model = CostModel::new().with_graph_totals(10_000, 50_000);
1351
1352 let scan = NodeScanOp {
1353 variable: "n".to_string(),
1354 label: None,
1355 input: None,
1356 };
1357
1358 let cost = model.node_scan_cost(&scan, 10_000.0);
1359 let expected_pages = (10_000.0 * 100.0) / 8192.0;
1360 assert!(
1361 (cost.io - expected_pages).abs() < 0.1,
1362 "Unlabeled scan should use total_nodes for IO: got {}, expected {}",
1363 cost.io,
1364 expected_pages
1365 );
1366 }
1367
1368 #[test]
1369 fn test_join_cost_with_actual_child_cardinalities() {
1370 let model = CostModel::new();
1371 let join = JoinOp {
1372 left: Box::new(LogicalOperator::Empty),
1373 right: Box::new(LogicalOperator::Empty),
1374 join_type: JoinType::Inner,
1375 conditions: vec![JoinCondition {
1376 left: LogicalExpression::Variable("a".to_string()),
1377 right: LogicalExpression::Variable("b".to_string()),
1378 }],
1379 };
1380
1381 let cost_actual = model.join_cost_with_children(&join, 500.0, Some(100.0), Some(10_000.0));
1383
1384 let cost_sqrt = model.join_cost(&join, 500.0);
1386
1387 assert!(
1391 cost_actual.cpu > cost_sqrt.cpu,
1392 "Actual child cardinalities ({}) should produce different cost than sqrt fallback ({})",
1393 cost_actual.cpu,
1394 cost_sqrt.cpu
1395 );
1396 }
1397
1398 #[test]
1399 fn test_expand_multi_edge_types() {
1400 let mut degrees = std::collections::HashMap::new();
1401 degrees.insert("KNOWS".to_string(), (5.0, 5.0));
1402 degrees.insert("FOLLOWS".to_string(), (20.0, 100.0));
1403
1404 let model = CostModel::new().with_edge_type_degrees(degrees);
1405
1406 let multi_expand = ExpandOp {
1408 from_variable: "a".to_string(),
1409 to_variable: "b".to_string(),
1410 edge_variable: None,
1411 direction: ExpandDirection::Outgoing,
1412 edge_types: vec!["KNOWS".to_string(), "FOLLOWS".to_string()],
1413 min_hops: 1,
1414 max_hops: Some(1),
1415 input: Box::new(LogicalOperator::Empty),
1416 path_alias: None,
1417 path_mode: PathMode::Walk,
1418 };
1419 let multi_cost = model.expand_cost(&multi_expand, 100.0);
1420
1421 let single_expand = ExpandOp {
1423 from_variable: "a".to_string(),
1424 to_variable: "b".to_string(),
1425 edge_variable: None,
1426 direction: ExpandDirection::Outgoing,
1427 edge_types: vec!["KNOWS".to_string()],
1428 min_hops: 1,
1429 max_hops: Some(1),
1430 input: Box::new(LogicalOperator::Empty),
1431 path_alias: None,
1432 path_mode: PathMode::Walk,
1433 };
1434 let single_cost = model.expand_cost(&single_expand, 100.0);
1435
1436 assert!(
1438 multi_cost.cpu > single_cost.cpu * 3.0,
1439 "Multi-type fanout ({}) should be much higher than single-type ({})",
1440 multi_cost.cpu,
1441 single_cost.cpu
1442 );
1443 }
1444
1445 #[test]
1446 fn test_recursive_tree_cost() {
1447 use crate::query::optimizer::CardinalityEstimator;
1448
1449 let mut label_cards = std::collections::HashMap::new();
1450 label_cards.insert("Person".to_string(), 1000_u64);
1451
1452 let model = CostModel::new()
1453 .with_label_cardinalities(label_cards)
1454 .with_graph_totals(1000, 5000)
1455 .with_avg_fanout(5.0);
1456
1457 let mut card_est = CardinalityEstimator::new();
1458 card_est.add_table_stats("Person", crate::query::optimizer::TableStats::new(1000));
1459
1460 let plan = LogicalOperator::Return(ReturnOp {
1462 items: vec![ReturnItem {
1463 expression: LogicalExpression::Variable("n".to_string()),
1464 alias: None,
1465 }],
1466 distinct: false,
1467 input: Box::new(LogicalOperator::Filter(FilterOp {
1468 predicate: LogicalExpression::Binary {
1469 left: Box::new(LogicalExpression::Property {
1470 variable: "n".to_string(),
1471 property: "age".to_string(),
1472 }),
1473 op: crate::query::plan::BinaryOp::Gt,
1474 right: Box::new(LogicalExpression::Literal(
1475 grafeo_common::types::Value::Int64(30),
1476 )),
1477 },
1478 input: Box::new(LogicalOperator::NodeScan(NodeScanOp {
1479 variable: "n".to_string(),
1480 label: Some("Person".to_string()),
1481 input: None,
1482 })),
1483 pushdown_hint: None,
1484 })),
1485 });
1486
1487 let tree_cost = model.estimate_tree(&plan, &card_est);
1488
1489 assert!(tree_cost.cpu > 0.0, "Tree should have CPU cost");
1491 assert!(tree_cost.io > 0.0, "Tree should have IO cost from scan");
1492
1493 let root_only_card = card_est.estimate(&plan);
1495 let root_only_cost = model.estimate(&plan, root_only_card);
1496
1497 assert!(
1499 tree_cost.total() > root_only_cost.total(),
1500 "Recursive tree cost ({}) should exceed root-only cost ({})",
1501 tree_cost.total(),
1502 root_only_cost.total()
1503 );
1504 }
1505
1506 #[test]
1507 fn test_statistics_driven_vs_default_cost() {
1508 let default_model = CostModel::new();
1509
1510 let mut label_cards = std::collections::HashMap::new();
1511 label_cards.insert("Person".to_string(), 100_u64);
1512 let stats_model = CostModel::new()
1513 .with_label_cardinalities(label_cards)
1514 .with_graph_totals(100, 500);
1515
1516 let scan = NodeScanOp {
1518 variable: "n".to_string(),
1519 label: Some("Person".to_string()),
1520 input: None,
1521 };
1522
1523 let default_cost = default_model.node_scan_cost(&scan, 100.0);
1524 let stats_cost = stats_model.node_scan_cost(&scan, 100.0);
1525
1526 assert!(
1530 (default_cost.io - stats_cost.io).abs() < 0.1,
1531 "When cardinality matches label size, costs should be similar"
1532 );
1533 }
1534
1535 #[test]
1536 fn test_leapfrog_join_cost_unit_min_cardinality() {
1537 let model = CostModel::new();
1538 let cost = model.leapfrog_join_cost(3, &[1.0, 100.0, 200.0], 50.0);
1540 assert!(cost.cpu > 0.0);
1541 assert!(cost.memory > 0.0);
1542 }
1543
1544 #[test]
1545 fn test_prefer_leapfrog_join_cardinalities_below_three() {
1546 let model = CostModel::new();
1547 assert!(!model.prefer_leapfrog_join(3, &[100.0, 200.0], 50.0));
1549 assert!(!model.prefer_leapfrog_join(5, &[], 10.0));
1550 }
1551
1552 #[test]
1553 fn test_factorized_benefit_zero_hops() {
1554 let model = CostModel::new();
1555 assert_eq!(model.factorized_benefit(10.0, 0), 1.0);
1557 }
1558
1559 #[test]
1560 fn test_factorized_benefit_unit_fanout_guard() {
1561 let model = CostModel::new();
1562 assert_eq!(model.factorized_benefit(1.0, 5), 1.0);
1564 }
1565}