Skip to main content

datafusion_datasource/
statistics.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Use statistics to optimize physical planning.
19//!
20//! Currently, this module houses code to sort file groups if they are non-overlapping with
21//! respect to the required sort order. See [`MinMaxStatistics`]
22
23use std::sync::Arc;
24
25use crate::PartitionedFile;
26use crate::file_groups::FileGroup;
27
28use arrow::array::RecordBatch;
29use arrow::compute::SortColumn;
30use arrow::datatypes::SchemaRef;
31use arrow::row::{Row, Rows};
32use datafusion_common::stats::{NdvFallback, Precision};
33use datafusion_common::{
34    DataFusionError, Result, ScalarValue, plan_datafusion_err, plan_err,
35};
36use datafusion_physical_expr::expressions::Column;
37use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
38use datafusion_physical_plan::{ColumnStatistics, Statistics};
39
40use futures::{Stream, StreamExt};
41
42/// A normalized representation of file min/max statistics that allows for efficient sorting & comparison.
43/// The min/max values are ordered by [`Self::sort_order`].
44/// Furthermore, any columns that are reversed in the sort order have their min/max values swapped.
45pub(crate) struct MinMaxStatistics {
46    min_by_sort_order: Rows,
47    max_by_sort_order: Rows,
48    sort_order: LexOrdering,
49}
50
51impl MinMaxStatistics {
52    /// Sort order used to sort the statistics
53    #[expect(unused)]
54    pub fn sort_order(&self) -> &LexOrdering {
55        &self.sort_order
56    }
57
58    /// Min value at index
59    #[expect(unused)]
60    pub fn min(&'_ self, idx: usize) -> Row<'_> {
61        self.min_by_sort_order.row(idx)
62    }
63
64    /// Max value at index
65    pub fn max(&'_ self, idx: usize) -> Row<'_> {
66        self.max_by_sort_order.row(idx)
67    }
68
69    pub fn new_from_files<'a>(
70        projected_sort_order: &LexOrdering, // Sort order with respect to projected schema
71        projected_schema: &SchemaRef,       // Projected schema
72        projection: Option<&[usize]>, // Indices of projection in full table schema (None = all columns)
73        files: impl IntoIterator<Item = &'a PartitionedFile>,
74    ) -> Result<Self> {
75        let Some(statistics_and_partition_values) = files
76            .into_iter()
77            .map(|file| {
78                file.statistics
79                    .as_ref()
80                    .zip(Some(file.partition_values.as_slice()))
81            })
82            .collect::<Option<Vec<_>>>()
83        else {
84            return plan_err!("Parquet file missing statistics");
85        };
86
87        // Helper function to get min/max statistics for a given column of projected_schema
88        let get_min_max = |i: usize| -> Result<(Vec<ScalarValue>, Vec<ScalarValue>)> {
89            Ok(statistics_and_partition_values
90                .iter()
91                .map(|(s, pv)| {
92                    if i < s.column_statistics.len() {
93                        s.column_statistics[i]
94                            .min_value
95                            .get_value()
96                            .cloned()
97                            .zip(s.column_statistics[i].max_value.get_value().cloned())
98                            .ok_or_else(|| plan_datafusion_err!("statistics not found"))
99                    } else {
100                        if let Some(partition_value) =
101                            pv.get(i - s.column_statistics.len())
102                        {
103                            Ok((partition_value.clone(), partition_value.clone()))
104                        } else {
105                            Err(plan_datafusion_err!(
106                                "statistics not found for partition, expected at most {}",
107                                s.column_statistics.len()
108                            ))
109                        }
110                    }
111                })
112                .collect::<Result<Vec<_>>>()?
113                .into_iter()
114                .unzip())
115        };
116
117        let Some(sort_columns) =
118            sort_columns_from_physical_sort_exprs(projected_sort_order)
119        else {
120            return plan_err!("sort expression must be on column");
121        };
122
123        // Project the schema & sort order down to just the relevant columns
124        let min_max_schema = Arc::new(
125            projected_schema
126                .project(&(sort_columns.iter().map(|c| c.index()).collect::<Vec<_>>()))?,
127        );
128
129        let min_max_sort_order = projected_sort_order
130            .iter()
131            .zip(sort_columns.iter())
132            .enumerate()
133            .map(|(idx, (sort_expr, col))| {
134                let expr = Arc::new(Column::new(col.name(), idx));
135                PhysicalSortExpr::new(expr, sort_expr.options)
136            });
137        // Safe to `unwrap` as we know that sort columns are non-empty:
138        let min_max_sort_order = LexOrdering::new(min_max_sort_order).unwrap();
139
140        let (min_values, max_values): (Vec<_>, Vec<_>) = sort_columns
141            .iter()
142            .map(|c| {
143                // Reverse the projection to get the index of the column in the full statistics
144                // The file statistics contains _every_ column , but the sort column's index()
145                // refers to the index in projected_schema
146                let i = projection
147                    .map(|p| p[c.index()])
148                    .unwrap_or_else(|| c.index());
149
150                let (min, max) = get_min_max(i).map_err(|e| {
151                    e.context(format!("get min/max for column: '{}'", c.name()))
152                })?;
153                Ok((
154                    ScalarValue::iter_to_array(min)?,
155                    ScalarValue::iter_to_array(max)?,
156                ))
157            })
158            .collect::<Result<Vec<_>>>()
159            .map_err(|e| e.context("collect min/max values"))?
160            .into_iter()
161            .unzip();
162
163        let min_batch = RecordBatch::try_new(Arc::clone(&min_max_schema), min_values)
164            .map_err(|e| {
165                DataFusionError::ArrowError(
166                    Box::new(e),
167                    Some("\ncreate min batch".to_string()),
168                )
169            })?;
170        let max_batch = RecordBatch::try_new(Arc::clone(&min_max_schema), max_values)
171            .map_err(|e| {
172                DataFusionError::ArrowError(
173                    Box::new(e),
174                    Some("\ncreate max batch".to_string()),
175                )
176            })?;
177
178        Self::new(&min_max_sort_order, &min_max_schema, min_batch, max_batch)
179    }
180
181    #[expect(clippy::needless_pass_by_value)]
182    pub fn new(
183        sort_order: &LexOrdering,
184        schema: &SchemaRef,
185        min_values: RecordBatch,
186        max_values: RecordBatch,
187    ) -> Result<Self> {
188        use arrow::row::*;
189
190        let sort_fields = sort_order
191            .iter()
192            .map(|expr| {
193                expr.expr
194                    .data_type(schema)
195                    .map(|data_type| SortField::new_with_options(data_type, expr.options))
196            })
197            .collect::<Result<Vec<_>>>()
198            .map_err(|e| e.context("create sort fields"))?;
199        let converter = RowConverter::new(sort_fields)?;
200
201        let Some(sort_columns) = sort_columns_from_physical_sort_exprs(sort_order) else {
202            return plan_err!("sort expression must be on column");
203        };
204
205        // swap min/max if they're reversed in the ordering
206        let (new_min_cols, new_max_cols): (Vec<_>, Vec<_>) = sort_order
207            .iter()
208            .zip(sort_columns.iter().copied())
209            .map(|(sort_expr, column)| {
210                let maxes = max_values.column_by_name(column.name());
211                let mins = min_values.column_by_name(column.name());
212                let opt_value = if sort_expr.options.descending {
213                    maxes.zip(mins)
214                } else {
215                    mins.zip(maxes)
216                };
217                opt_value.ok_or_else(|| {
218                    plan_datafusion_err!(
219                        "missing column in MinMaxStatistics::new: '{}'",
220                        column.name()
221                    )
222                })
223            })
224            .collect::<Result<Vec<_>>>()?
225            .into_iter()
226            .unzip();
227
228        let [min, max] = [new_min_cols, new_max_cols].map(|cols| {
229            let values = RecordBatch::try_new(
230                min_values.schema(),
231                cols.into_iter().cloned().collect(),
232            )?;
233            let sorting_columns = sort_order
234                .iter()
235                .zip(sort_columns.iter().copied())
236                .map(|(sort_expr, column)| {
237                    let schema = values.schema();
238                    let idx = schema.index_of(column.name())?;
239
240                    Ok(SortColumn {
241                        values: Arc::clone(values.column(idx)),
242                        options: Some(sort_expr.options),
243                    })
244                })
245                .collect::<Result<Vec<_>>>()
246                .map_err(|e| e.context("create sorting columns"))?;
247            converter
248                .convert_columns(
249                    &sorting_columns
250                        .into_iter()
251                        .map(|c| c.values)
252                        .collect::<Vec<_>>(),
253                )
254                .map_err(|e| {
255                    DataFusionError::ArrowError(
256                        Box::new(e),
257                        Some("convert columns".to_string()),
258                    )
259                })
260        });
261
262        Ok(Self {
263            min_by_sort_order: min.map_err(|e| e.context("build min rows"))?,
264            max_by_sort_order: max.map_err(|e| e.context("build max rows"))?,
265            sort_order: sort_order.clone(),
266        })
267    }
268
269    /// Return a sorted list of the min statistics together with the original indices
270    pub fn min_values_sorted(&self) -> Vec<(usize, Row<'_>)> {
271        let mut sort: Vec<_> = self.min_by_sort_order.iter().enumerate().collect();
272        sort.sort_unstable_by_key(|(_, row)| *row);
273        sort
274    }
275
276    /// Check if the min/max statistics are in order and non-overlapping
277    /// (or touching at boundaries)
278    pub fn is_sorted(&self) -> bool {
279        self.max_by_sort_order
280            .iter()
281            .zip(self.min_by_sort_order.iter().skip(1))
282            .all(|(max, next_min)| max <= next_min)
283    }
284}
285
286fn sort_columns_from_physical_sort_exprs(
287    sort_order: &LexOrdering,
288) -> Option<Vec<&Column>> {
289    sort_order
290        .iter()
291        .map(|expr| expr.expr.downcast_ref::<Column>())
292        .collect()
293}
294
295fn seed_summary_statistics(summary_statistics: &mut Statistics, file_stats: &Statistics) {
296    summary_statistics.num_rows = file_stats.num_rows;
297    summary_statistics.total_byte_size = file_stats.total_byte_size;
298
299    for (summary_col_stats, file_col_stats) in summary_statistics
300        .column_statistics
301        .iter_mut()
302        .zip(file_stats.column_statistics.iter())
303    {
304        summary_col_stats.null_count = file_col_stats.null_count;
305        summary_col_stats.max_value = file_col_stats.max_value.clone();
306        summary_col_stats.min_value = file_col_stats.min_value.clone();
307        summary_col_stats.sum_value = file_col_stats.sum_value.cast_to_sum_type();
308        summary_col_stats.byte_size = file_col_stats.byte_size;
309    }
310}
311
312fn merge_summary_statistics(
313    summary_statistics: &mut Statistics,
314    file_stats: &Statistics,
315) {
316    summary_statistics.num_rows = summary_statistics.num_rows.add(&file_stats.num_rows);
317    summary_statistics.total_byte_size = summary_statistics
318        .total_byte_size
319        .add(&file_stats.total_byte_size);
320
321    for (summary_col_stats, file_col_stats) in summary_statistics
322        .column_statistics
323        .iter_mut()
324        .zip(file_stats.column_statistics.iter())
325    {
326        let ColumnStatistics {
327            null_count: file_nc,
328            max_value: file_max,
329            min_value: file_min,
330            sum_value: file_sum,
331            distinct_count: _,
332            byte_size: file_sbs,
333        } = file_col_stats;
334
335        summary_col_stats.null_count = summary_col_stats.null_count.add(file_nc);
336        summary_col_stats.max_value = summary_col_stats.max_value.max(file_max);
337        summary_col_stats.min_value = summary_col_stats.min_value.min(file_min);
338        summary_col_stats.sum_value = summary_col_stats.sum_value.add_for_sum(file_sum);
339        summary_col_stats.byte_size = summary_col_stats.byte_size.add(file_sbs);
340    }
341}
342
343fn seed_first_file_statistics(
344    limit_num_rows: &mut Precision<usize>,
345    summary_statistics: &mut Statistics,
346    file_stats: &Statistics,
347    collect_stats: bool,
348) {
349    *limit_num_rows = file_stats.num_rows;
350
351    if collect_stats {
352        seed_summary_statistics(summary_statistics, file_stats);
353    }
354}
355
356fn merge_file_statistics(
357    limit_num_rows: &mut Precision<usize>,
358    summary_statistics: &mut Statistics,
359    file_stats: &Statistics,
360    collect_stats: bool,
361) {
362    *limit_num_rows = limit_num_rows.add(&file_stats.num_rows);
363
364    if collect_stats {
365        merge_summary_statistics(summary_statistics, file_stats);
366    }
367}
368
369/// Get all files as well as the file level summary statistics (no statistic for partition columns).
370/// If the optional `limit` is provided, includes only sufficient files. Needed to read up to
371/// `limit` number of rows. `collect_stats` is passed down from the configuration parameter on
372/// `ListingTable`. If it is false we only construct bare statistics and skip a potentially expensive
373///  call to `multiunzip` for constructing file level summary statistics.
374#[deprecated(
375    since = "47.0.0",
376    note = "Please use `get_files_with_limit` and  `compute_all_files_statistics` instead"
377)]
378#[cfg_attr(not(test), expect(unused))]
379pub async fn get_statistics_with_limit(
380    all_files: impl Stream<Item = Result<(PartitionedFile, Arc<Statistics>)>>,
381    file_schema: SchemaRef,
382    limit: Option<usize>,
383    collect_stats: bool,
384) -> Result<(FileGroup, Statistics)> {
385    let mut result_files = FileGroup::default();
386    // These statistics can be calculated as long as at least one file provides
387    // useful information. If none of the files provides any information, then
388    // they will end up having `Precision::Absent` values. Throughout calculations,
389    // missing values will be imputed as:
390    // - zero for summations, and
391    // - neutral element for extreme points.
392    let size = file_schema.fields().len();
393    let mut summary_statistics = Statistics {
394        num_rows: Precision::Absent,
395        total_byte_size: Precision::Absent,
396        column_statistics: vec![ColumnStatistics::default(); size],
397    };
398    // Keep limit pruning separate from the returned summary so `collect_stats=false`
399    // can still stop early using known file row counts.
400    let mut limit_num_rows = Precision::<usize>::Absent;
401
402    // Fusing the stream allows us to call next safely even once it is finished.
403    let mut all_files = Box::pin(all_files.fuse());
404
405    if let Some(first_file) = all_files.next().await {
406        let (mut file, file_stats) = first_file?;
407        file.statistics = Some(Arc::clone(&file_stats));
408        result_files.push(file);
409
410        seed_first_file_statistics(
411            &mut limit_num_rows,
412            &mut summary_statistics,
413            &file_stats,
414            collect_stats,
415        );
416
417        // If the number of rows exceeds the limit, we can stop processing
418        // files. This only applies when we know the number of rows. It also
419        // currently ignores tables that have no statistics regarding the
420        // number of rows.
421        let conservative_num_rows = match limit_num_rows {
422            Precision::Exact(nr) => nr,
423            _ => usize::MIN,
424        };
425        if conservative_num_rows <= limit.unwrap_or(usize::MAX) {
426            while let Some(current) = all_files.next().await {
427                let (mut file, file_stats) = current?;
428                file.statistics = Some(Arc::clone(&file_stats));
429                result_files.push(file);
430                merge_file_statistics(
431                    &mut limit_num_rows,
432                    &mut summary_statistics,
433                    &file_stats,
434                    collect_stats,
435                );
436
437                // If the number of rows exceeds the limit, we can stop processing
438                // files. This only applies when we know the number of rows. It also
439                // currently ignores tables that have no statistics regarding the
440                // number of rows.
441                if limit_num_rows.get_value().unwrap_or(&usize::MIN)
442                    > &limit.unwrap_or(usize::MAX)
443                {
444                    break;
445                }
446            }
447        }
448    };
449
450    let mut statistics = summary_statistics;
451    if all_files.next().await.is_some() {
452        // If we still have files in the stream, it means that the limit kicked
453        // in, and the statistic could have been different had we processed the
454        // files in a different order.
455        statistics = statistics.to_inexact()
456    }
457
458    Ok((result_files, statistics))
459}
460
461/// Computes the summary statistics for a group of files(`FileGroup` level's statistics).
462///
463/// This function combines statistics from all files in the file group to create
464/// summary statistics. It handles the following aspects:
465/// - Merges row counts and byte sizes across files
466/// - Computes column-level statistics like min/max values
467/// - Maintains appropriate precision information (exact, inexact, absent)
468///
469/// # Parameters
470/// * `file_group` - The group of files to process
471/// * `file_schema` - Schema of the files
472/// * `collect_stats` - Whether to collect statistics (if false, returns original file group)
473///
474/// # Returns
475/// A new file group with summary statistics attached
476#[expect(clippy::needless_pass_by_value)]
477pub fn compute_file_group_statistics(
478    file_group: FileGroup,
479    file_schema: SchemaRef,
480    collect_stats: bool,
481) -> Result<FileGroup> {
482    if !collect_stats {
483        return Ok(file_group);
484    }
485
486    let file_group_stats = file_group.iter().filter_map(|file| {
487        let stats = file.statistics.as_ref()?;
488        Some(stats.as_ref())
489    });
490    let statistics = Statistics::try_merge_iter_with_ndv_fallback(
491        file_group_stats,
492        &file_schema,
493        NdvFallback::Max,
494    )?;
495
496    Ok(file_group.with_statistics(Arc::new(statistics)))
497}
498
499/// Computes statistics for all files across multiple file groups.
500///
501/// This function:
502/// 1. Computes statistics for each individual file group
503/// 2. Summary statistics across all file groups
504/// 3. Optionally marks statistics as inexact
505///
506/// # Parameters
507/// * `file_groups` - Vector of file groups to process
508/// * `table_schema` - Schema of the table
509/// * `collect_stats` - Whether to collect statistics
510/// * `inexact_stats` - Whether to mark the resulting statistics as inexact
511///
512/// # Returns
513/// A tuple containing:
514/// * The processed file groups with their individual statistics attached
515/// * The summary statistics across all file groups, aka all files summary statistics
516#[expect(clippy::needless_pass_by_value)]
517pub fn compute_all_files_statistics(
518    file_groups: Vec<FileGroup>,
519    table_schema: SchemaRef,
520    collect_stats: bool,
521    inexact_stats: bool,
522) -> Result<(Vec<FileGroup>, Statistics)> {
523    let file_groups_with_stats = file_groups
524        .into_iter()
525        .map(|file_group| {
526            compute_file_group_statistics(
527                file_group,
528                Arc::clone(&table_schema),
529                collect_stats,
530            )
531        })
532        .collect::<Result<Vec<_>>>()?;
533
534    // Then summary statistics across all file groups
535    let file_groups_statistics = file_groups_with_stats
536        .iter()
537        .filter_map(|file_group| file_group.file_statistics(None));
538
539    let mut statistics = Statistics::try_merge_iter_with_ndv_fallback(
540        file_groups_statistics,
541        &table_schema,
542        NdvFallback::Max,
543    )?;
544
545    if inexact_stats {
546        statistics = statistics.to_inexact()
547    }
548
549    Ok((file_groups_with_stats, statistics))
550}
551
552#[cfg(test)]
553mod tests {
554    use super::*;
555    use crate::PartitionedFile;
556    use crate::file_groups::FileGroup;
557    use arrow::datatypes::{DataType, Field, Schema};
558    use futures::stream;
559
560    fn file_stats(sum: u32) -> Statistics {
561        Statistics {
562            num_rows: Precision::Exact(1),
563            total_byte_size: Precision::Exact(4),
564            column_statistics: vec![ColumnStatistics {
565                null_count: Precision::Exact(0),
566                max_value: Precision::Exact(ScalarValue::UInt32(Some(sum))),
567                min_value: Precision::Exact(ScalarValue::UInt32(Some(sum))),
568                sum_value: Precision::Exact(ScalarValue::UInt32(Some(sum))),
569                distinct_count: Precision::Exact(1),
570                byte_size: Precision::Exact(4),
571            }],
572        }
573    }
574
575    fn test_schema() -> SchemaRef {
576        Arc::new(Schema::new(vec![Field::new("a", DataType::Int64, true)]))
577    }
578
579    fn make_file_stats(
580        num_rows: usize,
581        total_byte_size: usize,
582        col_stats: ColumnStatistics,
583    ) -> Arc<Statistics> {
584        Arc::new(Statistics {
585            num_rows: Precision::Exact(num_rows),
586            total_byte_size: Precision::Exact(total_byte_size),
587            column_statistics: vec![col_stats],
588        })
589    }
590
591    fn rich_col_stats(
592        null_count: usize,
593        min: i64,
594        max: i64,
595        sum: i64,
596        byte_size: usize,
597    ) -> ColumnStatistics {
598        ColumnStatistics {
599            null_count: Precision::Exact(null_count),
600            max_value: Precision::Exact(ScalarValue::Int64(Some(max))),
601            min_value: Precision::Exact(ScalarValue::Int64(Some(min))),
602            distinct_count: Precision::Absent,
603            sum_value: Precision::Exact(ScalarValue::Int64(Some(sum))),
604            byte_size: Precision::Exact(byte_size),
605        }
606    }
607
608    fn utf8_file_stats(ndv: usize, min: &str, max: &str) -> Statistics {
609        Statistics {
610            num_rows: Precision::Exact(1),
611            total_byte_size: Precision::Exact(16),
612            column_statistics: vec![ColumnStatistics {
613                null_count: Precision::Exact(0),
614                max_value: Precision::Exact(ScalarValue::Utf8(Some(max.to_string()))),
615                min_value: Precision::Exact(ScalarValue::Utf8(Some(min.to_string()))),
616                sum_value: Precision::Absent,
617                distinct_count: Precision::Exact(ndv),
618                byte_size: Precision::Exact(16),
619            }],
620        }
621    }
622
623    fn file_with_stats(path: &str, stats: Statistics) -> PartitionedFile {
624        PartitionedFile::new(path, 1).with_statistics(Arc::new(stats))
625    }
626    #[tokio::test]
627    #[expect(deprecated)]
628    async fn test_get_statistics_with_limit_casts_first_file_sum_to_sum_type()
629    -> Result<()> {
630        let schema =
631            Arc::new(Schema::new(vec![Field::new("c1", DataType::UInt32, true)]));
632
633        let files = stream::iter(vec![Ok((
634            PartitionedFile::new("f1.parquet", 1),
635            Arc::new(file_stats(100)),
636        ))]);
637
638        let (_group, stats) =
639            get_statistics_with_limit(files, schema, None, true).await?;
640
641        assert_eq!(
642            stats.column_statistics[0].sum_value,
643            Precision::Exact(ScalarValue::UInt64(Some(100)))
644        );
645
646        Ok(())
647    }
648
649    #[tokio::test]
650    #[expect(deprecated)]
651    async fn test_get_statistics_with_limit_merges_sum_with_unsigned_widening()
652    -> Result<()> {
653        let schema =
654            Arc::new(Schema::new(vec![Field::new("c1", DataType::UInt32, true)]));
655
656        let files = stream::iter(vec![
657            Ok((
658                PartitionedFile::new("f1.parquet", 1),
659                Arc::new(file_stats(100)),
660            )),
661            Ok((
662                PartitionedFile::new("f2.parquet", 1),
663                Arc::new(file_stats(200)),
664            )),
665        ]);
666
667        let (_group, stats) =
668            get_statistics_with_limit(files, schema, None, true).await?;
669
670        assert_eq!(
671            stats.column_statistics[0].sum_value,
672            Precision::Exact(ScalarValue::UInt64(Some(300)))
673        );
674
675        Ok(())
676    }
677
678    #[tokio::test]
679    #[expect(deprecated)]
680    async fn get_statistics_with_limit_collect_stats_false_returns_bare_statistics() {
681        let all_files = stream::iter(vec![
682            Ok((
683                PartitionedFile::new("first.parquet", 10),
684                make_file_stats(0, 0, rich_col_stats(1, 1, 9, 15, 64)),
685            )),
686            Ok((
687                PartitionedFile::new("second.parquet", 20),
688                make_file_stats(10, 100, rich_col_stats(2, 10, 99, 300, 128)),
689            )),
690        ]);
691
692        let (_files, statistics) =
693            get_statistics_with_limit(all_files, test_schema(), None, false)
694                .await
695                .unwrap();
696
697        assert_eq!(statistics.num_rows, Precision::Absent);
698        assert_eq!(statistics.total_byte_size, Precision::Absent);
699        assert_eq!(statistics.column_statistics.len(), 1);
700        assert_eq!(
701            statistics.column_statistics[0].null_count,
702            Precision::Absent
703        );
704        assert_eq!(statistics.column_statistics[0].max_value, Precision::Absent);
705        assert_eq!(statistics.column_statistics[0].min_value, Precision::Absent);
706        assert_eq!(statistics.column_statistics[0].sum_value, Precision::Absent);
707        assert_eq!(statistics.column_statistics[0].byte_size, Precision::Absent);
708    }
709
710    #[tokio::test]
711    #[expect(deprecated)]
712    async fn get_statistics_with_limit_collect_stats_false_uses_row_counts_for_limit() {
713        let all_files = stream::iter(vec![
714            Ok((
715                PartitionedFile::new("first.parquet", 10),
716                make_file_stats(3, 30, rich_col_stats(1, 1, 9, 15, 64)),
717            )),
718            Ok((
719                PartitionedFile::new("second.parquet", 20),
720                make_file_stats(3, 30, rich_col_stats(2, 10, 99, 300, 128)),
721            )),
722            Ok((
723                PartitionedFile::new("third.parquet", 30),
724                make_file_stats(3, 30, rich_col_stats(0, 100, 199, 450, 256)),
725            )),
726        ]);
727
728        let (files, statistics) =
729            get_statistics_with_limit(all_files, test_schema(), Some(4), false)
730                .await
731                .unwrap();
732
733        assert_eq!(files.len(), 2);
734        assert_eq!(statistics.num_rows, Precision::Absent);
735        assert_eq!(statistics.total_byte_size, Precision::Absent);
736    }
737
738    #[tokio::test]
739    #[expect(deprecated)]
740    async fn get_statistics_with_limit_collect_stats_true_aggregates_statistics() {
741        let all_files = stream::iter(vec![
742            Ok((
743                PartitionedFile::new("first.parquet", 10),
744                make_file_stats(5, 50, rich_col_stats(1, 1, 9, 15, 64)),
745            )),
746            Ok((
747                PartitionedFile::new("second.parquet", 20),
748                make_file_stats(10, 100, rich_col_stats(2, 10, 99, 300, 128)),
749            )),
750        ]);
751
752        let (_files, statistics) =
753            get_statistics_with_limit(all_files, test_schema(), None, true)
754                .await
755                .unwrap();
756
757        assert_eq!(statistics.num_rows, Precision::Exact(15));
758        assert_eq!(statistics.total_byte_size, Precision::Exact(150));
759        assert_eq!(
760            statistics.column_statistics[0].null_count,
761            Precision::Exact(3)
762        );
763        assert_eq!(
764            statistics.column_statistics[0].min_value,
765            Precision::Exact(ScalarValue::Int64(Some(1)))
766        );
767        assert_eq!(
768            statistics.column_statistics[0].max_value,
769            Precision::Exact(ScalarValue::Int64(Some(99)))
770        );
771        assert_eq!(
772            statistics.column_statistics[0].sum_value,
773            Precision::Exact(ScalarValue::Int64(Some(315)))
774        );
775        assert_eq!(
776            statistics.column_statistics[0].byte_size,
777            Precision::Exact(192)
778        );
779    }
780
781    #[tokio::test]
782    #[expect(deprecated)]
783    async fn get_statistics_with_limit_collect_stats_true_limit_marks_inexact() {
784        let all_files = stream::iter(vec![
785            Ok((
786                PartitionedFile::new("first.parquet", 10),
787                make_file_stats(5, 50, rich_col_stats(0, 1, 5, 15, 64)),
788            )),
789            Ok((
790                PartitionedFile::new("second.parquet", 20),
791                make_file_stats(5, 50, rich_col_stats(1, 6, 10, 40, 64)),
792            )),
793            Ok((
794                PartitionedFile::new("third.parquet", 20),
795                make_file_stats(5, 50, rich_col_stats(2, 11, 15, 65, 64)),
796            )),
797        ]);
798
799        let (files, statistics) =
800            get_statistics_with_limit(all_files, test_schema(), Some(8), true)
801                .await
802                .unwrap();
803
804        assert_eq!(files.len(), 2);
805        assert_eq!(statistics.num_rows, Precision::Inexact(10));
806        assert_eq!(statistics.total_byte_size, Precision::Inexact(100));
807        assert_eq!(
808            statistics.column_statistics[0].min_value,
809            Precision::Inexact(ScalarValue::Int64(Some(1)))
810        );
811        assert_eq!(
812            statistics.column_statistics[0].max_value,
813            Precision::Inexact(ScalarValue::Int64(Some(10)))
814        );
815        assert_eq!(
816            statistics.column_statistics[0].sum_value,
817            Precision::Inexact(ScalarValue::Int64(Some(55)))
818        );
819        assert_eq!(
820            statistics.column_statistics[0].byte_size,
821            Precision::Inexact(128)
822        );
823    }
824
825    #[test]
826    fn test_compute_file_group_statistics_uses_max_ndv_fallback() -> Result<()> {
827        let schema = Arc::new(Schema::new(vec![Field::new("c1", DataType::Utf8, true)]));
828        let file_group = FileGroup::new(vec![
829            file_with_stats("f1.parquet", utf8_file_stats(5, "a", "x")),
830            file_with_stats("f2.parquet", utf8_file_stats(8, "b", "z")),
831        ]);
832
833        let file_group =
834            compute_file_group_statistics(file_group, Arc::clone(&schema), true)?;
835        let stats = file_group.file_statistics(None).unwrap();
836
837        assert_eq!(
838            stats.column_statistics[0].distinct_count,
839            Precision::Inexact(8)
840        );
841        assert_eq!(
842            stats.column_statistics[0].min_value,
843            Precision::Exact(ScalarValue::Utf8(Some("a".to_string())))
844        );
845        assert_eq!(
846            stats.column_statistics[0].max_value,
847            Precision::Exact(ScalarValue::Utf8(Some("z".to_string())))
848        );
849
850        Ok(())
851    }
852
853    #[test]
854    fn test_compute_all_files_statistics_uses_max_ndv_fallback() -> Result<()> {
855        let schema = Arc::new(Schema::new(vec![Field::new("c1", DataType::Utf8, true)]));
856        let file_groups = vec![
857            FileGroup::new(vec![
858                file_with_stats("f1.parquet", utf8_file_stats(5, "a", "x")),
859                file_with_stats("f2.parquet", utf8_file_stats(8, "b", "z")),
860            ]),
861            FileGroup::new(vec![
862                file_with_stats("f3.parquet", utf8_file_stats(3, "c", "w")),
863                file_with_stats("f4.parquet", utf8_file_stats(6, "d", "y")),
864            ]),
865        ];
866
867        let (file_groups, stats) =
868            compute_all_files_statistics(file_groups, schema, true, false)?;
869
870        assert_eq!(
871            file_groups[0]
872                .file_statistics(None)
873                .unwrap()
874                .column_statistics[0]
875                .distinct_count,
876            Precision::Inexact(8)
877        );
878        assert_eq!(
879            file_groups[1]
880                .file_statistics(None)
881                .unwrap()
882                .column_statistics[0]
883                .distinct_count,
884            Precision::Inexact(6)
885        );
886        assert_eq!(
887            stats.column_statistics[0].distinct_count,
888            Precision::Inexact(8)
889        );
890
891        Ok(())
892    }
893
894    #[test]
895    fn min_max_statistics_missing_column_stats_returns_error() {
896        let schema = test_schema();
897        let sort_order =
898            [PhysicalSortExpr::new_default(Arc::new(Column::new("a", 0)))].into();
899        let files = [
900            file_with_stats("f1.parquet", Statistics::default()),
901            file_with_stats("f2.parquet", Statistics::default()),
902        ];
903
904        let err = match MinMaxStatistics::new_from_files(
905            &sort_order,
906            &schema,
907            None,
908            files.iter(),
909        ) {
910            Ok(_) => panic!("expected missing statistics error"),
911            Err(err) => err,
912        };
913
914        assert!(
915            err.to_string()
916                .contains("statistics not found for partition"),
917            "unexpected error: {err:?}"
918        );
919    }
920}