Skip to main content

grafeo_engine/query/optimizer/
cost.rs

1//! Cost model for query optimization.
2//!
3//! Provides cost estimates for logical operators to guide optimization decisions.
4
5use 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/// Cost of an operation.
13///
14/// Represents the estimated resource consumption of executing an operator.
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct Cost {
17    /// Estimated CPU cycles / work units.
18    pub cpu: f64,
19    /// Estimated I/O operations (page reads).
20    pub io: f64,
21    /// Estimated memory usage in bytes.
22    pub memory: f64,
23    /// Network cost (for distributed queries).
24    pub network: f64,
25}
26
27impl Cost {
28    /// Creates a zero cost.
29    #[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    /// Creates a cost from CPU work units.
40    #[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    /// Adds I/O cost.
51    #[must_use]
52    pub fn with_io(mut self, io: f64) -> Self {
53        self.io = io;
54        self
55    }
56
57    /// Adds memory cost.
58    #[must_use]
59    pub fn with_memory(mut self, memory: f64) -> Self {
60        self.memory = memory;
61        self
62    }
63
64    /// Returns the total weighted cost.
65    ///
66    /// Uses default weights: CPU=1.0, IO=10.0, Memory=0.1, Network=100.0
67    #[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    /// Returns the total cost with custom weights.
73    #[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
101/// Cost model for estimating operator costs.
102///
103/// Default constants are calibrated relative to each other:
104/// - Tuple scan is the baseline (1x)
105/// - Hash lookup is ~3x (hash computation + potential cache miss)
106/// - Sort comparison is ~2x (key extraction + comparison)
107/// - Distance computation is ~10x (vector math)
108pub struct CostModel {
109    /// Cost per tuple processed by CPU (baseline unit).
110    cpu_tuple_cost: f64,
111    /// Cost per hash table lookup (~3x tuple cost: hash + cache miss).
112    hash_lookup_cost: f64,
113    /// Cost per comparison in sorting (~2x tuple cost: key extract + cmp).
114    sort_comparison_cost: f64,
115    /// Average tuple size in bytes (for IO estimation).
116    avg_tuple_size: f64,
117    /// Page size in bytes.
118    page_size: f64,
119    /// Global average edge fanout (fallback when per-type stats unavailable).
120    avg_fanout: f64,
121    /// Per-edge-type degree stats: (avg_out_degree, avg_in_degree).
122    edge_type_degrees: HashMap<String, (f64, f64)>,
123    /// Per-label node counts for accurate scan IO estimation.
124    label_cardinalities: HashMap<String, u64>,
125    /// Total node count in the graph.
126    total_nodes: u64,
127    /// Total edge count in the graph.
128    total_edges: u64,
129}
130
131impl CostModel {
132    /// Creates a new cost model with calibrated default parameters.
133    #[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    /// Sets the global average fanout from graph statistics.
150    #[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    /// Sets per-edge-type degree statistics for accurate expand cost estimation.
157    ///
158    /// Each entry maps edge type name to `(avg_out_degree, avg_in_degree)`.
159    #[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    /// Sets per-label node counts for accurate scan IO estimation.
166    #[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    /// Sets graph-level totals for cost estimation.
173    #[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    /// Returns the fanout for a specific expand operation.
181    ///
182    /// Uses per-edge-type degree stats when available, falling back to the
183    /// global average fanout. For multiple edge types, sums per-type fanouts.
184    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    /// Estimates the cost of a logical operator.
213    #[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    /// Estimates the cost of a node scan.
241    ///
242    /// When label statistics are available, uses the actual label cardinality
243    /// for IO estimation (pages to read) rather than the optimizer's cardinality
244    /// estimate, which may already account for filter selectivity.
245    fn node_scan_cost(&self, scan: &NodeScanOp, cardinality: f64) -> Cost {
246        // IO cost: based on how many nodes we actually need to scan from storage
247        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        // CPU cost: only pay for rows that pass the label filter
258        Cost::cpu(cardinality * self.cpu_tuple_cost).with_io(pages)
259    }
260
261    /// Estimates the cost of a filter operation.
262    fn filter_cost(&self, _filter: &FilterOp, cardinality: f64) -> Cost {
263        // Filter cost is just predicate evaluation per tuple
264        Cost::cpu(cardinality * self.cpu_tuple_cost * 1.5)
265    }
266
267    /// Estimates the cost of a projection.
268    fn project_cost(&self, project: &ProjectOp, cardinality: f64) -> Cost {
269        // Cost depends on number of expressions evaluated
270        let expr_count = project.projections.len() as f64;
271        Cost::cpu(cardinality * self.cpu_tuple_cost * expr_count)
272    }
273
274    /// Estimates the cost of an expand operation.
275    ///
276    /// Uses per-edge-type degree stats when available, otherwise falls back
277    /// to the global average fanout.
278    fn expand_cost(&self, expand: &ExpandOp, cardinality: f64) -> Cost {
279        let fanout = self.fanout_for_expand(expand);
280        // Adjacency list lookup per input row
281        let lookup_cost = cardinality * self.hash_lookup_cost;
282        // Process each expanded output tuple
283        let output_cost = cardinality * fanout * self.cpu_tuple_cost;
284        Cost::cpu(lookup_cost + output_cost)
285    }
286
287    /// Estimates the cost of a join operation.
288    ///
289    /// When child cardinalities are known (from recursive estimation), uses them
290    /// directly for build/probe cost. Otherwise falls back to sqrt approximation.
291    fn join_cost(&self, join: &JoinOp, cardinality: f64) -> Cost {
292        self.join_cost_with_children(join, cardinality, None, None)
293    }
294
295    /// Estimates join cost using actual child cardinalities.
296    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                // Hash join: build the smaller side, probe with the larger
307                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    /// Estimates the cost of a left outer join (OPTIONAL MATCH).
331    ///
332    /// Uses the same hash join cost model as inner joins: the right side is
333    /// built into a hash table, the left side probes. Output cost includes all
334    /// left rows (some with NULL-padded right side).
335    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    /// Estimates the cardinality of a child operator using available statistics.
351    ///
352    /// Used internally to compute left/right child cardinalities for joins
353    /// without requiring an external `CardinalityEstimator`. Uses the same
354    /// statistics the cost model already holds (label counts, fanout).
355    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                // Approximate: filters reduce cardinality by 10%
376                (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                // LimitOp.count may be a parameter; use input as upper bound
382                input.min(100.0)
383            }
384            _ => (self.total_nodes as f64).max(1.0),
385        }
386    }
387
388    /// Estimates the cost of a multi-way (leapfrog) join.
389    ///
390    /// Delegates to `leapfrog_join_cost` using per-input cardinality estimates
391    /// derived from the output cardinality divided equally among inputs.
392    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        // Approximate per-input cardinalities: assume each input contributes
398        // cardinality^(1/n) rows (AGM-style uniform assumption)
399        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    /// Estimates the cost of an aggregation.
405    fn aggregate_cost(&self, agg: &AggregateOp, cardinality: f64) -> Cost {
406        // Hash aggregation cost
407        let hash_cost = cardinality * self.hash_lookup_cost;
408
409        // Aggregate function evaluation
410        let agg_count = agg.aggregates.len() as f64;
411        let agg_cost = cardinality * self.cpu_tuple_cost * agg_count;
412
413        // Memory for hash table (estimated distinct groups)
414        let distinct_groups = (cardinality / 10.0).max(1.0); // Assume 10% distinct
415        let memory_cost = distinct_groups * self.avg_tuple_size;
416
417        Cost::cpu(hash_cost + agg_cost).with_memory(memory_cost)
418    }
419
420    /// Estimates the cost of a sort operation.
421    fn sort_cost(&self, sort: &SortOp, cardinality: f64) -> Cost {
422        if cardinality <= 1.0 {
423            return Cost::zero();
424        }
425
426        // Sort is O(n log n) comparisons
427        let comparisons = cardinality * cardinality.log2();
428        let key_count = sort.keys.len() as f64;
429
430        // Memory for sorting (full input materialization)
431        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    /// Estimates the cost of a distinct operation.
437    fn distinct_cost(&self, _distinct: &DistinctOp, cardinality: f64) -> Cost {
438        // Hash-based distinct
439        let hash_cost = cardinality * self.hash_lookup_cost;
440        let memory_cost = cardinality * self.avg_tuple_size * 0.5; // Assume 50% distinct
441
442        Cost::cpu(hash_cost).with_memory(memory_cost)
443    }
444
445    /// Estimates the cost of a limit operation.
446    fn limit_cost(&self, limit: &LimitOp, _cardinality: f64) -> Cost {
447        // Limit is very cheap - just counting
448        Cost::cpu(limit.count.estimate() * self.cpu_tuple_cost * 0.1)
449    }
450
451    /// Estimates the cost of a skip operation.
452    fn skip_cost(&self, skip: &SkipOp, _cardinality: f64) -> Cost {
453        // Skip requires scanning through skipped rows
454        Cost::cpu(skip.count.estimate() * self.cpu_tuple_cost)
455    }
456
457    /// Estimates the cost of a return operation.
458    fn return_cost(&self, ret: &ReturnOp, cardinality: f64) -> Cost {
459        // Return materializes results
460        let expr_count = ret.items.len() as f64;
461        Cost::cpu(cardinality * self.cpu_tuple_cost * expr_count)
462    }
463
464    /// Estimates the cost of a vector scan operation.
465    ///
466    /// HNSW index search is O(log N) per query, while brute-force is O(N).
467    /// This estimates the HNSW case with ef search parameter.
468    fn vector_scan_cost(&self, scan: &VectorScanOp, cardinality: f64) -> Cost {
469        // k determines output cardinality
470        let k = scan.k as f64;
471
472        // HNSW search cost: O(ef * log(N)) distance computations
473        // Assume ef = 64 (default), N = cardinality
474        let ef = 64.0;
475        let n = cardinality.max(1.0);
476        let search_cost = if scan.index_name.is_some() {
477            // HNSW: O(ef * log N)
478            ef * n.ln() * self.cpu_tuple_cost * 10.0 // Distance computation is ~10x regular tuple
479        } else {
480            // Brute-force: O(N)
481            n * self.cpu_tuple_cost * 10.0
482        };
483
484        // Memory for candidate heap
485        let memory = k * self.avg_tuple_size * 2.0;
486
487        Cost::cpu(search_cost).with_memory(memory)
488    }
489
490    /// Estimates the cost of a vector join operation.
491    ///
492    /// Vector join performs k-NN search for each input row.
493    fn vector_join_cost(&self, join: &VectorJoinOp, cardinality: f64) -> Cost {
494        let k = join.k as f64;
495
496        // Each input row triggers a vector search
497        // Assume brute-force for hybrid queries (no index specified typically)
498        let per_row_search_cost = if join.index_name.is_some() {
499            // HNSW: O(ef * log N)
500            let ef = 64.0;
501            let n = cardinality.max(1.0);
502            ef * n.ln() * self.cpu_tuple_cost * 10.0
503        } else {
504            // Brute-force: O(N) per input row
505            cardinality * self.cpu_tuple_cost * 10.0
506        };
507
508        // Total cost: input_rows * search_cost
509        // For vector join, cardinality is typically input cardinality * k
510        let input_cardinality = (cardinality / k).max(1.0);
511        let total_search_cost = input_cardinality * per_row_search_cost;
512
513        // Memory for results
514        let memory = cardinality * self.avg_tuple_size;
515
516        Cost::cpu(total_search_cost).with_memory(memory)
517    }
518
519    /// Estimates the total cost of an operator tree recursively.
520    ///
521    /// Walks the entire plan tree, computing per-operator cost at each level
522    /// using the cardinality estimator for accurate child cardinalities.
523    /// Returns the sum of all operator costs in the tree.
524    #[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    /// Compares two costs and returns the cheaper one.
617    #[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    /// Estimates the cost of a worst-case optimal join (WCOJ/leapfrog join).
623    ///
624    /// WCOJ is optimal for cyclic patterns like triangles. Traditional binary
625    /// hash joins are O(N²) for triangles; WCOJ achieves O(N^1.5) by processing
626    /// all relations simultaneously using sorted iterators.
627    ///
628    /// # Arguments
629    /// * `num_relations` - Number of relations participating in the join
630    /// * `cardinalities` - Cardinality of each input relation
631    /// * `output_cardinality` - Expected output cardinality
632    ///
633    /// # Cost Model
634    /// - Materialization: O(sum of cardinalities) to build trie indexes
635    /// - Intersection: O(output * log(min_cardinality)) for leapfrog seek operations
636    /// - Memory: Trie storage for all inputs
637    #[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        // Materialization phase: build trie indexes for each input
652        let materialize_cost = total_input * self.cpu_tuple_cost * 2.0; // Sorting + trie building
653
654        // Intersection phase: leapfrog seeks are O(log n) per relation
655        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        // Output materialization
662        let output_cost = output_cardinality * self.cpu_tuple_cost;
663
664        // Memory: trie storage (roughly 2x input size for sorted index)
665        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    /// Compares hash join cost vs leapfrog join cost for a cyclic pattern.
671    ///
672    /// Returns true if leapfrog (WCOJ) is estimated to be cheaper.
673    #[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            // Leapfrog is only beneficial for multi-way joins (3+)
682            return false;
683        }
684
685        let leapfrog_cost =
686            self.leapfrog_join_cost(num_relations, cardinalities, output_cardinality);
687
688        // Estimate cascade of binary hash joins
689        // For N relations, we need N-1 joins
690        // Each join produces intermediate results that feed the next
691        let mut hash_cascade_cost = Cost::zero();
692        let mut intermediate_cardinality = cardinalities[0];
693
694        for card in &cardinalities[1..] {
695            // Hash join cost: build + probe + output
696            let join_output = (intermediate_cardinality * card).sqrt(); // Estimated selectivity
697            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    /// Estimates cost for factorized execution (compressed intermediate results).
711    ///
712    /// Factorized execution avoids materializing full cross products by keeping
713    /// results in a compressed "factorized" form. This is beneficial for multi-hop
714    /// traversals where intermediate results can explode.
715    ///
716    /// Returns the reduction factor (1.0 = no benefit, lower = more compression).
717    #[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; // No benefit for single hop or low fanout
721        }
722
723        // Factorized representation compresses repeated prefixes
724        // Compression ratio improves with higher fanout and more hops
725        // Full materialization: fanout^hops
726        // Factorized: sum(fanout^i for i in 1..=hops) ≈ fanout^(hops+1) / (fanout - 1)
727
728        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        // Total = 10 + 1*10 + 100*0.1 = 10 + 10 + 10 = 30
768        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        // Sorting 1000 rows should be more expensive than 100 rows
797        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        // With custom weights: cpu*2 + io*5 + mem*0.5 = 20 + 10 + 50 = 80
822        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        // Filter cost is CPU only
837        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        // Cost should scale with number of projections
861        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        // Expand involves hash lookups and output generation
882        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)); // Symmetric
889        degrees.insert("WORKS_AT".to_string(), (1.0, 50.0)); // Many-to-one
890
891        let model = CostModel::new().with_edge_type_degrees(degrees);
892
893        // Outgoing KNOWS: fanout = 5
894        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        // Outgoing WORKS_AT: fanout = 1 (each person works at one company)
909        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        // KNOWS (fanout=5) should be more expensive than WORKS_AT (fanout=1)
924        assert!(
925            cost_knows.cpu > cost_works.cpu,
926            "KNOWS(5) should cost more than WORKS_AT(1)"
927        );
928
929        // Incoming WORKS_AT: fanout = 50 (company has many employees)
930        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        // Incoming WORKS_AT (fanout=50) should be most expensive
945        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        // Without edge type (uses global fanout too)
969        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        // Both should use global fanout = 7, so costs should be equal
984        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        // Hash join has CPU cost and memory cost
1005        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        // Cross join is expensive
1021        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        // Semi join can be cheaper than inner join
1044        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        // Aggregation has hash cost and memory cost
1079        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        // Distinct uses hash set
1093        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        // Limit is very cheap
1107        assert!(cost.cpu > 0.0);
1108        assert!(cost.cpu < 1.0); // Should be minimal
1109    }
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        // Skip must scan through skipped rows
1121        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        // Return materializes results
1144        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        // High CPU, low IO
1161        let cpu_heavy = Cost::cpu(100.0).with_io(1.0);
1162        // Low CPU, high IO
1163        let io_heavy = Cost::cpu(10.0).with_io(20.0);
1164
1165        // IO is weighted 10x, so io_heavy = 10 + 200 = 210, cpu_heavy = 100 + 10 = 110
1166        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        // More sort keys = more comparisons
1204        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        // Three-way join (triangle pattern)
1231        let cardinalities = vec![1000.0, 1000.0, 1000.0];
1232        let cost = model.leapfrog_join_cost(3, &cardinalities, 100.0);
1233
1234        // Should have CPU cost for materialization and intersection
1235        assert!(cost.cpu > 0.0);
1236        // Should have memory cost for trie storage
1237        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        // Compare costs for triangle pattern
1252        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        // Leapfrog should have reasonable cost for triangle patterns
1258        assert!(leapfrog_cost.cpu > 0.0);
1259        assert!(leapfrog_cost.memory > 0.0);
1260
1261        // The prefer_leapfrog_join method compares against hash cascade
1262        // Actual preference depends on specific cost parameters
1263        let _prefer = model.prefer_leapfrog_join(3, &cardinalities, output);
1264        // Test that it returns a boolean (doesn't panic)
1265    }
1266
1267    #[test]
1268    fn test_prefer_leapfrog_join_binary_case() {
1269        let model = CostModel::new();
1270
1271        // Binary join should NOT prefer leapfrog (need 3+ relations)
1272        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        // Single hop: no factorization benefit
1282        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        // Multi-hop with high fanout
1294        let benefit = model.factorized_benefit(10.0, 3);
1295
1296        // The factorized_benefit returns a ratio capped at 1.0
1297        // For high fanout, factorized size / full size approaches 1/fanout
1298        // which is beneficial but the formula gives a value <= 1.0
1299        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        // Low fanout: minimal benefit
1308        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        // Person scan reads 10x more pages than Company scan
1340        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        // With actual child cardinalities (100 left, 10000 right)
1382        let cost_actual = model.join_cost_with_children(&join, 500.0, Some(100.0), Some(10_000.0));
1383
1384        // With sqrt fallback (sqrt(500) ~ 22.4 for both sides)
1385        let cost_sqrt = model.join_cost(&join, 500.0);
1386
1387        // Actual build side (100) is larger than sqrt(500) ~ 22.4, so
1388        // actual cost should be higher for build, but the probe side (10000)
1389        // should dominate
1390        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        // Multi-type outgoing: KNOWS(5) + FOLLOWS(20) = 25
1407        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        // Single type: KNOWS(5) only
1422        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        // Multi-type (fanout=25) should be more expensive than single (fanout=5)
1437        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        // Build a plan: NodeScan -> Filter -> Return
1461        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        // Tree cost should include scan IO + filter CPU + return CPU
1490        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        // Compare with single-operator estimate (only costs the root)
1494        let root_only_card = card_est.estimate(&plan);
1495        let root_only_cost = model.estimate(&plan, root_only_card);
1496
1497        // Tree cost should be strictly higher because it includes child costs
1498        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        // Scan a small label: statistics model knows it's only 100 nodes
1517        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        // With statistics, IO cost is based on actual label size (100 nodes)
1527        // Without statistics, IO cost uses cardinality parameter (also 100 here)
1528        // They should be equal in this case since cardinality matches label size
1529        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        // min_card == 1.0 exercises the else branch in seek_cost (output * cpu_tuple_cost)
1539        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        // num_relations >= 3 but fewer cardinality entries: second guard fires
1548        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        // Zero hops falls through the `num_hops <= 1` guard
1556        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        // fanout exactly 1.0: no benefit regardless of hop count
1563        assert_eq!(model.factorized_benefit(1.0, 5), 1.0);
1564    }
1565}