Skip to main content

datafusion_common/
pruning.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use arrow::array::{Array, NullArray, UInt64Array};
6use arrow::array::{ArrayRef, BooleanArray};
7use arrow::datatypes::{FieldRef, Schema, SchemaRef};
8use std::collections::HashSet;
9use std::sync::Arc;
10
11use crate::error::DataFusionError;
12use crate::stats::Precision;
13use crate::{Column, Statistics};
14use crate::{ColumnStatistics, ScalarValue};
15
16/// A source of runtime statistical information to [`PruningPredicate`]s.
17///
18/// # Supported Information
19///
20/// 1. Minimum and maximum values for columns
21///
22/// 2. Null counts and row counts for columns
23///
24/// 3. Whether the values in a column are contained in a set of literals
25///
26/// # Vectorized Interface
27///
28/// Information for containers / files are returned as Arrow [`ArrayRef`], so
29/// the evaluation happens once on a single `RecordBatch`, which amortizes the
30/// overhead of evaluating the predicate. This is important when pruning 1000s
31/// of containers which often happens in analytic systems that have 1000s of
32/// potential files to consider.
33///
34/// For example, for the following three files with a single column `a`:
35/// ```text
36/// file1: column a: min=5, max=10
37/// file2: column a: No stats
38/// file2: column a: min=20, max=30
39/// ```
40///
41/// PruningStatistics would return:
42///
43/// ```text
44/// min_values("a") -> Some([5, Null, 20])
45/// max_values("a") -> Some([10, Null, 30])
46/// min_values("X") -> None
47/// ```
48///
49/// [`PruningPredicate`]: https://docs.rs/datafusion/latest/datafusion/physical_optimizer/pruning/struct.PruningPredicate.html
50pub trait PruningStatistics {
51    /// Return the minimum values for the named column, if known.
52    ///
53    /// If the minimum value for a particular container is not known, the
54    /// returned array should have `null` in that row. If the minimum value is
55    /// not known for any row, return `None`.
56    ///
57    /// Each non-null entry must be a conservative lower bound for all non-null
58    /// values in its container, using Arrow's comparison order for the column
59    /// type. For strings, this is unsigned lexicographic UTF-8 byte order.
60    /// Bounds that cannot satisfy this contract must be reported as unknown.
61    /// Pruning relies on providers to uphold this contract; it does not validate
62    /// the ordering or bound guarantees of arbitrary statistics sources.
63    ///
64    /// Note: the returned array must contain [`Self::num_containers`] rows
65    fn min_values(&self, column: &Column) -> Option<ArrayRef>;
66
67    /// Return the maximum values for the named column, if known.
68    ///
69    /// See [`Self::min_values`] for when to return `None` and null values.
70    ///
71    /// Each non-null entry must be a conservative upper bound for all non-null
72    /// values in its container, using the comparison order described in
73    /// [`Self::min_values`].
74    ///
75    /// Note: the returned array must contain [`Self::num_containers`] rows
76    fn max_values(&self, column: &Column) -> Option<ArrayRef>;
77
78    /// Return the number of containers (e.g. Row Groups) being pruned with
79    /// these statistics.
80    ///
81    /// This value corresponds to the size of the [`ArrayRef`] returned by
82    /// [`Self::min_values`], [`Self::max_values`], [`Self::null_counts`],
83    /// and [`Self::row_counts`].
84    fn num_containers(&self) -> usize;
85
86    /// Return the number of null values for the named column as an
87    /// [`UInt64Array`]
88    ///
89    /// See [`Self::min_values`] for when to return `None` and null values.
90    ///
91    /// Note: the returned array must contain [`Self::num_containers`] rows
92    ///
93    /// [`UInt64Array`]: arrow::array::UInt64Array
94    fn null_counts(&self, column: &Column) -> Option<ArrayRef>;
95
96    /// Return the number of rows in each container as an [`UInt64Array`].
97    ///
98    /// Row counts are container-level (not column-specific) — the value
99    /// is the same regardless of which column is being considered.
100    ///
101    /// See [`Self::min_values`] for when to return `None` and null values.
102    ///
103    /// Note: the returned array must contain [`Self::num_containers`] rows
104    ///
105    /// [`UInt64Array`]: arrow::array::UInt64Array
106    fn row_counts(&self) -> Option<ArrayRef>;
107
108    /// Returns [`BooleanArray`] where each row represents information known
109    /// about specific literal `values` in a column.
110    ///
111    /// For example, Parquet Bloom Filters implement this API to communicate
112    /// that `values` are known not to be present in a Row Group.
113    ///
114    /// The returned array has one row for each container, with the following
115    /// meanings:
116    /// * `true` if the values in `column`  ONLY contain values from `values`
117    /// * `false` if the values in `column` are NOT ANY of `values`
118    /// * `null` if the neither of the above holds or is unknown.
119    ///
120    /// If these statistics can not determine column membership for any
121    /// container, return `None` (the default).
122    ///
123    /// Note: the returned array must contain [`Self::num_containers`] rows
124    #[allow(clippy::allow_attributes, clippy::mutable_key_type)] // ScalarValue has interior mutability but is intentionally used as hash key
125    fn contained(
126        &self,
127        column: &Column,
128        values: &HashSet<ScalarValue>,
129    ) -> Option<BooleanArray>;
130}
131
132/// Prune files based on their partition values.
133///
134/// This is used both at planning time and execution time to prune
135/// files based on their partition values.
136/// This feeds into [`CompositePruningStatistics`] to allow pruning
137/// with filters that depend both on partition columns and data columns
138/// (e.g. `WHERE partition_col = data_col`).
139#[deprecated(
140    since = "52.0.0",
141    note = "This struct is no longer used internally. Use `replace_columns_with_literals` from `datafusion-physical-expr-adapter` to substitute partition column values before pruning. It will be removed in 58.0.0 or 6 months after 52.0.0 is released, whichever comes first."
142)]
143#[derive(Clone)]
144pub struct PartitionPruningStatistics {
145    /// Values for each column for each container.
146    ///
147    /// The outer vectors represent the columns while the inner vectors
148    /// represent the containers. The order must match the order of the
149    /// partition columns in [`PartitionPruningStatistics::partition_schema`].
150    partition_values: Vec<ArrayRef>,
151    /// The number of containers.
152    ///
153    /// Stored since the partition values are column-major and if
154    /// there are no columns we wouldn't know the number of containers.
155    num_containers: usize,
156    /// The schema of the partition columns.
157    ///
158    /// This must **not** be the schema of the entire file or table: it must
159    /// only be the schema of the partition columns, in the same order as the
160    /// values in [`PartitionPruningStatistics::partition_values`].
161    partition_schema: SchemaRef,
162}
163
164#[expect(deprecated)]
165impl PartitionPruningStatistics {
166    /// Create a new instance of [`PartitionPruningStatistics`].
167    ///
168    /// Args:
169    /// * `partition_values`: A vector of vectors of [`ScalarValue`]s.
170    ///   The outer vector represents the containers while the inner
171    ///   vector represents the partition values for each column.
172    ///   Note that this is the **opposite** of the order of the
173    ///   partition columns in `PartitionPruningStatistics::partition_schema`.
174    /// * `partition_schema`: The schema of the partition columns.
175    ///   This must **not** be the schema of the entire file or table:
176    ///   instead it must only be the schema of the partition columns,
177    ///   in the same order as the values in `partition_values`.
178    ///
179    /// # Example
180    ///
181    /// To create [`PartitionPruningStatistics`] for two partition columns `a` and `b`,
182    /// for three containers like this:
183    ///
184    /// | a | b |
185    /// | - | - |
186    /// | 1 | 2 |
187    /// | 3 | 4 |
188    /// | 5 | 6 |
189    ///
190    /// ```
191    /// # use std::sync::Arc;
192    /// # use datafusion_common::ScalarValue;
193    /// # use arrow::datatypes::{DataType, Field};
194    /// # use datafusion_common::pruning::PartitionPruningStatistics;
195    ///
196    /// let partition_values = vec![
197    ///     vec![ScalarValue::from(1i32), ScalarValue::from(2i32)],
198    ///     vec![ScalarValue::from(3i32), ScalarValue::from(4i32)],
199    ///     vec![ScalarValue::from(5i32), ScalarValue::from(6i32)],
200    /// ];
201    /// let partition_fields = vec![
202    ///     Arc::new(Field::new("a", DataType::Int32, false)),
203    ///     Arc::new(Field::new("b", DataType::Int32, false)),
204    /// ];
205    /// let partition_stats =
206    ///     PartitionPruningStatistics::try_new(partition_values, partition_fields).unwrap();
207    /// ```
208    pub fn try_new(
209        partition_values: Vec<Vec<ScalarValue>>,
210        partition_fields: Vec<FieldRef>,
211    ) -> Result<Self, DataFusionError> {
212        let num_containers = partition_values.len();
213        let partition_schema = Arc::new(Schema::new(partition_fields));
214        let mut partition_values_by_column =
215            vec![
216                Vec::with_capacity(partition_values.len());
217                partition_schema.fields().len()
218            ];
219        for partition_value in partition_values {
220            for (i, value) in partition_value.into_iter().enumerate() {
221                partition_values_by_column[i].push(value);
222            }
223        }
224        Ok(Self {
225            partition_values: partition_values_by_column
226                .into_iter()
227                .map(|v| {
228                    if v.is_empty() {
229                        Ok(Arc::new(NullArray::new(0)) as ArrayRef)
230                    } else {
231                        ScalarValue::iter_to_array(v)
232                    }
233                })
234                .collect::<Result<Vec<_>, _>>()?,
235            num_containers,
236            partition_schema,
237        })
238    }
239}
240
241#[expect(deprecated)]
242impl PruningStatistics for PartitionPruningStatistics {
243    fn min_values(&self, column: &Column) -> Option<ArrayRef> {
244        let index = self.partition_schema.index_of(column.name()).ok()?;
245        self.partition_values.get(index).and_then(|v| {
246            if v.is_empty() || v.null_count() == v.len() {
247                // If the array is empty or all nulls, return None
248                None
249            } else {
250                // Otherwise, return the array as is
251                Some(Arc::clone(v))
252            }
253        })
254    }
255
256    fn max_values(&self, column: &Column) -> Option<ArrayRef> {
257        self.min_values(column)
258    }
259
260    fn num_containers(&self) -> usize {
261        self.num_containers
262    }
263
264    fn null_counts(&self, _column: &Column) -> Option<ArrayRef> {
265        None
266    }
267
268    fn row_counts(&self) -> Option<ArrayRef> {
269        None
270    }
271
272    fn contained(
273        &self,
274        column: &Column,
275        values: &HashSet<ScalarValue>,
276    ) -> Option<BooleanArray> {
277        let index = self.partition_schema.index_of(column.name()).ok()?;
278        let array = self.partition_values.get(index)?;
279        let boolean_array = values.iter().try_fold(None, |acc, v| {
280            let arrow_value = v.to_scalar().ok()?;
281            let eq_result = arrow::compute::kernels::cmp::eq(array, &arrow_value).ok()?;
282            match acc {
283                None => Some(Some(eq_result)),
284                Some(acc_array) => {
285                    arrow::compute::kernels::boolean::or_kleene(&acc_array, &eq_result)
286                        .map(Some)
287                        .ok()
288                }
289            }
290        })??;
291        // If the boolean array is empty or all null values, return None
292        if boolean_array.is_empty() || boolean_array.null_count() == boolean_array.len() {
293            None
294        } else {
295            Some(boolean_array)
296        }
297    }
298}
299
300/// Prune a set of containers represented by their statistics.
301///
302/// Each [`Statistics`] represents a "container" -- some collection of data
303/// that has statistics of its columns.
304///
305/// It is up to the caller to decide what each container represents. For
306/// example, they can come from a file (e.g. [`PartitionedFile`]) or a set of
307/// files (e.g. [`FileGroup`])
308///
309/// [`PartitionedFile`]: https://docs.rs/datafusion/latest/datafusion/datasource/listing/struct.PartitionedFile.html
310/// [`FileGroup`]: https://docs.rs/datafusion/latest/datafusion/datasource/physical_plan/struct.FileGroup.html
311#[derive(Clone)]
312pub struct PrunableStatistics {
313    /// Statistics for each container.
314    /// These are taken as a reference since they may be rather large / expensive to clone
315    /// and we often won't return all of them as ArrayRefs (we only return the columns the predicate requests).
316    statistics: Vec<Arc<Statistics>>,
317    /// The schema of the file these statistics are for.
318    schema: SchemaRef,
319}
320
321impl PrunableStatistics {
322    /// Create a new instance of [`PrunableStatistics`].
323    /// Each [`Statistics`] represents a container (e.g. a file or a partition of files).
324    /// The `schema` is the schema of the data in the containers and should apply to all files.
325    pub fn new(statistics: Vec<Arc<Statistics>>, schema: SchemaRef) -> Self {
326        Self { statistics, schema }
327    }
328
329    fn get_exact_column_statistics(
330        &self,
331        column: &Column,
332        get_stat: impl Fn(&ColumnStatistics) -> &Precision<ScalarValue>,
333    ) -> Option<ArrayRef> {
334        let index = self.schema.index_of(column.name()).ok()?;
335        let mut has_value = false;
336        match ScalarValue::iter_to_array(self.statistics.iter().map(|s| {
337            s.column_statistics
338                .get(index)
339                .and_then(|stat| {
340                    if let Precision::Exact(min) = get_stat(stat) {
341                        has_value = true;
342                        Some(min.clone())
343                    } else {
344                        None
345                    }
346                })
347                .unwrap_or(ScalarValue::Null)
348        })) {
349            // If there is any non-null value and no errors, return the array
350            Ok(array) => has_value.then_some(array),
351            Err(_) => {
352                log::warn!(
353                    "Failed to convert min values to array for column {}",
354                    column.name()
355                );
356                None
357            }
358        }
359    }
360}
361
362impl PruningStatistics for PrunableStatistics {
363    fn min_values(&self, column: &Column) -> Option<ArrayRef> {
364        self.get_exact_column_statistics(column, |stat| &stat.min_value)
365    }
366
367    fn max_values(&self, column: &Column) -> Option<ArrayRef> {
368        self.get_exact_column_statistics(column, |stat| &stat.max_value)
369    }
370
371    fn num_containers(&self) -> usize {
372        self.statistics.len()
373    }
374
375    fn null_counts(&self, column: &Column) -> Option<ArrayRef> {
376        let index = self.schema.index_of(column.name()).ok()?;
377        if self.statistics.iter().any(|s| {
378            s.column_statistics
379                .get(index)
380                .is_some_and(|stat| stat.null_count.is_exact().unwrap_or(false))
381        }) {
382            Some(Arc::new(
383                self.statistics
384                    .iter()
385                    .map(|s| {
386                        s.column_statistics.get(index).and_then(|stat| {
387                            if let Precision::Exact(null_count) = &stat.null_count {
388                                u64::try_from(*null_count).ok()
389                            } else {
390                                None
391                            }
392                        })
393                    })
394                    .collect::<UInt64Array>(),
395            ))
396        } else {
397            None
398        }
399    }
400
401    fn row_counts(&self) -> Option<ArrayRef> {
402        if self
403            .statistics
404            .iter()
405            .any(|s| s.num_rows.is_exact().unwrap_or(false))
406        {
407            Some(Arc::new(
408                self.statistics
409                    .iter()
410                    .map(|s| {
411                        if let Precision::Exact(row_count) = &s.num_rows {
412                            u64::try_from(*row_count).ok()
413                        } else {
414                            None
415                        }
416                    })
417                    .collect::<UInt64Array>(),
418            ))
419        } else {
420            None
421        }
422    }
423
424    fn contained(
425        &self,
426        _column: &Column,
427        _values: &HashSet<ScalarValue>,
428    ) -> Option<BooleanArray> {
429        None
430    }
431}
432
433/// Combine multiple [`PruningStatistics`] into a single
434/// [`CompositePruningStatistics`].
435/// This can be used to combine statistics from different sources,
436/// for example partition values and file statistics.
437/// This allows pruning with filters that depend on multiple sources of statistics,
438/// such as `WHERE partition_col = data_col`.
439/// This is done by iterating over the statistics and returning the first
440/// one that has information for the requested column.
441/// If multiple statistics have information for the same column,
442/// the first one is returned without any regard for completeness or accuracy.
443/// That is: if the first statistics has information for a column, even if it is incomplete,
444/// that is returned even if a later statistics has more complete information.
445#[deprecated(
446    since = "52.0.0",
447    note = "This struct is no longer used internally. It may be removed in 58.0.0 or 6 months after 52.0.0 is released, whichever comes first. Please open an issue if you have a use case for it."
448)]
449pub struct CompositePruningStatistics {
450    pub statistics: Vec<Box<dyn PruningStatistics>>,
451}
452
453#[expect(deprecated)]
454impl CompositePruningStatistics {
455    /// Create a new instance of [`CompositePruningStatistics`] from
456    /// a vector of [`PruningStatistics`].
457    pub fn new(statistics: Vec<Box<dyn PruningStatistics>>) -> Self {
458        assert!(!statistics.is_empty());
459        // Check that all statistics have the same number of containers
460        let num_containers = statistics[0].num_containers();
461        for stats in &statistics {
462            assert_eq!(num_containers, stats.num_containers());
463        }
464        Self { statistics }
465    }
466}
467
468#[expect(deprecated)]
469impl PruningStatistics for CompositePruningStatistics {
470    fn min_values(&self, column: &Column) -> Option<ArrayRef> {
471        for stats in &self.statistics {
472            if let Some(array) = stats.min_values(column) {
473                return Some(array);
474            }
475        }
476        None
477    }
478
479    fn max_values(&self, column: &Column) -> Option<ArrayRef> {
480        for stats in &self.statistics {
481            if let Some(array) = stats.max_values(column) {
482                return Some(array);
483            }
484        }
485        None
486    }
487
488    fn num_containers(&self) -> usize {
489        self.statistics[0].num_containers()
490    }
491
492    fn null_counts(&self, column: &Column) -> Option<ArrayRef> {
493        for stats in &self.statistics {
494            if let Some(array) = stats.null_counts(column) {
495                return Some(array);
496            }
497        }
498        None
499    }
500
501    fn row_counts(&self) -> Option<ArrayRef> {
502        for stats in &self.statistics {
503            if let Some(array) = stats.row_counts() {
504                return Some(array);
505            }
506        }
507        None
508    }
509
510    fn contained(
511        &self,
512        column: &Column,
513        values: &HashSet<ScalarValue>,
514    ) -> Option<BooleanArray> {
515        for stats in &self.statistics {
516            if let Some(array) = stats.contained(column, values) {
517                return Some(array);
518            }
519        }
520        None
521    }
522}
523
524#[cfg(test)]
525#[expect(deprecated)]
526#[allow(clippy::allow_attributes, clippy::mutable_key_type)] // ScalarValue has interior mutability but is intentionally used as hash key
527mod tests {
528    use crate::{
529        ColumnStatistics,
530        cast::{as_int32_array, as_uint64_array},
531    };
532
533    use super::*;
534    use arrow::datatypes::{DataType, Field};
535    use std::sync::Arc;
536
537    /// return a PartitionPruningStatistics for two columns 'a' and 'b'
538    /// and the following stats
539    ///
540    /// | a | b |
541    /// | - | - |
542    /// | 1 | 2 |
543    /// | 3 | 4 |
544    fn partition_pruning_statistics_setup() -> PartitionPruningStatistics {
545        let partition_values = vec![
546            vec![ScalarValue::from(1i32), ScalarValue::from(2i32)],
547            vec![ScalarValue::from(3i32), ScalarValue::from(4i32)],
548        ];
549        let partition_fields = vec![
550            Arc::new(Field::new("a", DataType::Int32, false)),
551            Arc::new(Field::new("b", DataType::Int32, false)),
552        ];
553        PartitionPruningStatistics::try_new(partition_values, partition_fields).unwrap()
554    }
555
556    #[test]
557    fn test_partition_pruning_statistics() {
558        let partition_stats = partition_pruning_statistics_setup();
559
560        let column_a = Column::new_unqualified("a");
561        let column_b = Column::new_unqualified("b");
562
563        // Partition values don't know anything about nulls or row counts
564        assert!(partition_stats.null_counts(&column_a).is_none());
565        assert!(partition_stats.row_counts().is_none());
566        assert!(partition_stats.null_counts(&column_b).is_none());
567        assert!(partition_stats.row_counts().is_none());
568
569        // Min/max values are the same as the partition values
570        let min_values_a =
571            as_int32_array(&partition_stats.min_values(&column_a).unwrap())
572                .unwrap()
573                .into_iter()
574                .collect::<Vec<_>>();
575        let expected_values_a = vec![Some(1), Some(3)];
576        assert_eq!(min_values_a, expected_values_a);
577        let max_values_a =
578            as_int32_array(&partition_stats.max_values(&column_a).unwrap())
579                .unwrap()
580                .into_iter()
581                .collect::<Vec<_>>();
582        let expected_values_a = vec![Some(1), Some(3)];
583        assert_eq!(max_values_a, expected_values_a);
584
585        let min_values_b =
586            as_int32_array(&partition_stats.min_values(&column_b).unwrap())
587                .unwrap()
588                .into_iter()
589                .collect::<Vec<_>>();
590        let expected_values_b = vec![Some(2), Some(4)];
591        assert_eq!(min_values_b, expected_values_b);
592        let max_values_b =
593            as_int32_array(&partition_stats.max_values(&column_b).unwrap())
594                .unwrap()
595                .into_iter()
596                .collect::<Vec<_>>();
597        let expected_values_b = vec![Some(2), Some(4)];
598        assert_eq!(max_values_b, expected_values_b);
599
600        // Contained values are only true for the partition values
601        let values = HashSet::from([ScalarValue::from(1i32)]);
602        let contained_a = partition_stats.contained(&column_a, &values).unwrap();
603        let expected_contained_a = BooleanArray::from(vec![true, false]);
604        assert_eq!(contained_a, expected_contained_a);
605        let contained_b = partition_stats.contained(&column_b, &values).unwrap();
606        let expected_contained_b = BooleanArray::from(vec![false, false]);
607        assert_eq!(contained_b, expected_contained_b);
608
609        // The number of containers is the length of the partition values
610        assert_eq!(partition_stats.num_containers(), 2);
611    }
612
613    #[test]
614    fn test_partition_pruning_statistics_multiple_positive_values() {
615        let partition_stats = partition_pruning_statistics_setup();
616
617        let column_a = Column::new_unqualified("a");
618
619        // The two containers have `a` values 1 and 3, so they both only contain values from 1 and 3
620        let values = HashSet::from([ScalarValue::from(1i32), ScalarValue::from(3i32)]);
621        let contained_a = partition_stats.contained(&column_a, &values).unwrap();
622        let expected_contained_a = BooleanArray::from(vec![true, true]);
623        assert_eq!(contained_a, expected_contained_a);
624    }
625
626    #[test]
627    fn test_partition_pruning_statistics_multiple_negative_values() {
628        let partition_stats = partition_pruning_statistics_setup();
629
630        let column_a = Column::new_unqualified("a");
631
632        // The two containers have `a` values 1 and 3,
633        // so the first contains ONLY values from 1,2
634        // but the second does not
635        let values = HashSet::from([ScalarValue::from(1i32), ScalarValue::from(2i32)]);
636        let contained_a = partition_stats.contained(&column_a, &values).unwrap();
637        let expected_contained_a = BooleanArray::from(vec![true, false]);
638        assert_eq!(contained_a, expected_contained_a);
639    }
640
641    #[test]
642    fn test_partition_pruning_statistics_null_in_values() {
643        let partition_values = vec![
644            vec![
645                ScalarValue::from(1i32),
646                ScalarValue::from(2i32),
647                ScalarValue::from(3i32),
648            ],
649            vec![
650                ScalarValue::from(4i32),
651                ScalarValue::from(5i32),
652                ScalarValue::from(6i32),
653            ],
654        ];
655        let partition_fields = vec![
656            Arc::new(Field::new("a", DataType::Int32, false)),
657            Arc::new(Field::new("b", DataType::Int32, false)),
658            Arc::new(Field::new("c", DataType::Int32, false)),
659        ];
660        let partition_stats =
661            PartitionPruningStatistics::try_new(partition_values, partition_fields)
662                .unwrap();
663
664        let column_a = Column::new_unqualified("a");
665        let column_b = Column::new_unqualified("b");
666        let column_c = Column::new_unqualified("c");
667
668        let values_a = HashSet::from([ScalarValue::from(1i32), ScalarValue::Int32(None)]);
669        let contained_a = partition_stats.contained(&column_a, &values_a).unwrap();
670        let mut builder = BooleanArray::builder(2);
671        builder.append_value(true);
672        builder.append_null();
673        let expected_contained_a = builder.finish();
674        assert_eq!(contained_a, expected_contained_a);
675
676        // First match creates a NULL boolean array
677        // The accumulator should update the value to true for the second value
678        let values_b = HashSet::from([ScalarValue::Int32(None), ScalarValue::from(5i32)]);
679        let contained_b = partition_stats.contained(&column_b, &values_b).unwrap();
680        let mut builder = BooleanArray::builder(2);
681        builder.append_null();
682        builder.append_value(true);
683        let expected_contained_b = builder.finish();
684        assert_eq!(contained_b, expected_contained_b);
685
686        // All matches are null, contained should return None
687        let values_c = HashSet::from([ScalarValue::Int32(None)]);
688        let contained_c = partition_stats.contained(&column_c, &values_c);
689        assert!(contained_c.is_none());
690    }
691
692    #[test]
693    fn test_partition_pruning_statistics_empty() {
694        let partition_values = vec![];
695        let partition_fields = vec![
696            Arc::new(Field::new("a", DataType::Int32, false)),
697            Arc::new(Field::new("b", DataType::Int32, false)),
698        ];
699        let partition_stats =
700            PartitionPruningStatistics::try_new(partition_values, partition_fields)
701                .unwrap();
702
703        let column_a = Column::new_unqualified("a");
704        let column_b = Column::new_unqualified("b");
705
706        // Partition values don't know anything about nulls or row counts
707        assert!(partition_stats.null_counts(&column_a).is_none());
708        assert!(partition_stats.row_counts().is_none());
709        assert!(partition_stats.null_counts(&column_b).is_none());
710        assert!(partition_stats.row_counts().is_none());
711
712        // Min/max values are all missing
713        assert!(partition_stats.min_values(&column_a).is_none());
714        assert!(partition_stats.max_values(&column_a).is_none());
715        assert!(partition_stats.min_values(&column_b).is_none());
716        assert!(partition_stats.max_values(&column_b).is_none());
717
718        // Contained values are all empty
719        let values = HashSet::from([ScalarValue::from(1i32)]);
720        assert!(partition_stats.contained(&column_a, &values).is_none());
721    }
722
723    #[test]
724    fn test_statistics_pruning_statistics() {
725        let statistics = vec![
726            Arc::new(
727                Statistics::default()
728                    .add_column_statistics(
729                        ColumnStatistics::new_unknown()
730                            .with_min_value(Precision::Exact(ScalarValue::from(0i32)))
731                            .with_max_value(Precision::Exact(ScalarValue::from(100i32)))
732                            .with_null_count(Precision::Exact(0)),
733                    )
734                    .add_column_statistics(
735                        ColumnStatistics::new_unknown()
736                            .with_min_value(Precision::Exact(ScalarValue::from(100i32)))
737                            .with_max_value(Precision::Exact(ScalarValue::from(200i32)))
738                            .with_null_count(Precision::Exact(5)),
739                    )
740                    .with_num_rows(Precision::Exact(100)),
741            ),
742            Arc::new(
743                Statistics::default()
744                    .add_column_statistics(
745                        ColumnStatistics::new_unknown()
746                            .with_min_value(Precision::Exact(ScalarValue::from(50i32)))
747                            .with_max_value(Precision::Exact(ScalarValue::from(300i32)))
748                            .with_null_count(Precision::Exact(10)),
749                    )
750                    .add_column_statistics(
751                        ColumnStatistics::new_unknown()
752                            .with_min_value(Precision::Exact(ScalarValue::from(200i32)))
753                            .with_max_value(Precision::Exact(ScalarValue::from(400i32)))
754                            .with_null_count(Precision::Exact(0)),
755                    )
756                    .with_num_rows(Precision::Exact(200)),
757            ),
758        ];
759
760        let schema = Arc::new(Schema::new(vec![
761            Field::new("a", DataType::Int32, false),
762            Field::new("b", DataType::Int32, false),
763            Field::new("c", DataType::Int32, false),
764        ]));
765        let pruning_stats = PrunableStatistics::new(statistics, schema);
766
767        let column_a = Column::new_unqualified("a");
768        let column_b = Column::new_unqualified("b");
769
770        // Min/max values are the same as the statistics
771        let min_values_a = as_int32_array(&pruning_stats.min_values(&column_a).unwrap())
772            .unwrap()
773            .into_iter()
774            .collect::<Vec<_>>();
775        let expected_values_a = vec![Some(0), Some(50)];
776        assert_eq!(min_values_a, expected_values_a);
777        let max_values_a = as_int32_array(&pruning_stats.max_values(&column_a).unwrap())
778            .unwrap()
779            .into_iter()
780            .collect::<Vec<_>>();
781        let expected_values_a = vec![Some(100), Some(300)];
782        assert_eq!(max_values_a, expected_values_a);
783        let min_values_b = as_int32_array(&pruning_stats.min_values(&column_b).unwrap())
784            .unwrap()
785            .into_iter()
786            .collect::<Vec<_>>();
787        let expected_values_b = vec![Some(100), Some(200)];
788        assert_eq!(min_values_b, expected_values_b);
789        let max_values_b = as_int32_array(&pruning_stats.max_values(&column_b).unwrap())
790            .unwrap()
791            .into_iter()
792            .collect::<Vec<_>>();
793        let expected_values_b = vec![Some(200), Some(400)];
794        assert_eq!(max_values_b, expected_values_b);
795
796        // Null counts are the same as the statistics
797        let null_counts_a =
798            as_uint64_array(&pruning_stats.null_counts(&column_a).unwrap())
799                .unwrap()
800                .into_iter()
801                .collect::<Vec<_>>();
802        let expected_null_counts_a = vec![Some(0), Some(10)];
803        assert_eq!(null_counts_a, expected_null_counts_a);
804        let null_counts_b =
805            as_uint64_array(&pruning_stats.null_counts(&column_b).unwrap())
806                .unwrap()
807                .into_iter()
808                .collect::<Vec<_>>();
809        let expected_null_counts_b = vec![Some(5), Some(0)];
810        assert_eq!(null_counts_b, expected_null_counts_b);
811
812        // Row counts are the same as the statistics
813        let row_counts_a = as_uint64_array(&pruning_stats.row_counts().unwrap())
814            .unwrap()
815            .into_iter()
816            .collect::<Vec<_>>();
817        let expected_row_counts_a = vec![Some(100), Some(200)];
818        assert_eq!(row_counts_a, expected_row_counts_a);
819        let row_counts_b = as_uint64_array(&pruning_stats.row_counts().unwrap())
820            .unwrap()
821            .into_iter()
822            .collect::<Vec<_>>();
823        let expected_row_counts_b = vec![Some(100), Some(200)];
824        assert_eq!(row_counts_b, expected_row_counts_b);
825
826        // Contained values are all null/missing (we can't know this just from statistics)
827        let values = HashSet::from([ScalarValue::from(0i32)]);
828        assert!(pruning_stats.contained(&column_a, &values).is_none());
829        assert!(pruning_stats.contained(&column_b, &values).is_none());
830
831        // The number of containers is the length of the statistics
832        assert_eq!(pruning_stats.num_containers(), 2);
833
834        // Test with a column that has no statistics
835        let column_c = Column::new_unqualified("c");
836        assert!(pruning_stats.min_values(&column_c).is_none());
837        assert!(pruning_stats.max_values(&column_c).is_none());
838        assert!(pruning_stats.null_counts(&column_c).is_none());
839        // Since row counts uses the first column that has row counts we get them back even
840        // if this columns does not have them set.
841        // This is debatable, personally I think `row_count` should not take a `Column` as an argument
842        // at all since all columns should have the same number of rows.
843        // But for now we just document the current behavior in this test.
844        let row_counts_c = as_uint64_array(&pruning_stats.row_counts().unwrap())
845            .unwrap()
846            .into_iter()
847            .collect::<Vec<_>>();
848        let expected_row_counts_c = vec![Some(100), Some(200)];
849        assert_eq!(row_counts_c, expected_row_counts_c);
850        assert!(pruning_stats.contained(&column_c, &values).is_none());
851
852        // Test with a column that doesn't exist — column-specific stats
853        // return None, but row_counts is container-level and still available
854        let column_d = Column::new_unqualified("d");
855        assert!(pruning_stats.min_values(&column_d).is_none());
856        assert!(pruning_stats.max_values(&column_d).is_none());
857        assert!(pruning_stats.null_counts(&column_d).is_none());
858        assert!(pruning_stats.row_counts().is_some());
859        assert!(pruning_stats.contained(&column_d, &values).is_none());
860    }
861
862    #[test]
863    fn test_statistics_pruning_statistics_empty() {
864        let statistics = vec![];
865        let schema = Arc::new(Schema::new(vec![
866            Field::new("a", DataType::Int32, false),
867            Field::new("b", DataType::Int32, false),
868            Field::new("c", DataType::Int32, false),
869        ]));
870        let pruning_stats = PrunableStatistics::new(statistics, schema);
871
872        let column_a = Column::new_unqualified("a");
873        let column_b = Column::new_unqualified("b");
874
875        // Min/max values are all missing
876        assert!(pruning_stats.min_values(&column_a).is_none());
877        assert!(pruning_stats.max_values(&column_a).is_none());
878        assert!(pruning_stats.min_values(&column_b).is_none());
879        assert!(pruning_stats.max_values(&column_b).is_none());
880
881        // Null counts are all missing
882        assert!(pruning_stats.null_counts(&column_a).is_none());
883        assert!(pruning_stats.null_counts(&column_b).is_none());
884
885        // Row counts are all missing
886        assert!(pruning_stats.row_counts().is_none());
887        assert!(pruning_stats.row_counts().is_none());
888
889        // Contained values are all empty
890        let values = HashSet::from([ScalarValue::from(1i32)]);
891        assert!(pruning_stats.contained(&column_a, &values).is_none());
892    }
893
894    #[test]
895    fn test_composite_pruning_statistics_partition_and_file() {
896        // Create partition statistics
897        let partition_values = vec![
898            vec![ScalarValue::from(1i32), ScalarValue::from(10i32)],
899            vec![ScalarValue::from(2i32), ScalarValue::from(20i32)],
900        ];
901        let partition_fields = vec![
902            Arc::new(Field::new("part_a", DataType::Int32, false)),
903            Arc::new(Field::new("part_b", DataType::Int32, false)),
904        ];
905        let partition_stats =
906            PartitionPruningStatistics::try_new(partition_values, partition_fields)
907                .unwrap();
908
909        // Create file statistics
910        let file_statistics = vec![
911            Arc::new(
912                Statistics::default()
913                    .add_column_statistics(
914                        ColumnStatistics::new_unknown()
915                            .with_min_value(Precision::Exact(ScalarValue::from(100i32)))
916                            .with_max_value(Precision::Exact(ScalarValue::from(200i32)))
917                            .with_null_count(Precision::Exact(0)),
918                    )
919                    .add_column_statistics(
920                        ColumnStatistics::new_unknown()
921                            .with_min_value(Precision::Exact(ScalarValue::from(300i32)))
922                            .with_max_value(Precision::Exact(ScalarValue::from(400i32)))
923                            .with_null_count(Precision::Exact(5)),
924                    )
925                    .with_num_rows(Precision::Exact(100)),
926            ),
927            Arc::new(
928                Statistics::default()
929                    .add_column_statistics(
930                        ColumnStatistics::new_unknown()
931                            .with_min_value(Precision::Exact(ScalarValue::from(500i32)))
932                            .with_max_value(Precision::Exact(ScalarValue::from(600i32)))
933                            .with_null_count(Precision::Exact(10)),
934                    )
935                    .add_column_statistics(
936                        ColumnStatistics::new_unknown()
937                            .with_min_value(Precision::Exact(ScalarValue::from(700i32)))
938                            .with_max_value(Precision::Exact(ScalarValue::from(800i32)))
939                            .with_null_count(Precision::Exact(0)),
940                    )
941                    .with_num_rows(Precision::Exact(200)),
942            ),
943        ];
944
945        let file_schema = Arc::new(Schema::new(vec![
946            Field::new("col_x", DataType::Int32, false),
947            Field::new("col_y", DataType::Int32, false),
948        ]));
949        let file_stats = PrunableStatistics::new(file_statistics, file_schema);
950
951        // Create composite statistics
952        let composite_stats = CompositePruningStatistics::new(vec![
953            Box::new(partition_stats),
954            Box::new(file_stats),
955        ]);
956
957        // Test accessing columns that are only in partition statistics
958        let part_a = Column::new_unqualified("part_a");
959        let part_b = Column::new_unqualified("part_b");
960
961        // Test accessing columns that are only in file statistics
962        let col_x = Column::new_unqualified("col_x");
963        let col_y = Column::new_unqualified("col_y");
964
965        // For partition columns, should get values from partition statistics
966        let min_values_part_a =
967            as_int32_array(&composite_stats.min_values(&part_a).unwrap())
968                .unwrap()
969                .into_iter()
970                .collect::<Vec<_>>();
971        let expected_values_part_a = vec![Some(1), Some(2)];
972        assert_eq!(min_values_part_a, expected_values_part_a);
973
974        let max_values_part_a =
975            as_int32_array(&composite_stats.max_values(&part_a).unwrap())
976                .unwrap()
977                .into_iter()
978                .collect::<Vec<_>>();
979        // For partition values, min and max are the same
980        assert_eq!(max_values_part_a, expected_values_part_a);
981
982        let min_values_part_b =
983            as_int32_array(&composite_stats.min_values(&part_b).unwrap())
984                .unwrap()
985                .into_iter()
986                .collect::<Vec<_>>();
987        let expected_values_part_b = vec![Some(10), Some(20)];
988        assert_eq!(min_values_part_b, expected_values_part_b);
989
990        // For file columns, should get values from file statistics
991        let min_values_col_x =
992            as_int32_array(&composite_stats.min_values(&col_x).unwrap())
993                .unwrap()
994                .into_iter()
995                .collect::<Vec<_>>();
996        let expected_values_col_x = vec![Some(100), Some(500)];
997        assert_eq!(min_values_col_x, expected_values_col_x);
998
999        let max_values_col_x =
1000            as_int32_array(&composite_stats.max_values(&col_x).unwrap())
1001                .unwrap()
1002                .into_iter()
1003                .collect::<Vec<_>>();
1004        let expected_max_values_col_x = vec![Some(200), Some(600)];
1005        assert_eq!(max_values_col_x, expected_max_values_col_x);
1006
1007        let min_values_col_y =
1008            as_int32_array(&composite_stats.min_values(&col_y).unwrap())
1009                .unwrap()
1010                .into_iter()
1011                .collect::<Vec<_>>();
1012        let expected_values_col_y = vec![Some(300), Some(700)];
1013        assert_eq!(min_values_col_y, expected_values_col_y);
1014
1015        // Test null counts - only available from file statistics
1016        assert!(composite_stats.null_counts(&part_a).is_none());
1017        assert!(composite_stats.null_counts(&part_b).is_none());
1018
1019        let null_counts_col_x =
1020            as_uint64_array(&composite_stats.null_counts(&col_x).unwrap())
1021                .unwrap()
1022                .into_iter()
1023                .collect::<Vec<_>>();
1024        let expected_null_counts_col_x = vec![Some(0), Some(10)];
1025        assert_eq!(null_counts_col_x, expected_null_counts_col_x);
1026
1027        // Test row counts — container-level, available from file statistics
1028        let row_counts_col_x = as_uint64_array(&composite_stats.row_counts().unwrap())
1029            .unwrap()
1030            .into_iter()
1031            .collect::<Vec<_>>();
1032        let expected_row_counts = vec![Some(100), Some(200)];
1033        assert_eq!(row_counts_col_x, expected_row_counts);
1034
1035        // Test contained values - only available from partition statistics
1036        let values = HashSet::from([ScalarValue::from(1i32)]);
1037        let contained_part_a = composite_stats.contained(&part_a, &values).unwrap();
1038        let expected_contained_part_a = BooleanArray::from(vec![true, false]);
1039        assert_eq!(contained_part_a, expected_contained_part_a);
1040
1041        // File statistics don't implement contained
1042        assert!(composite_stats.contained(&col_x, &values).is_none());
1043
1044        // Non-existent column should return None for column-specific stats,
1045        // but row_counts is container-level and still available
1046        let non_existent = Column::new_unqualified("non_existent");
1047        assert!(composite_stats.min_values(&non_existent).is_none());
1048        assert!(composite_stats.max_values(&non_existent).is_none());
1049        assert!(composite_stats.null_counts(&non_existent).is_none());
1050        assert!(composite_stats.row_counts().is_some());
1051        assert!(composite_stats.contained(&non_existent, &values).is_none());
1052
1053        // Verify num_containers matches
1054        assert_eq!(composite_stats.num_containers(), 2);
1055    }
1056
1057    #[test]
1058    fn test_composite_pruning_statistics_priority() {
1059        // Create two sets of file statistics with the same column names
1060        // but different values to test that the first one gets priority
1061
1062        // First set of statistics
1063        let first_statistics = vec![
1064            Arc::new(
1065                Statistics::default()
1066                    .add_column_statistics(
1067                        ColumnStatistics::new_unknown()
1068                            .with_min_value(Precision::Exact(ScalarValue::from(100i32)))
1069                            .with_max_value(Precision::Exact(ScalarValue::from(200i32)))
1070                            .with_null_count(Precision::Exact(0)),
1071                    )
1072                    .with_num_rows(Precision::Exact(100)),
1073            ),
1074            Arc::new(
1075                Statistics::default()
1076                    .add_column_statistics(
1077                        ColumnStatistics::new_unknown()
1078                            .with_min_value(Precision::Exact(ScalarValue::from(300i32)))
1079                            .with_max_value(Precision::Exact(ScalarValue::from(400i32)))
1080                            .with_null_count(Precision::Exact(5)),
1081                    )
1082                    .with_num_rows(Precision::Exact(200)),
1083            ),
1084        ];
1085
1086        let first_schema = Arc::new(Schema::new(vec![Field::new(
1087            "col_a",
1088            DataType::Int32,
1089            false,
1090        )]));
1091        let first_stats = PrunableStatistics::new(first_statistics, first_schema);
1092
1093        // Second set of statistics with the same column name but different values
1094        let second_statistics = vec![
1095            Arc::new(
1096                Statistics::default()
1097                    .add_column_statistics(
1098                        ColumnStatistics::new_unknown()
1099                            .with_min_value(Precision::Exact(ScalarValue::from(1000i32)))
1100                            .with_max_value(Precision::Exact(ScalarValue::from(2000i32)))
1101                            .with_null_count(Precision::Exact(10)),
1102                    )
1103                    .with_num_rows(Precision::Exact(1000)),
1104            ),
1105            Arc::new(
1106                Statistics::default()
1107                    .add_column_statistics(
1108                        ColumnStatistics::new_unknown()
1109                            .with_min_value(Precision::Exact(ScalarValue::from(3000i32)))
1110                            .with_max_value(Precision::Exact(ScalarValue::from(4000i32)))
1111                            .with_null_count(Precision::Exact(20)),
1112                    )
1113                    .with_num_rows(Precision::Exact(2000)),
1114            ),
1115        ];
1116
1117        let second_schema = Arc::new(Schema::new(vec![Field::new(
1118            "col_a",
1119            DataType::Int32,
1120            false,
1121        )]));
1122        let second_stats = PrunableStatistics::new(second_statistics, second_schema);
1123
1124        // Create composite statistics with first stats having priority
1125        let composite_stats = CompositePruningStatistics::new(vec![
1126            Box::new(first_stats.clone()),
1127            Box::new(second_stats.clone()),
1128        ]);
1129
1130        let col_a = Column::new_unqualified("col_a");
1131
1132        // Should get values from first statistics since it has priority
1133        let min_values = as_int32_array(&composite_stats.min_values(&col_a).unwrap())
1134            .unwrap()
1135            .into_iter()
1136            .collect::<Vec<_>>();
1137        let expected_min_values = vec![Some(100), Some(300)];
1138        assert_eq!(min_values, expected_min_values);
1139
1140        let max_values = as_int32_array(&composite_stats.max_values(&col_a).unwrap())
1141            .unwrap()
1142            .into_iter()
1143            .collect::<Vec<_>>();
1144        let expected_max_values = vec![Some(200), Some(400)];
1145        assert_eq!(max_values, expected_max_values);
1146
1147        let null_counts = as_uint64_array(&composite_stats.null_counts(&col_a).unwrap())
1148            .unwrap()
1149            .into_iter()
1150            .collect::<Vec<_>>();
1151        let expected_null_counts = vec![Some(0), Some(5)];
1152        assert_eq!(null_counts, expected_null_counts);
1153
1154        let row_counts = as_uint64_array(&composite_stats.row_counts().unwrap())
1155            .unwrap()
1156            .into_iter()
1157            .collect::<Vec<_>>();
1158        let expected_row_counts = vec![Some(100), Some(200)];
1159        assert_eq!(row_counts, expected_row_counts);
1160
1161        // Create composite statistics with second stats having priority
1162        // Now that we've added Clone trait to PrunableStatistics, we can just clone them
1163
1164        let composite_stats_reversed = CompositePruningStatistics::new(vec![
1165            Box::new(second_stats.clone()),
1166            Box::new(first_stats.clone()),
1167        ]);
1168
1169        // Should get values from second statistics since it now has priority
1170        let min_values =
1171            as_int32_array(&composite_stats_reversed.min_values(&col_a).unwrap())
1172                .unwrap()
1173                .into_iter()
1174                .collect::<Vec<_>>();
1175        let expected_min_values = vec![Some(1000), Some(3000)];
1176        assert_eq!(min_values, expected_min_values);
1177
1178        let max_values =
1179            as_int32_array(&composite_stats_reversed.max_values(&col_a).unwrap())
1180                .unwrap()
1181                .into_iter()
1182                .collect::<Vec<_>>();
1183        let expected_max_values = vec![Some(2000), Some(4000)];
1184        assert_eq!(max_values, expected_max_values);
1185
1186        let null_counts =
1187            as_uint64_array(&composite_stats_reversed.null_counts(&col_a).unwrap())
1188                .unwrap()
1189                .into_iter()
1190                .collect::<Vec<_>>();
1191        let expected_null_counts = vec![Some(10), Some(20)];
1192        assert_eq!(null_counts, expected_null_counts);
1193
1194        let row_counts = as_uint64_array(&composite_stats_reversed.row_counts().unwrap())
1195            .unwrap()
1196            .into_iter()
1197            .collect::<Vec<_>>();
1198        let expected_row_counts = vec![Some(1000), Some(2000)];
1199        assert_eq!(row_counts, expected_row_counts);
1200    }
1201
1202    #[test]
1203    fn test_composite_pruning_statistics_empty_and_mismatched_containers() {
1204        // Test with empty statistics vector
1205        // This should never happen, so we panic instead of returning a Result which would burned callers
1206        let result = std::panic::catch_unwind(|| {
1207            CompositePruningStatistics::new(vec![]);
1208        });
1209        assert!(result.is_err());
1210
1211        // We should panic here because the number of containers is different
1212        let result = std::panic::catch_unwind(|| {
1213            // Create statistics with different number of containers
1214            // Use partition stats for the test
1215            let partition_values_1 = vec![
1216                vec![ScalarValue::from(1i32), ScalarValue::from(10i32)],
1217                vec![ScalarValue::from(2i32), ScalarValue::from(20i32)],
1218            ];
1219            let partition_fields_1 = vec![
1220                Arc::new(Field::new("part_a", DataType::Int32, false)),
1221                Arc::new(Field::new("part_b", DataType::Int32, false)),
1222            ];
1223            let partition_stats_1 = PartitionPruningStatistics::try_new(
1224                partition_values_1,
1225                partition_fields_1,
1226            )
1227            .unwrap();
1228            let partition_values_2 = vec![
1229                vec![ScalarValue::from(3i32), ScalarValue::from(30i32)],
1230                vec![ScalarValue::from(4i32), ScalarValue::from(40i32)],
1231                vec![ScalarValue::from(5i32), ScalarValue::from(50i32)],
1232            ];
1233            let partition_fields_2 = vec![
1234                Arc::new(Field::new("part_x", DataType::Int32, false)),
1235                Arc::new(Field::new("part_y", DataType::Int32, false)),
1236            ];
1237            let partition_stats_2 = PartitionPruningStatistics::try_new(
1238                partition_values_2,
1239                partition_fields_2,
1240            )
1241            .unwrap();
1242
1243            CompositePruningStatistics::new(vec![
1244                Box::new(partition_stats_1),
1245                Box::new(partition_stats_2),
1246            ]);
1247        });
1248        assert!(result.is_err());
1249    }
1250}