1use 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
25pub const TABLE_SCAN_COST_PER_ROW: f64 = 1.0;
27pub const INDEX_SCAN_COST_PER_ROW: f64 = 0.1;
29pub const JOIN_CPU_COST_PER_PAIR: f64 = 0.01;
31pub const NETWORK_COST_PER_ROW: f64 = 0.5;
33pub const SORT_CPU_COST_PER_ROW: f64 = 1.0;
35pub const SORT_MEMORY_PER_ROW: f64 = 1.0;
37
38#[derive(Debug, Clone, Copy, Default, PartialEq)]
57pub struct Cost {
58 pub cpu: f64,
60 pub io: f64,
62 pub memory: f64,
64}
65
66impl Cost {
67 pub const ZERO: Self = Self {
69 cpu: 0.0,
70 io: 0.0,
71 memory: 0.0,
72 };
73
74 pub fn new(cpu: f64, io: f64, memory: f64) -> Self {
76 Self { cpu, io, memory }
77 }
78
79 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 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#[derive(Debug, Clone)]
125pub struct CostEstimator {
126 cardinality: CardinalityEstimator,
127}
128
129impl CostEstimator {
130 pub fn new(stats_provider: Arc<dyn StatisticsProvider>) -> Self {
132 Self {
133 cardinality: CardinalityEstimator::new(stats_provider),
134 }
135 }
136
137 pub fn with_cardinality(cardinality: CardinalityEstimator) -> Self {
140 Self { cardinality }
141 }
142
143 pub fn cardinality(&self) -> &CardinalityEstimator {
145 &self.cardinality
146 }
147
148 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 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 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 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 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 assert_eq!(cost.io, 10_000.0);
305 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 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}