Skip to main content

micromegas_analytics/lakehouse/
scan_cost.rs

1use super::metadata_cache::MetadataCache;
2use datafusion::{
3    arrow::datatypes::{DataType, Schema},
4    catalog::memory::DataSourceExec,
5    datasource::{
6        listing::PartitionedFile,
7        memory::MemorySourceConfig,
8        physical_plan::{FileScanConfig, FileSource, ParquetSource},
9    },
10    parquet::file::metadata::ParquetMetaData,
11    physical_plan::{ExecutionPlan, empty::EmptyExec, placeholder_row::PlaceholderRowExec},
12};
13use std::collections::HashSet;
14use std::sync::Arc;
15
16/// How trustworthy an estimate is. Ordered best to worst, so the worst contributor is the max.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
18pub enum CostPrecision {
19    /// Every scanned file was sized from a cached parquet footer.
20    Footer,
21    /// At least one file was sized as its share of the file size.
22    FileSizeShare,
23    /// At least one leaf hides its work from the plan, so a flat cost was charged for it.
24    Opaque,
25}
26
27impl CostPrecision {
28    pub fn as_str(&self) -> &'static str {
29        match self {
30            Self::Footer => "footer",
31            Self::FileSizeShare => "file_size_share",
32            Self::Opaque => "opaque",
33        }
34    }
35}
36
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct ScanCostEstimate {
39    /// Estimated compressed bytes the scans will request.
40    pub bytes: u64,
41    /// Sum of `file_size` over the distinct files scanned: exact and unprojected.
42    pub partition_bytes: u64,
43    pub files: u64,
44    /// Files estimated from a cached footer.
45    pub footer_files: u64,
46    /// Leaves whose work is invisible at plan time.
47    pub opaque_nodes: u64,
48    /// Worst precision among contributors. With no contributors it is `Footer`, the best.
49    pub precision: CostPrecision,
50}
51
52impl Default for ScanCostEstimate {
53    fn default() -> Self {
54        Self {
55            bytes: 0,
56            partition_bytes: 0,
57            files: 0,
58            footer_files: 0,
59            opaque_nodes: 0,
60            precision: CostPrecision::Footer,
61        }
62    }
63}
64
65impl ScanCostEstimate {
66    fn degrade(&mut self, precision: CostPrecision) {
67        self.precision = self.precision.max(precision);
68    }
69}
70
71/// The single place footers are looked up, so swapping the cache implementation only touches
72/// this function. It never loads: a miss is costed from the file size instead, because loading
73/// would put object-store I/O in front of the admission gate.
74async fn cached_footer(cache: &MetadataCache, path: &str) -> Option<Arc<ParquetMetaData>> {
75    cache.get(path).await
76}
77
78fn leaf_count(data_type: &DataType) -> u64 {
79    match data_type {
80        DataType::Struct(fields) => fields.iter().map(|f| leaf_count(f.data_type())).sum(),
81        DataType::List(f)
82        | DataType::LargeList(f)
83        | DataType::FixedSizeList(f, _)
84        | DataType::Map(f, _)
85        | DataType::ListView(f)
86        | DataType::LargeListView(f) => leaf_count(f.data_type()),
87        DataType::Union(fields, _) => fields.iter().map(|(_, f)| leaf_count(f.data_type())).sum(),
88        _ => 1,
89    }
90}
91
92fn footer_projected_bytes(footer: &ParquetMetaData, projected_roots: &[usize]) -> u64 {
93    let schema = footer.file_metadata().schema_descr();
94    let mut total = 0_u64;
95    for row_group in footer.row_groups() {
96        for leaf in 0..schema.num_columns() {
97            if projected_roots.contains(&schema.get_column_root_idx(leaf)) {
98                total += row_group.column(leaf).compressed_size().max(0) as u64;
99            }
100        }
101    }
102    total
103}
104
105fn share_projected_bytes(file_size: u64, file_schema: &Schema, projected_roots: &[usize]) -> u64 {
106    let total_leaves: u64 = file_schema
107        .fields()
108        .iter()
109        .map(|f| leaf_count(f.data_type()))
110        .sum();
111    if total_leaves == 0 {
112        return 0;
113    }
114    let projected_leaves: u64 = projected_roots
115        .iter()
116        .filter_map(|i| file_schema.fields().get(*i))
117        .map(|f| leaf_count(f.data_type()))
118        .sum();
119    (file_size as u128 * projected_leaves as u128 / total_leaves as u128) as u64
120}
121
122fn distinct_files(config: &FileScanConfig) -> Vec<&PartitionedFile> {
123    let mut seen = HashSet::new();
124    config
125        .file_groups
126        .iter()
127        .flat_map(|g| g.iter())
128        .filter(|pf| seen.insert(pf.object_meta.location.as_ref()))
129        .collect()
130}
131
132async fn estimate_file_scan(
133    exec: &DataSourceExec,
134    metadata_cache: &MetadataCache,
135    opaque_leaf_cost: u64,
136    out: &mut ScanCostEstimate,
137) {
138    if let Some((config, source)) = exec.downcast_to_file_source::<ParquetSource>() {
139        let file_schema = config.file_schema();
140        let n_fields = file_schema.fields().len();
141        let projected_roots: Vec<usize> = match FileSource::projection(source) {
142            Some(p) => p
143                .column_indices()
144                .into_iter()
145                .filter(|i| *i < n_fields)
146                .collect(),
147            None => (0..n_fields).collect(),
148        };
149        for pf in distinct_files(config) {
150            let file_size = pf.object_meta.size;
151            out.files += 1;
152            out.partition_bytes += file_size;
153            match cached_footer(metadata_cache, pf.object_meta.location.as_ref()).await {
154                Some(footer) => {
155                    out.footer_files += 1;
156                    out.bytes += footer_projected_bytes(&footer, &projected_roots);
157                }
158                None => {
159                    out.bytes += share_projected_bytes(file_size, file_schema, &projected_roots);
160                    out.degrade(CostPrecision::FileSizeShare);
161                }
162            }
163        }
164    } else if let Some(config) = exec.data_source().downcast_ref::<FileScanConfig>() {
165        // Non-parquet (static CSV/JSON tables): no footer or column-share path.
166        for pf in distinct_files(config) {
167            out.files += 1;
168            out.bytes += pf.object_meta.size;
169            out.partition_bytes += pf.object_meta.size;
170            out.degrade(CostPrecision::FileSizeShare);
171        }
172    } else {
173        out.bytes += opaque_leaf_cost;
174        out.opaque_nodes += 1;
175        out.degrade(CostPrecision::Opaque);
176    }
177}
178
179async fn visit(
180    plan: &Arc<dyn ExecutionPlan>,
181    metadata_cache: &MetadataCache,
182    opaque_leaf_cost: u64,
183    out: &mut ScanCostEstimate,
184) {
185    if let Some(exec) = plan.downcast_ref::<DataSourceExec>() {
186        if exec
187            .data_source()
188            .downcast_ref::<MemorySourceConfig>()
189            .is_some()
190        {
191            return;
192        }
193        estimate_file_scan(exec, metadata_cache, opaque_leaf_cost, out).await;
194        return;
195    }
196    if plan.is::<EmptyExec>() || plan.is::<PlaceholderRowExec>() {
197        return;
198    }
199    let children = plan.children();
200    if children.is_empty() {
201        out.bytes += opaque_leaf_cost;
202        out.opaque_nodes += 1;
203        out.degrade(CostPrecision::Opaque);
204        return;
205    }
206    for child in children {
207        Box::pin(visit(child, metadata_cache, opaque_leaf_cost, out)).await;
208    }
209}
210
211/// Estimates the compressed parquet bytes `plan` will scan, from the scan nodes alone. Never
212/// fails: anything it cannot interpret is costed as an opaque leaf. Joins, aggregates and sorts
213/// add nothing; their memory is not predictable from the plan and the pool reservation stays
214/// the authority for it.
215pub async fn estimate_scan_cost(
216    plan: &Arc<dyn ExecutionPlan>,
217    metadata_cache: &MetadataCache,
218    opaque_leaf_cost: u64,
219) -> ScanCostEstimate {
220    let mut estimate = ScanCostEstimate::default();
221    visit(plan, metadata_cache, opaque_leaf_cost, &mut estimate).await;
222    estimate
223}