optd_core/
cost.rs

1// Copyright (c) 2023-2024 CMU Database Group
2//
3// Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at
4// https://opensource.org/licenses/MIT.
5
6use crate::cascades::{CascadesOptimizer, Memo, RelNodeContext};
7use crate::nodes::{ArcPredNode, NodeType};
8
9/// The statistics of a group.
10pub struct Statistics(pub Box<dyn std::any::Any + Send + Sync + 'static>);
11
12/// The cost of an operation. The cost is represented as a vector of double values.
13/// For example, it can be represented as `[compute_cost, io_cost]`.
14/// A lower value means a better cost.
15#[derive(Default, Clone, Debug, PartialOrd, PartialEq)]
16pub struct Cost(pub Vec<f64>);
17
18pub trait CostModel<T: NodeType, M: Memo<T>>: 'static + Send + Sync {
19    /// Compute the cost of a single operation
20    #[allow(clippy::too_many_arguments)]
21    fn compute_operation_cost(
22        &self,
23        node: &T,
24        predicates: &[ArcPredNode<T>],
25        children_stats: &[Option<&Statistics>],
26        children_costs: &[Cost],
27        context: Option<RelNodeContext>,
28        optimizer: Option<&CascadesOptimizer<T, M>>,
29    ) -> Cost;
30
31    /// Derive the statistics of a single operation
32    fn derive_statistics(
33        &self,
34        node: &T,
35        predicates: &[ArcPredNode<T>],
36        children_stats: &[&Statistics],
37        context: Option<RelNodeContext>,
38        optimizer: Option<&CascadesOptimizer<T, M>>,
39    ) -> Statistics;
40
41    fn explain_cost(&self, cost: &Cost) -> String;
42
43    fn explain_statistics(&self, cost: &Statistics) -> String;
44
45    fn accumulate(&self, total_cost: &mut Cost, cost: &Cost);
46
47    fn sum(&self, operation_cost: &Cost, inputs_cost: &[Cost]) -> Cost {
48        let mut total_cost = operation_cost.clone();
49        for input in inputs_cost {
50            self.accumulate(&mut total_cost, input);
51        }
52        total_cost
53    }
54
55    /// The zero cost.
56    fn zero(&self) -> Cost;
57
58    /// The weighted cost of a compound cost.
59    fn weighted_cost(&self, cost: &Cost) -> f64;
60}