adriangb commented on code in PR #27736:
URL: https://github.com/apache/datafusion/pull/27736#discussion_r4722119319
##########
datafusion/datasource-parquet/src/statistics_resolver.rs:
##########
@@ -0,0 +1,376 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+//! Statistics for expressions, such as struct field and variant accesses,
+//! read from Parquet leaf column statistics.
+//!
+//! ```text
+//! PruningPredicate Parquet scan, one file
+//! asks the matcher: is `expr` a key? --> FileStatisticsResolvers::matches
+//! -> first resolver whose `bind`
+//! returns a binding (cached)
+//! min_values_for_expr(expr) ----------> RowGroupPruningStatistics /
PagesPruningStatistics
+//! -> the cached binding reads leaf
+//! statistics through
+//! ParquetLeafStatistics
+//! ```
+//!
+//! A resolver works on [`ParquetLeafStatistics`], so the same resolver serves
+//! row group statistics and the page index.
+
+use std::collections::HashMap;
+use std::fmt::Debug;
+use std::sync::{Arc, Mutex, MutexGuard};
+
+use arrow::array::ArrayRef;
+use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
+use datafusion_common::ScalarValue;
+use datafusion_functions::core::getfield::GetFieldFunc;
+use datafusion_physical_expr::expressions::{Column, Literal};
+use datafusion_physical_expr::{PhysicalExpr, ScalarFunctionExpr};
+use datafusion_pruning::StatisticsExprMatcher;
+use parquet::schema::types::{SchemaDescPtr, SchemaDescriptor};
+
+/// Which statistic a [`BoundExprStatistics`] is asked for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ExprStatisticsKind {
+ /// Lower bounds, one per container.
+ Min,
+ /// Upper bounds, one per container.
+ Max,
+ /// The number of rows where the expression is null, one per container.
+ NullCount,
+}
+
+/// Statistics of Parquet leaf columns for a set of containers: the row
+/// groups of a file, or the pages of one row group.
+pub trait ParquetLeafStatistics {
+ /// Minimum values of the Parquet leaf column `leaf`, converted to the
+ /// type of `field`. Returns `None` when the statistics are unknown or
+ /// cannot be trusted.
+ fn leaf_mins(&self, leaf: usize, field: &Field) -> Option<ArrayRef>;
+
+ /// Maximum values of the Parquet leaf column `leaf`. See
+ /// [`Self::leaf_mins`].
+ fn leaf_maxes(&self, leaf: usize, field: &Field) -> Option<ArrayRef>;
+
+ /// Null counts of the Parquet leaf column `leaf`, as a `UInt64Array`.
+ /// For a leaf with no repeated ancestor, a row counts as null when the
+ /// leaf or any ancestor is null.
+ fn leaf_null_counts(&self, leaf: usize, field: &Field) -> Option<ArrayRef>;
+
+ /// Row counts, as a `UInt64Array`.
+ fn row_counts(&self) -> Option<ArrayRef>;
+}
+
+/// Reads statistics for an expression from Parquet leaf statistics.
+///
+/// DataFusion provides a resolver for struct fields.
+/// Other crates can add resolvers for their own functions, for example a
+/// variant extension that reads the statistics of shredded `typed_value`
+/// columns for `variant_get`. Register them with
+/// [`ParquetSource::with_statistics_resolver`].
+///
+/// [`ParquetSource::with_statistics_resolver`]:
crate::source::ParquetSource::with_statistics_resolver
+pub trait ParquetStatisticsResolver: Debug + Send + Sync {
+ /// Binds `expr` to the leaves of one file.
+ ///
+ /// The scan calls `bind` once per file for each distinct expression
+ /// that the pruning predicates ask about. Return `None` when this
+ /// resolver has no statistics for `expr` in this file. Then the pruning
+ /// predicate does not use `expr` as a statistics key, and it looks for
+ /// keys in the children of `expr` instead. For example, a predicate on
+ /// `TRY_CAST(e AS Int64)` can use the statistics of `e`.
+ ///
+ /// `EXPLAIN` has no file, so it binds against a Parquet schema that it
+ /// builds from the Arrow file schema. A resolver for leaves that exist
+ /// only in real files, such as shredded variant columns, binds nothing
+ /// there. Its keys then do not show in the `EXPLAIN` pruning predicate,
+ /// but the scan still uses them.
+ fn bind(
+ &self,
+ expr: &Arc<dyn PhysicalExpr>,
+ arrow_schema: &Schema,
+ parquet_schema: &SchemaDescriptor,
+ ) -> Option<Arc<dyn BoundExprStatistics>>;
+}
+
+/// The statistics of one expression in one file, from
+/// [`ParquetStatisticsResolver::bind`].
+pub trait BoundExprStatistics: Debug + Send + Sync {
+ /// Returns one value per container for `kind`.
+ ///
+ /// Bounds must be conservative: each non-null min (max) must be at most
+ /// (at least) every non-null value of the expression in its container.
+ /// Return null for a container whose statistics are unknown, and `None`
+ /// when they are unknown for every container. Pruning keeps a container
+ /// with unknown statistics.
+ fn statistics(
+ &self,
+ kind: ExprStatisticsKind,
+ statistics: &dyn ParquetLeafStatistics,
+ ) -> Option<ArrayRef>;
+
+ /// The Parquet leaf whose pages hold the values of the expression, if
+ /// page index pruning can use these statistics.
+ ///
+ /// The page index prunes one leaf at a time, because the pages of
+ /// different leaves do not line up. Return `None` (the default) when the
+ /// statistics need more than one leaf.
+ fn page_index_leaf(&self) -> Option<usize> {
+ None
+ }
+
+ /// The Parquet leaf whose bloom filter can rule out values of the
+ /// expression.
+ ///
+ /// Return a leaf only when every non-null value of the expression is
+ /// stored in that leaf, with the leaf's physical type. Then a value
+ /// missing from the leaf's bloom filter cannot be a value of the
+ /// expression. The literal is hashed as its own type, so the expression
+ /// must have the type of the leaf without any conversion.
+ ///
+ /// Return `None` (the default) otherwise. For example, a shredded
+ /// variant may store some values in its binary `value` column, which a
+ /// bloom filter on `typed_value` cannot see.
+ fn bloom_filter_leaf(&self) -> Option<usize> {
+ None
+ }
+}
+
+/// The [`ParquetStatisticsResolver`]s of a Parquet scan.
+///
+/// The default holds [`GetFieldStatisticsResolver`]. For each file, the
+/// scan binds them to the schema of that file.
+#[derive(Debug, Clone)]
+pub(crate) struct ParquetStatisticsResolvers {
+ resolvers: Vec<Arc<dyn ParquetStatisticsResolver>>,
+}
+
+impl Default for ParquetStatisticsResolvers {
+ fn default() -> Self {
+ Self {
+ resolvers: vec![Arc::new(GetFieldStatisticsResolver)],
+ }
+ }
+}
+
+impl ParquetStatisticsResolvers {
+ /// Adds `resolver`. Resolvers are asked in the order they were added.
+ pub(crate) fn with_resolver(
+ mut self,
+ resolver: Arc<dyn ParquetStatisticsResolver>,
+ ) -> Self {
+ self.resolvers.push(resolver);
+ self
+ }
+
+ /// Returns `true` if resolvers beyond the built-in ones were added.
+ #[cfg(feature = "proto")]
+ pub(crate) fn has_custom_resolvers(&self) -> bool {
+ self.resolvers.len() > Self::default().resolvers.len()
+ }
+}
+
+type BoundStatistics = Arc<dyn BoundExprStatistics>;
+
+/// [`ParquetStatisticsResolvers`] bound to the schema of one file.
+///
+/// This is the [`StatisticsExprMatcher`] of the pruning predicates for the
+/// file. An expression is a statistics key when the first resolver binds
+/// it. The pruning statistics then read the values from the same binding,
+/// so the key and its statistics always agree.
+///
+/// Each expression is bound once. The binding is cached for the row group,
+/// page index, bloom filter and dynamic filter pruning of the file.
+#[derive(Debug)]
+pub(crate) struct FileStatisticsResolvers {
+ resolvers: ParquetStatisticsResolvers,
+ arrow_schema: SchemaRef,
+ parquet_schema: SchemaDescPtr,
+ bindings: Mutex<HashMap<Arc<dyn PhysicalExpr>, BoundStatistics>>,
+}
+
+impl FileStatisticsResolvers {
+ /// Binds `resolvers` to a file with `arrow_schema` and `parquet_schema`.
+ /// Expressions refer to the columns of `arrow_schema`.
+ pub(crate) fn new(
+ resolvers: ParquetStatisticsResolvers,
+ arrow_schema: SchemaRef,
+ parquet_schema: SchemaDescPtr,
+ ) -> Self {
+ Self {
+ resolvers,
+ arrow_schema,
+ parquet_schema,
+ bindings: Mutex::new(HashMap::new()),
+ }
+ }
+
+ /// The binding of `expr` from the first resolver that binds it.
+ ///
+ /// The cache holds only successful bindings, so an expression without
+ /// statistics does not grow it. The lock is not held while a resolver
+ /// runs.
+ pub(crate) fn bind(
+ &self,
+ expr: &Arc<dyn PhysicalExpr>,
+ ) -> Option<Arc<dyn BoundExprStatistics>> {
+ if let Some(bound) = self.lock_bindings().get(expr) {
+ return Some(Arc::clone(bound));
+ }
+ let bound = self
+ .resolvers
+ .resolvers
+ .iter()
+ .find_map(|r| r.bind(expr, &self.arrow_schema,
&self.parquet_schema))?;
+ Some(Arc::clone(
+ self.lock_bindings()
+ .entry(Arc::clone(expr))
+ .or_insert(bound),
+ ))
+ }
+
+ fn lock_bindings(
+ &self,
+ ) -> MutexGuard<'_, HashMap<Arc<dyn PhysicalExpr>, BoundStatistics>> {
+ self.bindings.lock().unwrap_or_else(|e| e.into_inner())
+ }
+
+ /// The statistics of `expr` for `kind`, if `expr` is bound.
+ pub(crate) fn statistics(
+ &self,
+ expr: &Arc<dyn PhysicalExpr>,
+ kind: ExprStatisticsKind,
+ statistics: &dyn ParquetLeafStatistics,
+ ) -> Option<ArrayRef> {
+ self.bind(expr)?.statistics(kind, statistics)
+ }
+}
+
+/// Two values are equal only when they are the same instance, because
+/// resolvers have no equality of their own.
+impl PartialEq for FileStatisticsResolvers {
+ fn eq(&self, other: &Self) -> bool {
+ std::ptr::eq(self, other)
+ }
+}
+
+impl StatisticsExprMatcher for FileStatisticsResolvers {
+ fn matches(&self, expr: &Arc<dyn PhysicalExpr>) -> bool {
+ self.bind(expr).is_some()
+ }
+}
+
+/// Returns the index of the Parquet leaf column at `path`, such as
+/// `["s", "a"]` for the field `a` of the struct column `s`.
+pub fn leaf_index_by_path(
+ parquet_schema: &SchemaDescriptor,
+ path: &[&str],
+) -> Option<usize> {
+ parquet_schema.columns().iter().position(|descr| {
+ let parts = descr.path().parts();
+ parts.len() == path.len() && parts.iter().zip(path).all(|(a, b)| a ==
b)
+ })
+}
+
+/// Reads the statistics of `get_field(column, 'a', 'b', ...)` from the
+/// Parquet leaf of that struct field.
+///
+/// Only struct paths are supported. A path through a map is a runtime key
+/// lookup, and a field below a list has statistics per element, not per row.
+#[derive(Debug, Default)]
+pub(crate) struct GetFieldStatisticsResolver;
Review Comment:
I spent some time with #26282 to understand where they fit.
I like the split for `get_field` on a plain struct. The function says which
struct paths it reads, the scan maps those paths to Parquet leaves, and nothing
in Parquet needs to downcast `GetFieldFunc`.
Where I get stuck is Variant. Shredding only exists in each file's physical
schema. At planning time `variant_get` sees an unshredded Variant, so the
useful answer from `required_fields` only comes from the per-file call. That
means `ScalarUDFImpl` answers a question about one file's storage layout, and
if the schema adapter unshreds before execution, the function never runs on the
layout it described. It feels like that knowledge belongs at the
format/encoding layer rather than on the function.
So maybe the scope is:
- `NestedInputAccess` (or something like it) for paths that exist at the
logical level, like struct fields. A built-in resolver here would handle every
function with the capability, so `get_field` loses its special case.
- The resolver trait for layouts that only exist per file: shredded Variant,
sidecar leaves, anything that needs bloom filters or per-page data.
That would also let #26282 drop the placeholder-column rewrite, since
`bind`/`StatsExpr` gives it a place to plug in.
But at that point we are creating a trait that as far as I can tell only
helps `get_field` i.e. a trait with a single user.
Does that match how you see it, or am I missing a case where the per-file
`required_fields` is the better home for shredding?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]