Skip to main content

vlorql_core/statistics/
cost.rs

1//! A three-dimensional cost model for comparing execution plans.
2//!
3//! Every operation is scored on three axes — [`Cost::cpu`],
4//! [`Cost::io`], and [`Cost::memory`] — so a planner can weigh, say, a
5//! cheap-IO/expensive-CPU plan against its opposite. Costs compose with
6//! `+` (run two operations) and `*` by a scalar (repeat an operation),
7//! and they order by their [scalar total](Cost::total) so
8//! `min`/`max`/`sort` pick the cheapest plan.
9//!
10//! [`CostEstimator`] turns cardinality estimates into concrete costs
11//! for the three plan building blocks the initial planner needs: table
12//! scans, joins, and sorts. It shares the [`CardinalityEstimator`]'s
13//! [`StatisticsProvider`](crate::statistics::StatisticsProvider), so a
14//! scan's cost reflects the same row estimates used elsewhere.
15
16use std::ops::{Add, Mul};
17use std::sync::Arc;
18
19use crate::errors::VlorQLError;
20use crate::schema::Predicate;
21
22use super::cardinality::CardinalityEstimator;
23use super::providers::StatisticsProvider;
24
25/// CPU cost charged per row emitted by a sequential table scan.
26pub const TABLE_SCAN_COST_PER_ROW: f64 = 1.0;
27/// CPU cost charged per row emitted by an index scan.
28pub const INDEX_SCAN_COST_PER_ROW: f64 = 0.1;
29/// CPU cost charged per candidate row pair examined by a join.
30pub const JOIN_CPU_COST_PER_PAIR: f64 = 0.01;
31/// Cost charged per row shipped across the network.
32pub const NETWORK_COST_PER_ROW: f64 = 0.5;
33/// Multiplier applied to the `n log n` comparison term of a sort.
34pub const SORT_CPU_COST_PER_ROW: f64 = 1.0;
35/// Memory charged to buffer one row while sorting.
36pub const SORT_MEMORY_PER_ROW: f64 = 1.0;
37
38/// The estimated cost of an operation, split across three resources.
39///
40/// The fields are additive resource *quantities*, not a single score.
41/// [`Cost::total`] collapses them into one comparable number, and the
42/// [`PartialOrd`]/[`Ord`] impls order by that total so a collection of
43/// candidate costs can be sorted directly.
44///
45/// # Examples
46///
47/// ```
48/// use vlorql_core::statistics::Cost;
49///
50/// let scan = Cost { cpu: 100.0, io: 10.0, memory: 0.0 };
51/// let sort = Cost { cpu: 20.0, io: 0.0, memory: 50.0 };
52/// let combined = scan + sort;
53/// assert_eq!(combined.cpu, 120.0);
54/// assert!(scan.total() > sort.total());
55/// ```
56#[derive(Debug, Clone, Copy, Default, PartialEq)]
57pub struct Cost {
58    /// Estimated CPU work (in abstract per-row units).
59    pub cpu: f64,
60    /// Estimated IO work (rows read from or written to storage).
61    pub io: f64,
62    /// Estimated peak memory (rows held in memory at once).
63    pub memory: f64,
64}
65
66impl Cost {
67    /// A zero cost, the additive identity.
68    pub const ZERO: Self = Self {
69        cpu: 0.0,
70        io: 0.0,
71        memory: 0.0,
72    };
73
74    /// Creates a cost from its three components.
75    pub fn new(cpu: f64, io: f64, memory: f64) -> Self {
76        Self { cpu, io, memory }
77    }
78
79    /// Collapses the three resources into a single comparable scalar.
80    ///
81    /// This is a plain sum of the components; callers that want to
82    /// weight the axes differently can read the fields directly.
83    pub fn total(&self) -> f64 {
84        self.cpu + self.io + self.memory
85    }
86}
87
88impl Add for Cost {
89    type Output = Self;
90
91    fn add(self, rhs: Self) -> Self {
92        Self {
93            cpu: self.cpu + rhs.cpu,
94            io: self.io + rhs.io,
95            memory: self.memory + rhs.memory,
96        }
97    }
98}
99
100impl Mul<f64> for Cost {
101    type Output = Self;
102
103    /// Scales every resource by `rhs` (e.g. to repeat an operation).
104    fn mul(self, rhs: f64) -> Self {
105        Self {
106            cpu: self.cpu * rhs,
107            io: self.io * rhs,
108            memory: self.memory * rhs,
109        }
110    }
111}
112
113impl PartialOrd for Cost {
114    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
115        self.total().partial_cmp(&other.total())
116    }
117}
118
119/// Turns cardinality estimates into concrete [`Cost`] values.
120///
121/// Clone is cheap: the estimator only holds a [`CardinalityEstimator`],
122/// which itself is a shared `Arc` handle to a
123/// [`StatisticsProvider`](crate::statistics::StatisticsProvider).
124#[derive(Debug, Clone)]
125pub struct CostEstimator {
126    cardinality: CardinalityEstimator,
127}
128
129impl CostEstimator {
130    /// Creates a cost estimator backed by `stats_provider`.
131    pub fn new(stats_provider: Arc<dyn StatisticsProvider>) -> Self {
132        Self {
133            cardinality: CardinalityEstimator::new(stats_provider),
134        }
135    }
136
137    /// Creates a cost estimator that shares an existing
138    /// [`CardinalityEstimator`].
139    pub fn with_cardinality(cardinality: CardinalityEstimator) -> Self {
140        Self { cardinality }
141    }
142
143    /// Returns the underlying cardinality estimator.
144    pub fn cardinality(&self) -> &CardinalityEstimator {
145        &self.cardinality
146    }
147
148    /// Estimates the cost of scanning `table`, optionally reduced by a
149    /// pushed-down `filter`.
150    ///
151    /// IO is charged for every stored row (the scan must read them all);
152    /// CPU is charged only for the rows that survive `filter`, using the
153    /// sequential-scan per-row weight. The output row count is folded
154    /// into `memory` so downstream operators can see the scan's fan-out.
155    pub async fn estimate_scan(
156        &self,
157        table: &str,
158        filter: Option<&Predicate>,
159    ) -> Result<Cost, VlorQLError> {
160        let rows = self.cardinality.estimate_table_cardinality(table).await?;
161        let selectivity = match filter {
162            Some(pred) => {
163                self.cardinality
164                    .estimate_predicate_cardinality(table, pred)
165                    .await?
166            }
167            None => 1.0,
168        };
169        let output_rows = rows as f64 * selectivity;
170        Ok(Cost {
171            cpu: output_rows * TABLE_SCAN_COST_PER_ROW,
172            io: rows as f64,
173            memory: output_rows,
174        })
175    }
176
177    /// Estimates the cost of joining two already-costed inputs that
178    /// together produce `join_cardinality` rows.
179    ///
180    /// The child costs are summed (both inputs must be produced), then a
181    /// nested-loop-style CPU term is charged for the candidate pairs the
182    /// join examines, approximated here by the output cardinality. The
183    /// result set is buffered in `memory`.
184    pub fn estimate_join(&self, left_cost: Cost, right_cost: Cost, join_cardinality: u64) -> Cost {
185        let pairs = join_cardinality as f64;
186        let join_cost = Cost {
187            cpu: pairs * JOIN_CPU_COST_PER_PAIR,
188            io: 0.0,
189            memory: pairs,
190        };
191        left_cost + right_cost + join_cost
192    }
193
194    /// Estimates the cost of sorting `cardinality` rows.
195    ///
196    /// CPU follows the `n log2 n` comparison count of a comparison sort
197    /// (with a floor of `n` so a single row still costs something), and
198    /// every row is buffered in `memory`.
199    pub fn estimate_sort(&self, cardinality: u64) -> Cost {
200        let n = cardinality as f64;
201        let comparisons = if cardinality > 1 { n * n.log2() } else { n };
202        Cost {
203            cpu: comparisons * SORT_CPU_COST_PER_ROW,
204            io: 0.0,
205            memory: n * SORT_MEMORY_PER_ROW,
206        }
207    }
208
209    /// Estimates the network cost of shipping `cardinality` rows to the
210    /// caller.
211    pub fn estimate_network(&self, cardinality: u64) -> Cost {
212        Cost {
213            cpu: cardinality as f64 * NETWORK_COST_PER_ROW,
214            io: 0.0,
215            memory: 0.0,
216        }
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223    use crate::schema::{ComparisonOperator, DataType, Expression, Predicate};
224    use crate::statistics::{
225        ColumnStatistics, DummyStatisticsProvider, StatisticsCatalog, TableStatistics,
226    };
227    use serde_json::json;
228
229    fn estimator() -> CostEstimator {
230        let mut users = TableStatistics {
231            row_count: 10_000,
232            ..TableStatistics::default()
233        };
234        users.columns.insert(
235            "status".to_owned(),
236            ColumnStatistics {
237                distinct_count: 4,
238                ..ColumnStatistics::default()
239            },
240        );
241
242        let mut catalog = StatisticsCatalog::default();
243        catalog.tables.insert("users".to_owned(), users);
244        CostEstimator::new(Arc::new(DummyStatisticsProvider::new(catalog)))
245    }
246
247    #[test]
248    fn cost_add_is_componentwise() {
249        let a = Cost::new(1.0, 2.0, 3.0);
250        let b = Cost::new(10.0, 20.0, 30.0);
251        assert_eq!(a + b, Cost::new(11.0, 22.0, 33.0));
252    }
253
254    #[test]
255    fn cost_mul_scales_each_component() {
256        let scaled = Cost::new(1.0, 2.0, 3.0) * 2.0;
257        assert_eq!(scaled, Cost::new(2.0, 4.0, 6.0));
258    }
259
260    #[test]
261    fn cost_default_and_zero_are_empty() {
262        assert_eq!(Cost::default(), Cost::ZERO);
263        assert_eq!(Cost::default().total(), 0.0);
264    }
265
266    #[test]
267    fn cost_orders_by_total() {
268        let cheap = Cost::new(1.0, 1.0, 1.0);
269        let pricey = Cost::new(10.0, 0.0, 0.0);
270        assert!(cheap < pricey);
271
272        let mut costs = [pricey, cheap];
273        costs.sort_by(|a, b| a.partial_cmp(b).unwrap());
274        assert_eq!(costs[0], cheap);
275    }
276
277    #[tokio::test]
278    async fn scan_without_filter_charges_every_row() {
279        let cost = estimator().estimate_scan("users", None).await.unwrap();
280        assert_eq!(cost.io, 10_000.0);
281        assert_eq!(cost.cpu, 10_000.0);
282        assert_eq!(cost.memory, 10_000.0);
283    }
284
285    #[tokio::test]
286    async fn scan_with_filter_reads_all_rows_but_emits_fewer() {
287        // status = 'active' has selectivity 1/4, so 2500 rows survive.
288        let filter = Predicate::Comparison {
289            left: Expression::ColumnRef {
290                table: Some("users".to_owned()),
291                column: "status".to_owned(),
292            },
293            op: ComparisonOperator::Eq,
294            right: Expression::Literal {
295                value: json!("active"),
296                data_type: DataType::String,
297            },
298        };
299        let cost = estimator()
300            .estimate_scan("users", Some(&filter))
301            .await
302            .unwrap();
303        // IO still reads the whole table.
304        assert_eq!(cost.io, 10_000.0);
305        // CPU/memory reflect the filtered output.
306        assert_eq!(cost.cpu, 2_500.0);
307        assert_eq!(cost.memory, 2_500.0);
308    }
309
310    #[test]
311    fn join_sums_children_and_adds_pair_cost() {
312        let est = estimator();
313        let left = Cost::new(100.0, 200.0, 50.0);
314        let right = Cost::new(10.0, 20.0, 5.0);
315        let joined = est.estimate_join(left, right, 1_000);
316        assert_eq!(joined.cpu, 100.0 + 10.0 + 1_000.0 * JOIN_CPU_COST_PER_PAIR);
317        assert_eq!(joined.io, 220.0);
318        assert_eq!(joined.memory, 50.0 + 5.0 + 1_000.0);
319    }
320
321    #[test]
322    fn sort_cost_grows_super_linearly() {
323        let est = estimator();
324        let small = est.estimate_sort(10);
325        let large = est.estimate_sort(1_000);
326        // n log2 n: 10 * ~3.32 vs 1000 * ~9.97.
327        assert!((small.cpu - 10.0 * 10.0_f64.log2()).abs() < 1e-6);
328        assert!((large.cpu - 1_000.0 * 1_000.0_f64.log2()).abs() < 1e-6);
329        assert!(large.cpu / large.memory > small.cpu / small.memory);
330    }
331
332    #[test]
333    fn sort_of_single_row_is_linear_floor() {
334        let est = estimator();
335        let one = est.estimate_sort(1);
336        assert_eq!(one.cpu, 1.0);
337        assert_eq!(one.memory, 1.0);
338    }
339
340    #[test]
341    fn network_cost_scales_with_rows() {
342        let est = estimator();
343        let cost = est.estimate_network(200);
344        assert_eq!(cost.cpu, 200.0 * NETWORK_COST_PER_ROW);
345    }
346}