diff --git a/Cargo.lock b/Cargo.lock index d9da77fa4b988..eeba54ac98e43 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2539,6 +2539,7 @@ dependencies = [ "hashbrown 0.17.1", "indexmap 2.14.2", "itertools 0.15.0", + "log", "parking_lot 0.13.0", "pin-project", "rand 0.9.4", @@ -2686,6 +2687,7 @@ dependencies = [ "datafusion-datasource", "datafusion-expr", "datafusion-expr-common", + "datafusion-functions", "datafusion-functions-nested", "datafusion-physical-expr", "datafusion-physical-expr-common", diff --git a/datafusion-examples/examples/data_io/parquet_index.rs b/datafusion-examples/examples/data_io/parquet_index.rs index ae52cdf1fe329..f184da9ee3355 100644 --- a/datafusion-examples/examples/data_io/parquet_index.rs +++ b/datafusion-examples/examples/data_io/parquet_index.rs @@ -12,7 +12,6 @@ use arrow::datatypes::{Int32Type, SchemaRef}; use arrow::util::pretty::pretty_format_batches; use async_trait::async_trait; use datafusion::catalog::Session; -use datafusion::common::pruning::PruningStatistics; use datafusion::common::{ DFSchema, DataFusionError, Result, ScalarValue, internal_datafusion_err, }; @@ -29,6 +28,7 @@ use datafusion::parquet::arrow::{ ArrowWriter, arrow_reader::ParquetRecordBatchReaderBuilder, }; use datafusion::physical_expr::PhysicalExpr; +use datafusion::physical_expr_common::pruning::PruningStatistics; use datafusion::physical_optimizer::pruning::PruningPredicateBuilder; use datafusion::physical_plan::ExecutionPlan; use datafusion::prelude::*; diff --git a/datafusion-examples/examples/query_planning/pruning.rs b/datafusion-examples/examples/query_planning/pruning.rs index cd300bbfcddae..7ab6bdc23d1f5 100644 --- a/datafusion-examples/examples/query_planning/pruning.rs +++ b/datafusion-examples/examples/query_planning/pruning.rs @@ -9,12 +9,12 @@ use std::sync::Arc; use arrow::array::{ArrayRef, BooleanArray, Int32Array}; use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; -use datafusion::common::pruning::PruningStatistics; use datafusion::common::{DFSchema, ScalarValue}; use datafusion::error::Result; use datafusion::execution::context::ExecutionProps; use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext; use datafusion::physical_expr::create_physical_expr; +use datafusion::physical_expr_common::pruning::PruningStatistics; use datafusion::physical_optimizer::pruning::{ PruningPredicate, PruningPredicateBuilder, }; diff --git a/datafusion/catalog-listing/src/table.rs b/datafusion/catalog-listing/src/table.rs index 05e3c6c9d1674..c1f31420da4a5 100644 --- a/datafusion/catalog-listing/src/table.rs +++ b/datafusion/catalog-listing/src/table.rs @@ -10,7 +10,6 @@ use crate::{ListingOptions, ListingTableConfig}; use arrow::datatypes::{Field, Metadata, Schema, SchemaBuilder, SchemaRef}; use async_trait::async_trait; use datafusion_catalog::{ScanArgs, ScanResult, Session, TableProvider}; -use datafusion_common::pruning::PrunableStatistics; use datafusion_common::stats::{Precision, is_known_empty}; use datafusion_common::{ Constraints, DFSchema, SchemaExt, SplitPoint, Statistics, internal_datafusion_err, @@ -38,6 +37,7 @@ use datafusion_expr::{ }; use datafusion_physical_expr::{create_lex_ordering, create_physical_partitioning}; use datafusion_physical_expr_adapter::PhysicalExprAdapterFactory; +use datafusion_physical_expr_common::pruning::PrunableStatistics; use datafusion_physical_expr_common::sort_expr::LexOrdering; use datafusion_physical_plan::ExecutionPlan; use datafusion_physical_plan::empty::EmptyExec; diff --git a/datafusion/common/src/lib.rs b/datafusion/common/src/lib.rs index b37ee729c9e63..e822618d67f1f 100644 --- a/datafusion/common/src/lib.rs +++ b/datafusion/common/src/lib.rs @@ -43,7 +43,6 @@ pub mod nested_struct; mod null_equality; pub mod parquet_config; pub mod parsers; -pub mod pruning; pub mod rounding; pub mod scalar; pub mod spans; diff --git a/datafusion/core/tests/parquet/expr_statistics_resolver.rs b/datafusion/core/tests/parquet/expr_statistics_resolver.rs new file mode 100644 index 0000000000000..83269173c0f59 --- /dev/null +++ b/datafusion/core/tests/parquet/expr_statistics_resolver.rs @@ -0,0 +1,489 @@ +// 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 + +//! A [`ParquetStatisticsResolver`] registered from outside DataFusion prunes +//! row groups for its own function. +//! +//! `fake_variant_get(v, 'a')` stands in for a shredded variant access. The +//! file stores `a` in `v.typed_value.a.typed_value` when it is shredded and +//! in `v.typed_value.a.value` (binary) when it is not: +//! +//! | Row group | `typed_value` | `value` | Bounds usable? | +//! |-----------|---------------|--------------|----------------| +//! | 0 | 1, 2 | null, null | yes: [1, 2] | +//! | 1 | 10, 11 | null, null | yes: [10, 11] | +//! | 2 | 3, null | null, <100> | no: one row is not shredded | +//! +//! For `fake_variant_get(v, 'a') > 5`, only row group 0 can be pruned. +//! +//! The binding does not implement `bloom_filter_leaf` or `page_index_leaf`. +//! A bloom filter on `typed_value` cannot see values stored in `value`, and +//! its validity check needs a second leaf, whose pages do not line up. + +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, BinaryArray, BooleanArray, Int32Array, Int64Array, RecordBatch, + StructArray, UInt64Array, +}; +use arrow::compute::nullif; +use arrow::datatypes::{DataType, Field, Fields, Schema, SchemaRef}; +use datafusion::datasource::listing::PartitionedFile; +use datafusion::datasource::physical_plan::ParquetSource; +use datafusion::functions::core::expr_fn::get_field; +use datafusion::prelude::{SessionConfig, SessionContext}; +use datafusion_common::{DFSchema, Result, ScalarValue, internal_err}; +use datafusion_datasource::file_scan_config::FileScanConfigBuilder; +use datafusion_datasource::source::DataSourceExec; +use datafusion_datasource_parquet::statistics_resolver::{ + BoundExprStatistics, ExprStatisticsKind, ParquetLeafStatistics, + ParquetStatisticsResolver, leaf_index_by_path, +}; +use datafusion_execution::object_store::ObjectStoreUrl; +use datafusion_expr::{ + ColumnarValue, Operator, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature, + Volatility, col, lit, +}; +use datafusion_physical_expr::expressions::{ + BinaryExpr, Column, DynamicFilterPhysicalExpr, Literal, TryCastExpr, +}; +use datafusion_physical_expr::{PhysicalExpr, ScalarFunctionExpr}; +use datafusion_physical_plan::ExecutionPlan; +use datafusion_physical_plan::metrics::MetricValue; +use futures::StreamExt; +use parquet::arrow::ArrowWriter; +use parquet::file::properties::WriterProperties; +use parquet::schema::types::SchemaDescriptor; +use tempfile::NamedTempFile; + +use crate::parquet::utils::MetricsFinder; + +/// Returns `v.typed_value.`. Only its statistics are used here. +#[derive(Debug, PartialEq, Eq, Hash)] +struct FakeVariantGet(Signature); + +impl ScalarUDFImpl for FakeVariantGet { + fn name(&self) -> &str { + "fake_variant_get" + } + + fn signature(&self) -> &Signature { + &self.0 + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result { + Ok(DataType::Int64) + } + + fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result { + internal_err!("the scan only prunes with statistics, it does not filter rows") + } +} + +/// Reads `fake_variant_get(v, 'key')` bounds from the shredded column, but +/// only for containers where no row fell back to the binary `value` column. +#[derive(Debug)] +struct FakeVariantResolver; + +impl FakeVariantResolver { + /// The column name and key of `fake_variant_get(column, 'key')`. + fn args(expr: &Arc) -> Option<(&str, &str)> { + let func = expr.downcast_ref::()?; + if func.name() != "fake_variant_get" { + return None; + } + let [column, key] = func.args() else { + return None; + }; + let column = column.downcast_ref::()?; + let ScalarValue::Utf8(Some(key)) = key.downcast_ref::()?.value() else { + return None; + }; + Some((column.name(), key.as_str())) + } +} + +impl ParquetStatisticsResolver for FakeVariantResolver { + fn bind( + &self, + expr: &Arc, + _arrow_schema: &Schema, + parquet_schema: &SchemaDescriptor, + ) -> Option> { + let (column, key) = Self::args(expr)?; + let typed = leaf_index_by_path( + parquet_schema, + &[column, "typed_value", key, "typed_value"], + )?; + let fallback = + leaf_index_by_path(parquet_schema, &[column, "typed_value", key, "value"])?; + Some(Arc::new(FakeVariantStatistics { typed, fallback })) + } +} + +/// The leaves of one `fake_variant_get(v, 'key')` in one file. +#[derive(Debug)] +struct FakeVariantStatistics { + typed: usize, + fallback: usize, +} + +impl BoundExprStatistics for FakeVariantStatistics { + fn statistics( + &self, + kind: ExprStatisticsKind, + statistics: &dyn ParquetLeafStatistics, + ) -> Option { + let typed_field = Field::new("typed_value", DataType::Int64, true); + let fallback_field = Field::new("value", DataType::Binary, true); + + let bounds = match kind { + ExprStatisticsKind::Min => statistics.leaf_mins(self.typed, &typed_field)?, + ExprStatisticsKind::Max => statistics.leaf_maxes(self.typed, &typed_field)?, + // A null `typed_value` may hold a value in `value`. + ExprStatisticsKind::NullCount => return None, + }; + // The bounds hold only where every row is shredded, which is where + // the fallback column is null in every row. + let fallback_nulls = + statistics.leaf_null_counts(self.fallback, &fallback_field)?; + let rows = statistics.row_counts()?; + let fallback_nulls = fallback_nulls.as_any().downcast_ref::()?; + let rows = rows.as_any().downcast_ref::()?; + // Unknown counts are null. Treat them as not shredded. + let not_shredded: BooleanArray = fallback_nulls + .iter() + .zip(rows.iter()) + .map(|(nulls, rows)| Some(nulls.is_none() || nulls != rows)) + .collect(); + nullif(&bounds, ¬_shredded).ok() + } +} + +fn shredded_schema() -> SchemaRef { + let a = Fields::from(vec![ + Field::new("value", DataType::Binary, true), + Field::new("typed_value", DataType::Int64, true), + ]); + let typed_value = Fields::from(vec![Field::new("a", DataType::Struct(a), true)]); + let v = Fields::from(vec![Field::new( + "typed_value", + DataType::Struct(typed_value), + true, + )]); + Arc::new(Schema::new(vec![Field::new( + "v", + DataType::Struct(v), + true, + )])) +} + +/// Writes the file described in the module docs, two rows per row group. +fn write_file(schema: &SchemaRef) -> NamedTempFile { + let DataType::Struct(v_fields) = schema.field(0).data_type() else { + unreachable!() + }; + let DataType::Struct(tv_fields) = v_fields[0].data_type() else { + unreachable!() + }; + let DataType::Struct(a_fields) = tv_fields[0].data_type() else { + unreachable!() + }; + let value: ArrayRef = Arc::new(BinaryArray::from(vec![ + None, + None, + None, + None, + None, + Some(100i64.to_le_bytes().as_slice()), + ])); + let typed: ArrayRef = Arc::new(Int64Array::from(vec![ + Some(1), + Some(2), + Some(10), + Some(11), + Some(3), + None, + ])); + let a = StructArray::new(a_fields.clone(), vec![value, typed], None); + let tv = StructArray::new(tv_fields.clone(), vec![Arc::new(a)], None); + let v = StructArray::new(v_fields.clone(), vec![Arc::new(tv)], None); + let batch = RecordBatch::try_new(Arc::clone(schema), vec![Arc::new(v)]).unwrap(); + + let file = NamedTempFile::new().unwrap(); + let props = WriterProperties::builder() + .set_max_row_group_row_count(Some(2)) + .build(); + let mut writer = + ArrowWriter::try_new(file.reopen().unwrap(), Arc::clone(schema), Some(props)) + .unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + file +} + +/// Scans the file with `fake_variant_get(v, 'a') > 5` and returns the +/// (pruned, matched) row group counts from statistics. +async fn row_groups_pruned(register_resolver: bool) -> (usize, usize) { + let schema = shredded_schema(); + let file = write_file(&schema); + let ctx = SessionContext::new(); + + let udf = ScalarUDF::from(FakeVariantGet(Signature::any(2, Volatility::Immutable))); + let predicate = udf.call(vec![col("v"), lit("a")]).gt(lit(5i64)); + let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap(); + let predicate = ctx.create_physical_expr(predicate, &df_schema).unwrap(); + + let mut source = ParquetSource::new(Arc::clone(&schema)).with_predicate(predicate); + if register_resolver { + source = source.with_statistics_resolver(Arc::new(FakeVariantResolver)); + } + let path = file.path().to_str().unwrap().to_string(); + let size = std::fs::metadata(file.path()).unwrap().len(); + let config = + FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), Arc::new(source)) + .with_file(PartitionedFile::new(path, size)) + .build(); + let plan: Arc = DataSourceExec::from_data_source(config); + datafusion::physical_plan::collect(Arc::clone(&plan), ctx.task_ctx()) + .await + .unwrap(); + + let metrics = MetricsFinder::find_metrics(plan.as_ref()).unwrap(); + let Some(MetricValue::PruningMetrics { + pruning_metrics, .. + }) = metrics.sum_by_name("row_groups_pruned_statistics") + else { + panic!("metrics: {metrics:#?}"); + }; + (pruning_metrics.pruned(), pruning_metrics.matched()) +} + +/// Scans the file with a dynamic filter that starts as `true`. After the +/// first batch, the test sets the filter to `fake_variant_get(v, 'a') < 5`. +/// Returns the `row_groups_pruned_dynamic_filter` count. +async fn row_groups_pruned_dynamic(register_resolver: bool) -> usize { + let schema = shredded_schema(); + let file = write_file(&schema); + let ctx = SessionContext::new_with_config(SessionConfig::new().with_batch_size(1)); + + let udf = ScalarUDF::from(FakeVariantGet(Signature::any(2, Volatility::Immutable))); + let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap(); + let column = ctx.create_physical_expr(col("v"), &df_schema).unwrap(); + let filter = Arc::new(DynamicFilterPhysicalExpr::new( + vec![Arc::clone(&column)], + Arc::new(Literal::new(ScalarValue::Boolean(Some(true)))), + )); + + let mut source = ParquetSource::new(Arc::clone(&schema)) + .with_predicate(Arc::clone(&filter) as Arc); + if register_resolver { + source = source.with_statistics_resolver(Arc::new(FakeVariantResolver)); + } + let path = file.path().to_str().unwrap().to_string(); + let size = std::fs::metadata(file.path()).unwrap().len(); + let config = + FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), Arc::new(source)) + .with_file(PartitionedFile::new(path, size)) + .build(); + let plan: Arc = DataSourceExec::from_data_source(config); + let mut stream = plan.execute(0, ctx.task_ctx()).unwrap(); + // The first batch comes from row group 0. + stream.next().await.unwrap().unwrap(); + let predicate = udf.call(vec![col("v"), lit("a")]).lt(lit(5i64)); + filter + .update(ctx.create_physical_expr(predicate, &df_schema).unwrap()) + .unwrap(); + while let Some(batch) = stream.next().await { + batch.unwrap(); + } + + let metrics = MetricsFinder::find_metrics(plan.as_ref()).unwrap(); + metrics + .sum_by_name("row_groups_pruned_dynamic_filter") + .unwrap() + .as_usize() +} + +#[tokio::test] +async fn external_resolver_prunes_row_groups_with_a_dynamic_filter() { + // Row group 1 ([10, 11]) is pruned. Row group 2 is kept because one of + // its rows is not shredded. + assert_eq!(row_groups_pruned_dynamic(true).await, 1); + assert_eq!(row_groups_pruned_dynamic(false).await, 0); +} + +#[tokio::test] +async fn external_resolver_prunes_shredded_row_groups() { + // Row group 0 is pruned. Row group 2 is kept because one of its rows + // is not shredded, even though its shredded max (3) is below 5. + assert_eq!(row_groups_pruned(true).await, (1, 2)); +} + +#[tokio::test] +async fn without_resolver_nothing_is_pruned() { + assert_eq!(row_groups_pruned(false).await, (0, 3)); +} + +/// Matches `TRY_CAST(s['a'] AS Int64)` and reads its bounds from a sidecar +/// leaf `s_a_int64`. The test file has no such leaf. +#[derive(Debug)] +struct SidecarCastResolver; + +impl SidecarCastResolver { + fn is_cast_of_field(expr: &Arc) -> bool { + expr.downcast_ref::().is_some_and(|cast| { + cast.cast_type() == &DataType::Int64 + && cast + .expr() + .downcast_ref::() + .is_some_and(|func| func.name() == "get_field") + }) + } +} + +impl ParquetStatisticsResolver for SidecarCastResolver { + fn bind( + &self, + expr: &Arc, + _arrow_schema: &Schema, + parquet_schema: &SchemaDescriptor, + ) -> Option> { + if !Self::is_cast_of_field(expr) { + return None; + } + let leaf = leaf_index_by_path(parquet_schema, &["s_a_int64"])?; + Some(Arc::new(SidecarStatistics { leaf })) + } +} + +#[derive(Debug)] +struct SidecarStatistics { + leaf: usize, +} + +impl BoundExprStatistics for SidecarStatistics { + fn statistics( + &self, + kind: ExprStatisticsKind, + statistics: &dyn ParquetLeafStatistics, + ) -> Option { + let field = Field::new("s_a_int64", DataType::Int64, true); + match kind { + ExprStatisticsKind::Min => statistics.leaf_mins(self.leaf, &field), + ExprStatisticsKind::Max => statistics.leaf_maxes(self.leaf, &field), + ExprStatisticsKind::NullCount => { + statistics.leaf_null_counts(self.leaf, &field) + } + } + } +} + +/// Writes `s: {a: Int32}` with rows 1, 2, 10, 11, 3, 4, two rows per row +/// group. With `sidecar`, the file also has the leaf `s_a_int64` with the +/// value 4000000000 in every row. Its bounds differ from those of `s.a`. +fn struct_int32_file(sidecar: bool) -> NamedTempFile { + let a = Field::new("a", DataType::Int32, true); + let mut fields = vec![Field::new( + "s", + DataType::Struct(Fields::from(vec![a.clone()])), + true, + )]; + let values: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 10, 11, 3, 4])); + let mut columns: Vec = vec![Arc::new(StructArray::new( + Fields::from(vec![a]), + vec![values], + None, + ))]; + if sidecar { + fields.push(Field::new("s_a_int64", DataType::Int64, true)); + columns.push(Arc::new(Int64Array::from(vec![4_000_000_000; 6]))); + } + let schema = Arc::new(Schema::new(fields)); + let batch = RecordBatch::try_new(Arc::clone(&schema), columns).unwrap(); + let file = NamedTempFile::new().unwrap(); + let props = WriterProperties::builder() + .set_max_row_group_row_count(Some(2)) + .build(); + let mut writer = + ArrowWriter::try_new(file.reopen().unwrap(), schema, Some(props)).unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + file +} + +/// Scans `files` with `TRY_CAST(s['a'] AS Int64) > 3000000000` and +/// `SidecarCastResolver`. Returns the (pruned, matched) row group counts +/// from statistics and the number of rows read. The scan does not filter +/// rows, so the rows read are the rows of the kept row groups. +async fn sidecar_scan(files: &[&NamedTempFile]) -> (usize, usize, usize) { + let a = Field::new("a", DataType::Int32, true); + let schema = Arc::new(Schema::new(vec![ + Field::new("s", DataType::Struct(Fields::from(vec![a])), true), + Field::new("s_a_int64", DataType::Int64, true), + ])); + let ctx = SessionContext::new(); + let df_schema = DFSchema::try_from(Arc::clone(&schema)).unwrap(); + let field = ctx + .create_physical_expr(get_field(col("s"), "a"), &df_schema) + .unwrap(); + // The literal does not fit in Int32, so the simplifier keeps the cast. + let predicate: Arc = Arc::new(BinaryExpr::new( + Arc::new(TryCastExpr::new(field, DataType::Int64)), + Operator::Gt, + Arc::new(Literal::new(ScalarValue::Int64(Some(3_000_000_000)))), + )); + + let source = ParquetSource::new(Arc::clone(&schema)) + .with_predicate(predicate) + .with_statistics_resolver(Arc::new(SidecarCastResolver)); + let mut config = + FileScanConfigBuilder::new(ObjectStoreUrl::local_filesystem(), Arc::new(source)); + for file in files { + let path = file.path().to_str().unwrap().to_string(); + let size = std::fs::metadata(file.path()).unwrap().len(); + config = config.with_file(PartitionedFile::new(path, size)); + } + let plan: Arc = DataSourceExec::from_data_source(config.build()); + let batches = datafusion::physical_plan::collect(Arc::clone(&plan), ctx.task_ctx()) + .await + .unwrap(); + let rows = batches.iter().map(RecordBatch::num_rows).sum(); + + let metrics = MetricsFinder::find_metrics(plan.as_ref()).unwrap(); + let Some(MetricValue::PruningMetrics { + pruning_metrics, .. + }) = metrics.sum_by_name("row_groups_pruned_statistics") + else { + panic!("metrics: {metrics:#?}"); + }; + (pruning_metrics.pruned(), pruning_metrics.matched(), rows) +} + +/// The resolver matches `TRY_CAST(s['a'] AS Int64)`, but the file has no +/// sidecar leaf for it. The pruning predicate then uses the statistics of +/// the inner `s['a']`, and every row group is pruned. +#[tokio::test] +async fn unbound_outer_expression_falls_back_to_inner_statistics() { + let file = struct_int32_file(false); + assert_eq!(sidecar_scan(&[&file]).await, (3, 0, 0)); +} + +/// The file has the sidecar leaf, so the resolver binds the outer +/// expression. Its bounds (4000000000) keep every row group, although the +/// bounds of `s.a` would prune them all. +#[tokio::test] +async fn bound_outer_expression_uses_its_own_statistics() { + let file = struct_int32_file(true); + assert_eq!(sidecar_scan(&[&file]).await, (0, 3, 6)); +} + +/// Each file binds on its own: the file with the sidecar leaf keeps its +/// row groups, and the file without it is pruned with `s.a`. +#[tokio::test] +async fn each_file_binds_the_outer_expression_on_its_own() { + let with_leaf = struct_int32_file(true); + let without_leaf = struct_int32_file(false); + assert_eq!(sidecar_scan(&[&with_leaf, &without_leaf]).await, (3, 3, 6)); +} diff --git a/datafusion/core/tests/parquet/mod.rs b/datafusion/core/tests/parquet/mod.rs index 54482eaa5d02d..62623556bb23f 100644 --- a/datafusion/core/tests/parquet/mod.rs +++ b/datafusion/core/tests/parquet/mod.rs @@ -37,6 +37,7 @@ mod dynamic_row_group_pruning; #[cfg(feature = "parquet_encryption")] mod encryption; mod expr_adapter; +mod expr_statistics_resolver; mod external_access_plan; mod file_statistics; mod filter_pushdown; @@ -47,6 +48,7 @@ mod row_group_pruning; mod schema; mod schema_coercion; mod string_in_list_pruning; +mod struct_field_pruning; mod utils; #[cfg(test)] diff --git a/datafusion/core/tests/parquet/struct_field_pruning.rs b/datafusion/core/tests/parquet/struct_field_pruning.rs new file mode 100644 index 0000000000000..d24809ef7ed2d --- /dev/null +++ b/datafusion/core/tests/parquet/struct_field_pruning.rs @@ -0,0 +1,98 @@ +// 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 + +//! Pruning on struct fields, for files that SQL cannot write. + +use std::io::Write; +use std::sync::Arc; + +use arrow::array::{ArrayRef, Int64Array, RecordBatch, StructArray}; +use arrow::datatypes::{DataType, Field, Fields, Schema}; +use datafusion::prelude::{ParquetReadOptions, SessionContext}; +use datafusion_common::ScalarValue; +use parquet::arrow::ArrowWriter; +use parquet::file::metadata::{ParquetMetaData, ParquetMetaDataWriter}; +use parquet::file::statistics::Statistics; +use parquet::file::writer::TrackedWrite; +use tempfile::NamedTempFile; + +/// Writes `s: {a: Int64}` with rows `{a: 1}` and `{a: null}` in one row +/// group. The footer keeps the min and max of `s.a`, but not its null count. +fn struct_file_without_null_count() -> NamedTempFile { + let a = Field::new("a", DataType::Int64, true); + let schema = Arc::new(Schema::new(vec![Field::new( + "s", + DataType::Struct(Fields::from(vec![a.clone()])), + true, + )])); + let values: ArrayRef = Arc::new(Int64Array::from(vec![Some(1), None])); + let s = StructArray::new(Fields::from(vec![a]), vec![values], None); + let batch = RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(s)]).unwrap(); + let mut bytes = Vec::new(); + let mut writer = ArrowWriter::try_new(&mut bytes, schema, None).unwrap(); + writer.write(&batch).unwrap(); + let metadata = writer.close().unwrap(); + + let group = &metadata.row_groups()[0]; + let column = group.column(0).clone(); + let Statistics::Int64(stats) = column.statistics().unwrap() else { + panic!("expected Int64 statistics"); + }; + let stats = Statistics::int64( + stats.min_opt().copied(), + stats.max_opt().copied(), + None, + None, + false, + ); + let column = column.into_builder().set_statistics(stats).build().unwrap(); + let group = group + .clone() + .into_builder() + .set_column_metadata(vec![column]) + .build() + .unwrap(); + let metadata = ParquetMetaData::new(metadata.file_metadata().clone(), vec![group]); + + // Replace the footer. The encoded rows and their offsets do not change. + let footer_len = + u32::from_le_bytes(bytes[bytes.len() - 8..bytes.len() - 4].try_into().unwrap()); + bytes.truncate(bytes.len() - 8 - footer_len as usize); + let mut file = tempfile::Builder::new() + .suffix(".parquet") + .tempfile() + .unwrap(); + let mut output = TrackedWrite::new(file.as_file_mut()); + output.write_all(&bytes).unwrap(); + ParquetMetaDataWriter::new_with_tracked(output, &metadata) + .finish() + .unwrap(); + file +} + +#[tokio::test] +async fn missing_struct_field_null_count_keeps_row_group() { + // A missing null count is unknown, not zero. `s['a'] IS NULL` must not + // prune the row group. + let file = struct_file_without_null_count(); + let ctx = SessionContext::new(); + ctx.register_parquet( + "t", + file.path().to_str().unwrap(), + ParquetReadOptions::default(), + ) + .await + .unwrap(); + let batches = ctx + .sql("SELECT count(*) FROM t WHERE s['a'] IS NULL") + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!( + ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(), + ScalarValue::Int64(Some(1)), + ); +} diff --git a/datafusion/datasource-parquet/src/bloom_filter.rs b/datafusion/datasource-parquet/src/bloom_filter.rs index d00d513bb1fed..b60fde47ae4e5 100644 --- a/datafusion/datasource-parquet/src/bloom_filter.rs +++ b/datafusion/datasource-parquet/src/bloom_filter.rs @@ -8,9 +8,10 @@ use std::collections::{HashMap, HashSet}; +use crate::statistics_resolver::bound_statistics; use arrow::array::{ArrayRef, BooleanArray}; -use datafusion_common::pruning::PruningStatistics; use datafusion_common::{Column, ScalarValue}; +use datafusion_physical_expr_common::pruning::{PruningStatistics, StatsExpr}; use parquet::basic::Type; use parquet::bloom_filter::Sbbf; use parquet::data_type::Decimal; @@ -23,6 +24,9 @@ use parquet::data_type::Decimal; pub struct BloomFilterStatistics { /// Per-column Bloom filters keyed by predicate column name. column_sbbf: HashMap, + /// Bloom filters for expressions with their own statistics (such as + /// struct fields), by the leaf that the expression is bound to. + expr_sbbf: Vec<(usize, ColumnBloomFilter)>, } #[derive(Debug, Clone)] @@ -45,12 +49,57 @@ impl BloomFilterStatistics { pub fn with_capacity(capacity: usize) -> Self { Self { column_sbbf: HashMap::with_capacity(capacity), + expr_sbbf: vec![], } } /// Returns true if no per-column Bloom filters have been loaded. pub fn is_empty(&self) -> bool { - self.column_sbbf.is_empty() + self.column_sbbf.is_empty() && self.expr_sbbf.is_empty() + } + + /// Add the Bloom filter of the Parquet leaf `leaf`, for the expressions + /// whose binding names it as their bloom filter leaf. + pub(crate) fn insert_for_leaf( + &mut self, + leaf: usize, + sbbf: Sbbf, + ty: Type, + type_length: i32, + ) { + self.expr_sbbf.push(( + leaf, + ColumnBloomFilter { + sbbf, + physical_type: ty, + type_length, + }, + )); + } + + /// `Some(false)` if `filter` proves that none of `values` is present, + /// otherwise `None` (unknown). Never `Some(true)`: a bloom filter cannot + /// prove that a value is present. + #[allow(clippy::allow_attributes, clippy::mutable_key_type)] // ScalarValue has interior mutability but is intentionally used as hash key + fn contains( + filter: &ColumnBloomFilter, + values: &HashSet, + ) -> BooleanArray { + // Bloom filters are probabilistic data structures that can return false + // positives (i.e. it might return true even if the value is not + // present) however, the bloom filter will return `false` if the value is + // definitely not present. + let known_not_present = Self::is_known_not_present( + &filter.sbbf, + values, + &filter.physical_type, + filter.type_length, + ); + // Given the bloom filter is probabilistic, we can't be sure that + // the row group actually contains the values. Return `None` to + // indicate this uncertainty + let contains = if known_not_present { Some(false) } else { None }; + BooleanArray::from(vec![contains]) } /// Add a Bloom filter for the specified column, along with the column's @@ -210,28 +259,18 @@ impl PruningStatistics for BloomFilterStatistics { values: &HashSet, ) -> Option { let column_bloom_filter = self.column_sbbf.get(column.name.as_str())?; + Some(Self::contains(column_bloom_filter, values)) + } - // Bloom filters are probabilistic data structures that can return false - // positives (i.e. it might return true even if the value is not - // present) however, the bloom filter will return `false` if the value is - // definitely not present. - let known_not_present = Self::is_known_not_present( - &column_bloom_filter.sbbf, - values, - &column_bloom_filter.physical_type, - column_bloom_filter.type_length, - ); - - let contains = if known_not_present { - Some(false) - } else { - // Given the bloom filter is probabilistic, we can't be sure that - // the row group actually contains the values. Return `None` to - // indicate this uncertainty - None - }; - - Some(BooleanArray::from(vec![contains])) + /// Like [`Self::contained`], for an expression with its own bloom filter. + fn contained_for_expr( + &self, + expr: &StatsExpr, + values: &HashSet, + ) -> Option { + let leaf = bound_statistics(expr)?.bloom_filter_leaf()?; + let (_, filter) = self.expr_sbbf.iter().find(|(l, _)| *l == leaf)?; + Some(Self::contains(filter, values)) } } @@ -250,6 +289,7 @@ mod tests { use bytes::{BufMut, BytesMut}; use datafusion_common::Result; use datafusion_expr::{Expr, col, lit}; + use datafusion_physical_expr::PhysicalExpr; use datafusion_physical_expr::planner::logical2physical; use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet; use datafusion_pruning::{PruningPredicate, PruningPredicateBuilder}; @@ -259,7 +299,7 @@ mod tests { use parquet::file::properties::{EnabledStatistics, WriterProperties}; fn build_test_pruning_predicate( - expr: Arc, + expr: Arc, schema: Schema, ) -> PruningPredicate { PruningPredicateBuilder::new() diff --git a/datafusion/datasource-parquet/src/mod.rs b/datafusion/datasource-parquet/src/mod.rs index 4bb7166fac1e1..a0d4f950fbfa9 100644 --- a/datafusion/datasource-parquet/src/mod.rs +++ b/datafusion/datasource-parquet/src/mod.rs @@ -33,6 +33,7 @@ mod sort; pub mod source; #[cfg(test)] mod statistics_order_tests; +pub mod statistics_resolver; mod supported_predicates; #[cfg(test)] mod test_util; diff --git a/datafusion/datasource-parquet/src/opener/mod.rs b/datafusion/datasource-parquet/src/opener/mod.rs index 1866b6ba81992..24eea1dae4bd4 100644 --- a/datafusion/datasource-parquet/src/opener/mod.rs +++ b/datafusion/datasource-parquet/src/opener/mod.rs @@ -21,6 +21,9 @@ use crate::push_decoder::{ RowFilterContext, RowGroupPruner, RowGroupReverser, }; use crate::row_group_filter::{RowGroupAccessPlanFilter, row_group_in_range}; +use crate::statistics_resolver::{ + FileStatisticsResolvers, ParquetStatisticsResolvers, bound_statistics, +}; use crate::{ Int96Coercer, ParquetAccessPlan, ParquetFileMetrics, ParquetFileReaderFactory, ParquetRowSelection, ParquetVirtualColumn, RowGroupAccess, @@ -300,6 +303,8 @@ pub(super) struct ParquetMorselizer { /// Whether to also reverse the rows of each row group, making a reversed /// scan exactly ordered. Buffers one decoded row group at a time. pub reverse_rows: bool, + /// Statistics for expressions such as struct field accesses. + pub statistics_resolvers: ParquetStatisticsResolvers, /// Pool charged for the row group a `reverse_rows` scan buffers. pub memory_pool: Option>, /// Optional sort order used to reorder row groups by their min/max statistics. @@ -493,6 +498,7 @@ struct PreparedParquetOpen { row_group_range_assignment: RowGroupRangeAssignment, reverse_row_groups: bool, reverse_rows: bool, + statistics_resolvers: ParquetStatisticsResolvers, memory_pool: Option>, sort_order_for_reorder: Option, preserve_order: bool, @@ -517,6 +523,9 @@ struct FiltersPreparedParquetOpen { loaded: MetadataLoadedParquetOpen, pruning_predicate: Option>, page_pruning_predicate: Option>, + /// The scan's statistics resolvers bound to this file. Every pruning + /// predicate of the file uses them as its matcher. + file_statistics_resolvers: Arc, } /// State of [`ParquetOpenState`] @@ -1002,6 +1011,7 @@ impl ParquetMorselizer { row_group_range_assignment: self.row_group_range_assignment, reverse_row_groups: self.reverse_row_groups, reverse_rows: self.reverse_rows, + statistics_resolvers: self.statistics_resolvers.clone(), memory_pool: self.memory_pool.clone(), sort_order_for_reorder: self.sort_order_for_reorder.clone(), preserve_order: self.preserve_order, @@ -1226,11 +1236,20 @@ impl MetadataLoadedParquetOpen { } // Build predicates for this specific file + let file_statistics_resolvers = Arc::new(FileStatisticsResolvers::new( + prepared.statistics_resolvers.clone(), + Arc::clone(&physical_file_schema), + reader_metadata + .metadata() + .file_metadata() + .schema_descr_ptr(), + )); let pruning_predicate = build_pruning_predicates( prepared.predicate.as_ref(), &physical_file_schema, &prepared.predicate_creation_errors, prepared.max_in_list_size, + Some(&file_statistics_resolvers), ); // Only build page pruning predicate if page index is enabled @@ -1240,6 +1259,7 @@ impl MetadataLoadedParquetOpen { predicate, &physical_file_schema, prepared.max_in_list_size, + Some(&file_statistics_resolvers), ); (p.filter_number() > 0).then_some(p) }) @@ -1255,6 +1275,7 @@ impl MetadataLoadedParquetOpen { }, pruning_predicate, page_pruning_predicate, + file_statistics_resolvers, }) } } @@ -1458,17 +1479,15 @@ impl RowGroupsPrunedParquetOpen { // page index exists before attempting to read it. let arrow_schema = &self.prepared.loaded.prepared.physical_file_schema; let parquet_schema = parquet_metadata.file_metadata().schema_descr(); - Ok(page_pruning_predicate.predicate_column_names().any(|name| { - let Some((leaf_idx, _)) = parquet_column(parquet_schema, arrow_schema, name) - else { - return false; - }; - row_groups.row_group_indexes().any(|rg_idx| { - let column = parquet_metadata.row_group(rg_idx).column(leaf_idx); - column.column_index_offset().is_some() - && column.offset_index_offset().is_some() - }) - })) + Ok(page_pruning_predicate + .predicate_leaf_indexes(arrow_schema, parquet_schema) + .any(|leaf_idx| { + row_groups.row_group_indexes().any(|rg_idx| { + let column = parquet_metadata.row_group(rg_idx).column(leaf_idx); + column.column_index_offset().is_some() + && column.offset_index_offset().is_some() + }) + })) } /// Load the page index if pruning requires it and metadata did not include it. @@ -1524,21 +1543,32 @@ impl RowGroupsPrunedParquetOpen { reader_metadata, ); - let parquet_columns = predicate - .literal_columns() + // Bloom filters of columns, and of struct fields from the leaf + // that their statistics key is bound to. + let parquet_schema = builder.parquet_schema(); + let columns = predicate.literal_columns().into_iter().filter_map(|name| { + let (leaf, _) = parquet_column( + parquet_schema, + &prepared.physical_file_schema, + &name, + )?; + Some((BloomFilterKey::Column(name), leaf)) + }); + let exprs = predicate.literal_exprs().into_iter().filter_map(|expr| { + let leaf = bound_statistics(&expr)?.bloom_filter_leaf()?; + Some((BloomFilterKey::Leaf(leaf), leaf)) + }); + let mut bloom_filter_leaves = columns.chain(exprs).collect::>(); + // Expressions that read the same leaf share its bloom filter. + let mut seen_leaves = HashSet::new(); + bloom_filter_leaves.retain(|(key, leaf)| { + !matches!(key, BloomFilterKey::Leaf(_)) || seen_leaves.insert(*leaf) + }); + let bloom_filter_leaves = bloom_filter_leaves .into_iter() - .filter_map(|column_name| { - let (column_idx, _) = parquet_column( - builder.parquet_schema(), - &prepared.physical_file_schema, - &column_name, - )?; - Some(( - column_name, - column_idx, - builder.parquet_schema().column(column_idx).physical_type(), - builder.parquet_schema().column(column_idx).type_length(), - )) + .map(|(key, leaf)| { + let descr = parquet_schema.column(leaf); + (key, leaf, descr.physical_type(), descr.type_length()) }) .collect::>(); @@ -1551,31 +1581,36 @@ impl RowGroupsPrunedParquetOpen { continue; } let mut bloom_filter_stats = - BloomFilterStatistics::with_capacity(parquet_columns.len()); + BloomFilterStatistics::with_capacity(bloom_filter_leaves.len()); let mut pruned = false; - for (column_name, column_idx, physical_type, type_length) in - &parquet_columns - { - let bf: Sbbf = match builder - .get_row_group_column_bloom_filter(idx, *column_idx) - .await - { - Ok(Some(bf)) => bf, - Ok(None) => continue, - Err(e) => { - debug!("Ignoring error reading bloom filter: {e}"); - prepared.file_metrics.predicate_evaluation_errors.add(1); - continue; - } - }; + for (key, leaf, physical_type, type_length) in &bloom_filter_leaves { + let bf: Sbbf = + match builder.get_row_group_column_bloom_filter(idx, *leaf).await + { + Ok(Some(bf)) => bf, + Ok(None) => continue, + Err(e) => { + debug!("Ignoring error reading bloom filter: {e}"); + prepared.file_metrics.predicate_evaluation_errors.add(1); + continue; + } + }; - bloom_filter_stats.insert( - column_name.clone(), - bf, - *physical_type, - *type_length, - ); + match key { + BloomFilterKey::Column(name) => bloom_filter_stats.insert( + name.clone(), + bf, + *physical_type, + *type_length, + ), + BloomFilterKey::Leaf(leaf) => bloom_filter_stats.insert_for_leaf( + *leaf, + bf, + *physical_type, + *type_length, + ), + } if self.row_groups.prune_row_group_with_bloom_filters( idx, @@ -1604,6 +1639,15 @@ impl RowGroupsPrunedParquetOpen { } } +/// What a Bloom filter read for row group pruning belongs to. +enum BloomFilterKey { + /// A column of the file schema, by name. + Column(String), + /// The leaf of an expression with its own statistics, such as a struct + /// field. The bloom filter statistics find it through the binding. + Leaf(usize), +} + impl RowGroupsPrunedParquetOpen { /// Build the final parquet stream once all pruning work is complete. fn build_stream(self) -> Result>> { @@ -1616,6 +1660,7 @@ impl RowGroupsPrunedParquetOpen { loaded, pruning_predicate: _, page_pruning_predicate, + file_statistics_resolvers, } = prepared; let MetadataLoadedParquetOpen { prepared, @@ -1888,14 +1933,17 @@ impl RowGroupsPrunedParquetOpen { // a threshold change is a single atomic load — not a tree walk per // RG check. let row_group_pruner = match &prepared.predicate { - Some(predicate) if pruner_eligible => Some(RowGroupPruner::new( - Arc::clone(predicate), - Arc::clone(&prepared.physical_file_schema), - Arc::clone(reader_metadata.metadata()), - prepared.predicate_creation_errors.clone(), - prepared.file_metrics.predicate_evaluation_errors.clone(), - prepared.max_in_list_size, - )), + Some(predicate) if pruner_eligible => Some( + RowGroupPruner::new( + Arc::clone(predicate), + Arc::clone(&prepared.physical_file_schema), + Arc::clone(reader_metadata.metadata()), + prepared.predicate_creation_errors.clone(), + prepared.file_metrics.predicate_evaluation_errors.clone(), + prepared.max_in_list_size, + ) + .with_statistics_resolvers(file_statistics_resolvers), + ), _ => None, }; let row_groups_pruned_dynamic = prepared @@ -2099,11 +2147,13 @@ pub(crate) fn build_page_pruning_predicate( predicate: &Arc, file_schema: &SchemaRef, max_in_list_size: usize, + statistics_resolvers: Option<&Arc>, ) -> Arc { - Arc::new(PagePruningAccessPlanFilter::new_with_max_in_list_size( + Arc::new(PagePruningAccessPlanFilter::new_with_statistics_resolvers( predicate, file_schema, max_in_list_size, + statistics_resolvers, )) } @@ -2112,13 +2162,15 @@ pub(crate) fn build_pruning_predicates( file_schema: &SchemaRef, predicate_creation_errors: &Count, max_in_list_size: usize, + statistics_resolvers: Option<&Arc>, ) -> Option> { let predicate = predicate.as_ref()?; - PruningPredicateBuilder::new() + let builder = PruningPredicateBuilder::new() .with_file_schema(Arc::clone(file_schema)) .with_error_counter(predicate_creation_errors) .with_max_in_list_size(max_in_list_size) - .build(Arc::clone(predicate)) + .with_statistics_expr_matcher(statistics_resolvers.cloned().map(|r| r as _)); + builder.build(Arc::clone(predicate)) } /// Returns a `ArrowReaderMetadata` with the page index loaded, loading @@ -2427,7 +2479,12 @@ mod test { ); let page_pruning_predicate = predicate.map(|expr| { let predicate = logical2physical(&expr, &arrow_schema); - build_page_pruning_predicate(&predicate, &arrow_schema, MAX_IN_LIST_SIZE) + build_page_pruning_predicate( + &predicate, + &arrow_schema, + MAX_IN_LIST_SIZE, + None, + ) }); let store: Arc = Arc::new(InMemory::new()); @@ -2444,6 +2501,14 @@ mod test { let options = ArrowReaderOptions::new(); let reader_metadata = ArrowReaderMetadata::try_new(Arc::new(metadata), options.clone()).unwrap(); + let file_statistics_resolvers = Arc::new(FileStatisticsResolvers::new( + Default::default(), + arrow_schema, + reader_metadata + .metadata() + .file_metadata() + .schema_descr_ptr(), + )); let mut open = RowGroupsPrunedParquetOpen { prepared: FiltersPreparedParquetOpen { loaded: MetadataLoadedParquetOpen { @@ -2453,6 +2518,7 @@ mod test { }, pruning_predicate: None, page_pruning_predicate, + file_statistics_resolvers, }, row_groups: RowGroupAccessPlanFilter::new(plan), decoder_read_plans: None, @@ -2714,6 +2780,7 @@ mod test { row_group_range_assignment: self.row_group_range_assignment, reverse_row_groups: self.reverse_row_groups, reverse_rows: self.reverse_rows, + statistics_resolvers: Default::default(), memory_pool: self.memory_pool.clone(), sort_order_for_reorder: None, virtual_state, diff --git a/datafusion/datasource-parquet/src/page_filter.rs b/datafusion/datasource-parquet/src/page_filter.rs index 0e2962e43e451..bc273eb95a3b1 100644 --- a/datafusion/datasource-parquet/src/page_filter.rs +++ b/datafusion/datasource-parquet/src/page_filter.rs @@ -4,6 +4,9 @@ //! Contains code to filter entire pages +use crate::statistics_resolver::{ + ExprStatisticsKind, FileStatisticsResolvers, ParquetLeafStatistics, bound_statistics, +}; use std::collections::HashSet; use std::sync::Arc; @@ -15,15 +18,16 @@ use crate::{ParquetAccessPlan, RowGroupAccess}; use arrow::array::BooleanArray; use arrow::{ array::ArrayRef, - datatypes::{Schema, SchemaRef}, + datatypes::{Field, Schema, SchemaRef}, }; use datafusion_common::ScalarValue; -use datafusion_common::pruning::PruningStatistics; use datafusion_physical_expr::{PhysicalExpr, split_conjunction}; +use datafusion_physical_expr_common::pruning::{PruningStatistics, StatsExpr}; use datafusion_pruning::{MAX_IN_LIST_SIZE, PruningPredicate, PruningPredicateBuilder}; use log::{debug, trace}; use parquet::arrow::arrow_reader::statistics::StatisticsConverter; +use parquet::arrow::parquet_column; use parquet::file::metadata::page_index::PageIndexProvider; use parquet::file::page_index::offset_index::PageLocation; use parquet::schema::types::SchemaDescriptor; @@ -134,6 +138,9 @@ impl PagePruningResult { impl PagePruningAccessPlanFilter { /// Create a new [`PagePruningAccessPlanFilter`] from a physical /// expression, using the default `IN (...)` pruning limit. + /// + /// The filter has no statistics matcher, so only column statistics + /// prune pages. #[expect(clippy::needless_pass_by_value)] pub fn new(expr: &Arc, schema: SchemaRef) -> Self { Self::new_with_max_in_list_size(expr, &schema, MAX_IN_LIST_SIZE) @@ -144,6 +151,17 @@ impl PagePruningAccessPlanFilter { expr: &Arc, schema: &SchemaRef, max_in_list_size: usize, + ) -> Self { + Self::new_with_statistics_resolvers(expr, schema, max_in_list_size, None) + } + + /// Create a page filter that also prunes on the expressions that + /// `statistics_resolvers` provide statistics for. + pub(crate) fn new_with_statistics_resolvers( + expr: &Arc, + schema: &SchemaRef, + max_in_list_size: usize, + statistics_resolvers: Option<&Arc>, ) -> Self { let mut predicates = vec![]; let mut all_predicates_supported = true; @@ -151,11 +169,13 @@ impl PagePruningAccessPlanFilter { // Ordinary pruning can use any supported conjunct. Fully matched // ranges require every original conjunct to be supported. for predicate in split_conjunction(expr) { - let pp = match PruningPredicateBuilder::new() + let builder = PruningPredicateBuilder::new() .with_file_schema(Arc::clone(schema)) .with_max_in_list_size(max_in_list_size) - .try_build(Arc::clone(predicate)) - { + .with_statistics_expr_matcher( + statistics_resolvers.cloned().map(|r| r as _), + ); + let pp = match builder.try_build(Arc::clone(predicate)) { Ok(pp) => pp, Err(e) => { debug!("Ignoring error creating page pruning predicate: {e}"); @@ -170,7 +190,7 @@ impl PagePruningAccessPlanFilter { continue; } - if pp.required_columns().single_column().is_none() { + if pp.required_columns().single_key().is_none() { debug!("Ignoring multi-column page pruning predicate: {predicate}"); all_predicates_supported = false; continue; @@ -256,7 +276,7 @@ impl PagePruningAccessPlanFilter { let inverted = build_inverted_predicate(predicate, arrow_schema)?; inverted .required_columns() - .single_column() + .single_key() .is_some() .then_some(inverted) }) @@ -471,14 +491,23 @@ impl PagePruningAccessPlanFilter { self.predicates.len() } - /// Returns the names of the columns referenced by the page pruning - /// predicates (each predicate references exactly one column, see - /// [`Self::new`]). - pub(crate) fn predicate_column_names(&self) -> impl Iterator { - self.predicates - .iter() - .filter_map(|p| p.required_columns().single_column()) - .map(|c| c.name()) + /// Returns the Parquet leaf column indexes read by the page pruning + /// predicates (each predicate reads exactly one column or expression, + /// see [`Self::new`]). + pub(crate) fn predicate_leaf_indexes<'a>( + &'a self, + arrow_schema: &'a Schema, + parquet_schema: &'a SchemaDescriptor, + ) -> impl Iterator + 'a { + self.predicates.iter().filter_map(move |p| { + match p.required_columns().single_key()? { + (column, None) => { + parquet_column(parquet_schema, arrow_schema, column.name()) + .map(|(leaf, _)| leaf) + } + (_, Some(expr)) => bound_statistics(expr)?.page_index_leaf(), + } + }) } } @@ -605,26 +634,37 @@ fn prune_pages_for_predicate( #[cfg(test)] tests::PAGE_PREDICATE_CALLS.set(tests::PAGE_PREDICATE_CALLS.get() + 1); - let column = predicate.required_columns().single_column()?; - let converter = - match StatisticsConverter::try_new(column.name(), arrow_schema, parquet_schema) { - Ok(converter) => converter, - Err(e) => { - debug!( - "Could not create statistics converter for column {}: {e}", - column.name() - ); - return None; - } - }; + let (column, stats_expr) = predicate.required_columns().single_key()?; + // The converter of an expression key only selects the leaf whose pages + // are pruned. Its values come from the binding, so its Arrow field is + // the type of the expression. + let expr_field; + let converter = match stats_expr { + None => StatisticsConverter::try_new(column.name(), arrow_schema, parquet_schema), + Some(expr) => { + let leaf = bound_statistics(expr)?.page_index_leaf()?; + expr_field = Field::new( + expr.to_string(), + expr.expr().data_type(arrow_schema).ok()?, + true, + ); + StatisticsConverter::from_column_index(leaf, &expr_field, parquet_schema) + } + }; + let converter = match converter { + Ok(converter) => converter, + Err(e) => { + debug!( + "Could not create statistics converter for column {}: {e}", + column.name() + ); + return None; + } + }; - prune_pages_in_one_row_group( - row_group_index, - predicate, - converter, - parquet_metadata, - metrics, - ) + let pruning_stats = + PagesPruningStatistics::try_new(row_group_index, converter, parquet_metadata)?; + prune_pages_in_one_row_group(row_group_index, predicate, &pruning_stats, metrics) } /// Returns a [`RowSelection`] for the rows in this row group to scan, in addition to a vec of @@ -638,17 +678,13 @@ fn prune_pages_for_predicate( fn prune_pages_in_one_row_group( row_group_index: usize, pruning_predicate: &PruningPredicate, - converter: StatisticsConverter<'_>, - parquet_metadata: &ParquetMetaData, + pruning_stats: &PagesPruningStatistics<'_>, metrics: &ParquetFileMetrics, ) -> Option<(RowSelection, Vec)> { - let pruning_stats = - PagesPruningStatistics::try_new(row_group_index, converter, parquet_metadata)?; - // Each element in values is a boolean indicating whether the page may have // values that match the predicate (true) or could not possibly have values // that match the predicate (false). - let values = match pruning_predicate.prune(&pruning_stats) { + let values = match pruning_predicate.prune(pruning_stats) { Ok(values) => values, Err(e) => { debug!("Error evaluating page index predicate values {e}"); @@ -706,6 +742,9 @@ struct PagesPruningStatistics<'a> { page_index: &'a dyn PageIndexProvider, page_offsets: &'a Vec, trusted_min_max: bool, + /// The Parquet leaf whose pages are pruned + leaf: usize, + parquet_schema: &'a SchemaDescriptor, } impl<'a> PagesPruningStatistics<'a> { @@ -757,6 +796,8 @@ impl<'a> PagesPruningStatistics<'a> { page_index, page_offsets, trusted_min_max, + leaf: parquet_column_index, + parquet_schema: file_metadata.schema_descr(), }) } @@ -781,7 +822,60 @@ impl<'a> PagesPruningStatistics<'a> { Some(vec) } } + +/// Page statistics are only known for the leaf whose pages are pruned, +/// because the pages of other leaves do not line up with them. +impl ParquetLeafStatistics for PagesPruningStatistics<'_> { + fn leaf_mins(&self, leaf: usize, field: &Field) -> Option { + if leaf != self.leaf || !self.trusted_min_max { + return None; + } + StatisticsConverter::from_column_index(leaf, field, self.parquet_schema) + .ok()? + .data_page_mins(self.page_index, [&self.row_group_index]) + .ok() + } + + fn leaf_maxes(&self, leaf: usize, field: &Field) -> Option { + if leaf != self.leaf || !self.trusted_min_max { + return None; + } + StatisticsConverter::from_column_index(leaf, field, self.parquet_schema) + .ok()? + .data_page_maxes(self.page_index, [&self.row_group_index]) + .ok() + } + + fn leaf_null_counts(&self, leaf: usize, field: &Field) -> Option { + if leaf != self.leaf { + return None; + } + let counts = + StatisticsConverter::from_column_index(leaf, field, self.parquet_schema) + .ok()? + .data_page_null_counts(self.page_index, [&self.row_group_index]) + .ok()?; + Some(Arc::new(counts)) + } + + fn row_counts(&self) -> Option { + PruningStatistics::row_counts(self) + } +} + impl PruningStatistics for PagesPruningStatistics<'_> { + fn min_values_for_expr(&self, expr: &StatsExpr) -> Option { + bound_statistics(expr)?.statistics(ExprStatisticsKind::Min, self) + } + + fn max_values_for_expr(&self, expr: &StatsExpr) -> Option { + bound_statistics(expr)?.statistics(ExprStatisticsKind::Max, self) + } + + fn null_counts_for_expr(&self, expr: &StatsExpr) -> Option { + bound_statistics(expr)?.statistics(ExprStatisticsKind::NullCount, self) + } + fn min_values(&self, _column: &datafusion_common::Column) -> Option { if !self.trusted_min_max { return None; diff --git a/datafusion/datasource-parquet/src/pruning.rs b/datafusion/datasource-parquet/src/pruning.rs index 8e3d79bf1ba3e..a5a27b9740218 100644 --- a/datafusion/datasource-parquet/src/pruning.rs +++ b/datafusion/datasource-parquet/src/pruning.rs @@ -40,11 +40,24 @@ pub(crate) fn build_inverted_predicate( .then_with(|| a.name().cmp(b.name())) }); - for column in columns { + // A matched expression such as `s['a']` can be NULL when its root column + // is not nullable, so every matched expression gets its own `IS NULL`. + let mut null_operands: Vec> = columns + .into_iter() + .map(|column| Arc::new(column) as Arc) + .collect(); + null_operands.extend( + predicate + .stats_key_exprs() + .iter() + .map(|key| Arc::clone(key.expr())), + ); + + for operand in null_operands { inverted_expr = Arc::new(BinaryExpr::new( inverted_expr, Operator::Or, - Arc::new(IsNullExpr::new(Arc::new(column))), + Arc::new(IsNullExpr::new(operand)), )); } @@ -53,6 +66,7 @@ pub(crate) fn build_inverted_predicate( PruningPredicateBuilder::new() .with_file_schema(Arc::clone(predicate.schema())) .with_max_in_list_size(predicate.max_in_list_size()) + .with_statistics_expr_matcher(predicate.statistics_expr_matcher().cloned()) .try_build(inverted_expr) .ok() } diff --git a/datafusion/datasource-parquet/src/push_decoder.rs b/datafusion/datasource-parquet/src/push_decoder.rs index aa0d299d22560..892a888635f87 100644 --- a/datafusion/datasource-parquet/src/push_decoder.rs +++ b/datafusion/datasource-parquet/src/push_decoder.rs @@ -22,6 +22,7 @@ //! The opener constructs both halves and hands the state off to //! [`PushDecoderStreamState::into_stream`] for consumption. +use crate::statistics_resolver::FileStatisticsResolvers; use std::collections::VecDeque; use std::sync::Arc; @@ -175,6 +176,8 @@ pub(crate) struct RowGroupPruner { /// container-level pruning. Sourced from /// `datafusion.execution.parquet.max_in_list_size`. max_in_list_size: usize, + /// Statistics for expressions such as struct field accesses. + statistics_resolvers: Option>, } impl RowGroupPruner { @@ -197,9 +200,20 @@ impl RowGroupPruner { predicate_creation_errors, predicate_evaluation_errors, max_in_list_size, + statistics_resolvers: None, } } + /// Use `statistics_resolvers` for the statistics of expressions such as + /// struct field accesses, as the scan's row group pruning does. + pub(crate) fn with_statistics_resolvers( + mut self, + statistics_resolvers: Arc, + ) -> Self { + self.statistics_resolvers = Some(statistics_resolvers); + self + } + /// Returns `true` when the statistics for `row_group_indices` prove that /// every requested row group can be skipped under the current value of /// the dynamic predicate. @@ -221,11 +235,14 @@ impl RowGroupPruner { .watcher() .is_some_and(|tracker| tracker.changed()); if self.needs_initial_build || dynamic_changed { - self.pruning_predicate = PruningPredicateBuilder::new() + let builder = PruningPredicateBuilder::new() .with_file_schema(Arc::clone(&self.arrow_schema)) .with_error_counter(&self.predicate_creation_errors) .with_max_in_list_size(self.max_in_list_size) - .build(Arc::clone(&self.predicate)); + .with_statistics_expr_matcher( + self.statistics_resolvers.clone().map(|r| r as _), + ); + self.pruning_predicate = builder.build(Arc::clone(&self.predicate)); self.needs_initial_build = false; } diff --git a/datafusion/datasource-parquet/src/row_group_filter.rs b/datafusion/datasource-parquet/src/row_group_filter.rs index 97600a7ae374a..1909916558e66 100644 --- a/datafusion/datasource-parquet/src/row_group_filter.rs +++ b/datafusion/datasource-parquet/src/row_group_filter.rs @@ -9,13 +9,16 @@ use super::{ParquetAccessPlan, ParquetFileMetrics, RowGroupAccess}; use crate::bloom_filter::BloomFilterStatistics; use crate::metadata::{has_untrusted_byte_array_stats, has_untrusted_min_max_order}; use crate::pruning::build_inverted_predicate; +use crate::statistics_resolver::{ + ExprStatisticsKind, ParquetLeafStatistics, bound_statistics, +}; use arrow::array::{ArrayRef, BooleanArray, UInt64Array}; use arrow::compute::nullif; -use arrow::datatypes::Schema; +use arrow::datatypes::{Field, Schema}; use datafusion_common::parquet_config::RowGroupRangeAssignment; -use datafusion_common::pruning::PruningStatistics; use datafusion_common::{Column, Result, ScalarValue}; use datafusion_datasource::FileRange; +use datafusion_physical_expr_common::pruning::{PruningStatistics, StatsExpr}; use datafusion_pruning::PruningPredicate; use parquet::arrow::arrow_reader::statistics::StatisticsConverter; use parquet::basic::ColumnOrder; @@ -65,7 +68,7 @@ pub(crate) fn row_group_in_range( impl RowGroupAccessPlanFilter { /// Create a new `RowGroupPlanBuilder` for pruning out the groups to scan - /// based on metadata and statistics + /// based on metadata and statistics. pub fn new(access_plan: ParquetAccessPlan) -> Self { Self { access_plan } } @@ -598,7 +601,58 @@ impl<'a> RowGroupPruningStatistics<'a> { } } +impl ParquetLeafStatistics for RowGroupPruningStatistics<'_> { + fn leaf_mins(&self, leaf: usize, field: &Field) -> Option { + if has_untrusted_min_max_order(self.parquet_schema, self.column_orders, leaf) { + return None; + } + let converter = + StatisticsConverter::from_column_index(leaf, field, self.parquet_schema) + .ok()?; + let values = converter.row_group_mins(self.metadata_iter()).ok()?; + self.mask_untrusted_byte_array_stats(Some(leaf), values) + } + + fn leaf_maxes(&self, leaf: usize, field: &Field) -> Option { + if has_untrusted_min_max_order(self.parquet_schema, self.column_orders, leaf) { + return None; + } + let converter = + StatisticsConverter::from_column_index(leaf, field, self.parquet_schema) + .ok()?; + let values = converter.row_group_maxes(self.metadata_iter()).ok()?; + self.mask_untrusted_byte_array_stats(Some(leaf), values) + } + + fn leaf_null_counts(&self, leaf: usize, field: &Field) -> Option { + let counts = + StatisticsConverter::from_column_index(leaf, field, self.parquet_schema) + .ok()? + // Missing counts cannot rule out nulls. + .with_missing_null_counts_as_zero(false) + .row_group_null_counts(self.metadata_iter()) + .ok()?; + Some(Arc::new(counts)) + } + + fn row_counts(&self) -> Option { + PruningStatistics::row_counts(self) + } +} + impl PruningStatistics for RowGroupPruningStatistics<'_> { + fn min_values_for_expr(&self, expr: &StatsExpr) -> Option { + bound_statistics(expr)?.statistics(ExprStatisticsKind::Min, self) + } + + fn max_values_for_expr(&self, expr: &StatsExpr) -> Option { + bound_statistics(expr)?.statistics(ExprStatisticsKind::Max, self) + } + + fn null_counts_for_expr(&self, expr: &StatsExpr) -> Option { + bound_statistics(expr)?.statistics(ExprStatisticsKind::NullCount, self) + } + fn min_values(&self, column: &Column) -> Option { let converter = self.min_max_statistics_converter(column)?; let values = converter.row_group_mins(self.metadata_iter()).ok()?; diff --git a/datafusion/datasource-parquet/src/source.rs b/datafusion/datasource-parquet/src/source.rs index 62a003d24fa5c..c4cd425f8461e 100644 --- a/datafusion/datasource-parquet/src/source.rs +++ b/datafusion/datasource-parquet/src/source.rs @@ -3,6 +3,8 @@ // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements //! ParquetSource implementation for reading parquet files +use crate::statistics_resolver::{FileStatisticsResolvers, ParquetStatisticsResolvers}; +use parquet::arrow::ArrowSchemaConverter; use std::fmt::Debug; use std::fmt::Formatter; use std::sync::Arc; @@ -316,6 +318,9 @@ pub struct ParquetSource { /// /// [`ParquetOptions::enable_exact_reverse_scan`]: datafusion_common::config::ParquetOptions::enable_exact_reverse_scan reverse_rows: bool, + /// Statistics for expressions such as struct field accesses, used for + /// row group and page pruning. + statistics_resolvers: ParquetStatisticsResolvers, /// Pool charged for the row group a `reverse_rows` scan buffers. Set by /// [`FileSource::with_memory_pool`] when the scan is opened. memory_pool: Option>, @@ -349,6 +354,7 @@ impl ParquetSource { encryption_factory: None, reverse_row_groups: false, reverse_rows: false, + statistics_resolvers: ParquetStatisticsResolvers::default(), memory_pool: None, sort_order_for_reorder: None, } @@ -479,6 +485,21 @@ impl ParquetSource { self.table_parquet_options.global.enable_page_index } + /// Add a [`ParquetStatisticsResolver`], which provides statistics for + /// expressions such as `variant_get(v, 'a')` from Parquet leaf + /// statistics, so that predicates on them can prune row groups. + /// + /// The built-in resolver for struct fields is always present. + /// + /// [`ParquetStatisticsResolver`]: crate::statistics_resolver::ParquetStatisticsResolver + pub fn with_statistics_resolver( + mut self, + resolver: Arc, + ) -> Self { + self.statistics_resolvers = self.statistics_resolvers.with_resolver(resolver); + self + } + /// If enabled, the reader will read by the bloom filter pub fn with_bloom_filter_on_read(mut self, bloom_filter_on_read: bool) -> Self { self.table_parquet_options.global.bloom_filter_on_read = bloom_filter_on_read; @@ -660,6 +681,7 @@ impl FileSource for ParquetSource { .row_group_range_assignment, reverse_row_groups: self.reverse_row_groups, reverse_rows: self.reverse_rows, + statistics_resolvers: self.statistics_resolvers.clone(), memory_pool: self.memory_pool.clone(), sort_order_for_reorder: self.sort_order_for_reorder.clone(), virtual_state, @@ -824,11 +846,25 @@ impl FileSource for ParquetSource { // Instead, we use the logical schema of the file (the table schema without partition columns). if let Some(predicate) = &self.predicate { let predicate_creation_errors = Count::new(); + // Bind the resolvers to the Parquet schema that a file + // written with the logical schema would have. + let file_schema = self.table_schema.file_schema(); + let statistics_resolvers = ArrowSchemaConverter::new() + .convert(file_schema) + .ok() + .map(|parquet_schema| { + Arc::new(FileStatisticsResolvers::new( + self.statistics_resolvers.clone(), + Arc::clone(file_schema), + Arc::new(parquet_schema), + )) + }); if let Some(pruning_predicate) = build_pruning_predicates( Some(predicate), - self.table_schema.table_schema(), + file_schema, &predicate_creation_errors, self.max_in_list_size(), + statistics_resolvers.as_ref(), ) { let mut guarantees = pruning_predicate .literal_guarantees() @@ -1165,12 +1201,14 @@ impl FileSource for ParquetSource { encryption_factory: _, reverse_row_groups, reverse_rows, + // Custom resolvers require a custom codec for serialization. + statistics_resolvers, // Runtime only: set when the scan is opened. memory_pool: _, sort_order_for_reorder, } = self; - if schema_provider.is_some() { + if schema_provider.is_some() || statistics_resolvers.has_custom_resolvers() { return Ok(None); } diff --git a/datafusion/datasource-parquet/src/statistics_order_tests.rs b/datafusion/datasource-parquet/src/statistics_order_tests.rs index c3ae36f5d9302..efe94fc9f9cf7 100644 --- a/datafusion/datasource-parquet/src/statistics_order_tests.rs +++ b/datafusion/datasource-parquet/src/statistics_order_tests.rs @@ -10,12 +10,12 @@ use std::sync::Arc; use arrow::array::{BooleanArray, record_batch}; use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; use bytes::Bytes; -use datafusion_common::pruning::{PrunableStatistics, PruningStatistics}; use datafusion_common::stats::Precision; use datafusion_common::{Column, ScalarValue, Statistics}; use datafusion_expr::{Expr, col, lit}; use datafusion_physical_expr::PhysicalExpr; use datafusion_physical_expr::planner::logical2physical; +use datafusion_physical_expr_common::pruning::{PrunableStatistics, PruningStatistics}; use datafusion_physical_plan::metrics::{Count, ExecutionPlanMetricsSet}; use datafusion_pruning::{MAX_IN_LIST_SIZE, PruningPredicate, PruningPredicateBuilder}; use parquet::arrow::ArrowWriter; @@ -396,6 +396,7 @@ fn large_string_in_list_preserves_rows_with_untrusted_page_order() { &physical, &file.schema, max_in_list_size, + None, ); assert_eq!(page_filter.filter_number(), 1); let all = ParquetAccessPlan::new_all(file.metadata.num_row_groups()); diff --git a/datafusion/datasource-parquet/src/statistics_resolver.rs b/datafusion/datasource-parquet/src/statistics_resolver.rs new file mode 100644 index 0000000000000..ab738b22708f5 --- /dev/null +++ b/datafusion/datasource-parquet/src/statistics_resolver.rs @@ -0,0 +1,349 @@ +// 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::bind +//! keeps the binding in StatsExpr <-- -> first resolver whose `bind` +//! returns a binding +//! min_values_for_expr(stats_expr) ----> RowGroupPruningStatistics / PagesPruningStatistics +//! -> the 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::any::Any; +use std::fmt::Debug; +use std::sync::Arc; + +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, StatsExpr}; +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; + + /// Maximum values of the Parquet leaf column `leaf`. See + /// [`Self::leaf_mins`]. + fn leaf_maxes(&self, leaf: usize, field: &Field) -> Option; + + /// 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; + + /// Row counts, as a `UInt64Array`. + fn row_counts(&self) -> Option; +} + +/// 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. + /// + /// 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`. + /// + /// The pruning predicates of a file call `bind` for many nodes of each + /// predicate, and again for each dynamic filter update. So a resolver + /// must reject an expression that it does not handle cheaply, for + /// example with one downcast. + /// + /// `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, + arrow_schema: &Schema, + parquet_schema: &SchemaDescriptor, + ) -> Option>; +} + +/// 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; + + /// 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 { + 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 { + 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>, +} + +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, + ) -> 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; + +/// [`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 predicate stores that binding in the key's [`StatsExpr`], and the +/// pruning statistics read the values from it (see [`bound_statistics`]). +/// So the key and its statistics always agree, and nothing looks the +/// expression up again. +#[derive(Debug)] +pub(crate) struct FileStatisticsResolvers { + resolvers: ParquetStatisticsResolvers, + arrow_schema: SchemaRef, + parquet_schema: SchemaDescPtr, +} + +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, + } + } +} + +/// 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 { + /// The binding of the first resolver that binds `expr`. + fn bind(&self, expr: &Arc) -> Option> { + let bound: BoundStatistics = self + .resolvers + .resolvers + .iter() + .find_map(|r| r.bind(expr, &self.arrow_schema, &self.parquet_schema))?; + Some(Arc::new(bound)) + } +} + +/// The binding that [`FileStatisticsResolvers`] created for `expr`, or +/// `None` when another matcher created it. +pub(crate) fn bound_statistics(expr: &StatsExpr) -> Option<&BoundStatistics> { + expr.binding::() +} + +/// 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 { + 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; + +impl GetFieldStatisticsResolver { + /// The root column and field path of `expr`, including chained calls + /// such as `get_field(get_field(s, 'a'), 'b')`. + fn path(expr: &Arc) -> Option<(&Column, Vec<&str>)> { + let func = ScalarFunctionExpr::try_downcast_func::(expr.as_ref())?; + let (base, keys) = func.args().split_first()?; + let (column, mut path) = match base.downcast_ref::() { + Some(column) => (column, vec![]), + None => Self::path(base)?, + }; + for key in keys { + match key.downcast_ref::()?.value() { + ScalarValue::Utf8(Some(name)) + | ScalarValue::LargeUtf8(Some(name)) + | ScalarValue::Utf8View(Some(name)) => path.push(name.as_str()), + _ => return None, + } + } + (!path.is_empty()).then_some((column, path)) + } + + /// The Parquet leaf index and Arrow field of `expr`. + fn leaf<'a>( + expr: &Arc, + arrow_schema: &'a Schema, + parquet_schema: &SchemaDescriptor, + ) -> Option<(usize, &'a Field)> { + let (column, path) = Self::path(expr)?; + let mut field = arrow_schema.field_with_name(column.name()).ok()?; + for name in &path { + let DataType::Struct(fields) = field.data_type() else { + return None; + }; + field = fields.iter().find(|f| f.name() == name)?; + } + if field.data_type().is_nested() { + return None; + } + let mut parts = vec![column.name()]; + parts.extend(path); + let leaf = leaf_index_by_path(parquet_schema, &parts)?; + (parquet_schema.column(leaf).max_rep_level() == 0).then_some((leaf, field)) + } +} + +impl ParquetStatisticsResolver for GetFieldStatisticsResolver { + fn bind( + &self, + expr: &Arc, + arrow_schema: &Schema, + parquet_schema: &SchemaDescriptor, + ) -> Option> { + let (leaf, field) = Self::leaf(expr, arrow_schema, parquet_schema)?; + Some(Arc::new(StructFieldStatistics { + leaf, + field: field.clone(), + })) + } +} + +/// The statistics of a struct field, read from its Parquet leaf. +#[derive(Debug)] +struct StructFieldStatistics { + leaf: usize, + field: Field, +} + +impl BoundExprStatistics for StructFieldStatistics { + fn statistics( + &self, + kind: ExprStatisticsKind, + statistics: &dyn ParquetLeafStatistics, + ) -> Option { + match kind { + ExprStatisticsKind::Min => statistics.leaf_mins(self.leaf, &self.field), + ExprStatisticsKind::Max => statistics.leaf_maxes(self.leaf, &self.field), + ExprStatisticsKind::NullCount => { + statistics.leaf_null_counts(self.leaf, &self.field) + } + } + } + + fn page_index_leaf(&self) -> Option { + Some(self.leaf) + } + + /// A struct field leaf holds every non-null value of the field. + fn bloom_filter_leaf(&self) -> Option { + Some(self.leaf) + } +} diff --git a/datafusion/physical-expr-common/Cargo.toml b/datafusion/physical-expr-common/Cargo.toml index 0ed6b10e8cd9a..1259d9735e834 100644 --- a/datafusion/physical-expr-common/Cargo.toml +++ b/datafusion/physical-expr-common/Cargo.toml @@ -45,6 +45,7 @@ datafusion-proto-models = { workspace = true, optional = true } hashbrown = { workspace = true } indexmap = { workspace = true } itertools = { workspace = true } +log = { workspace = true } parking_lot = { workspace = true } pin-project = { workspace = true } regex = { workspace = true } diff --git a/datafusion/physical-expr-common/src/lib.rs b/datafusion/physical-expr-common/src/lib.rs index fa26461c774c0..6d317233031cb 100644 --- a/datafusion/physical-expr-common/src/lib.rs +++ b/datafusion/physical-expr-common/src/lib.rs @@ -22,6 +22,7 @@ pub mod binary_view_map; pub mod datum; pub mod metrics; pub mod physical_expr; +pub mod pruning; pub mod regex; pub mod sort_expr; pub mod tree_node; diff --git a/datafusion/common/src/pruning.rs b/datafusion/physical-expr-common/src/pruning.rs similarity index 90% rename from datafusion/common/src/pruning.rs rename to datafusion/physical-expr-common/src/pruning.rs index 7e13b6a30e865..755d03ebc5315 100644 --- a/datafusion/common/src/pruning.rs +++ b/datafusion/physical-expr-common/src/pruning.rs @@ -5,13 +5,79 @@ use arrow::array::{Array, NullArray, UInt64Array}; use arrow::array::{ArrayRef, BooleanArray}; use arrow::datatypes::{FieldRef, Schema, SchemaRef}; +use std::any::Any; use std::collections::HashSet; +use std::fmt; +use std::hash::{Hash, Hasher}; use std::sync::Arc; -use crate::error::DataFusionError; -use crate::stats::Precision; -use crate::{Column, Statistics}; -use crate::{ColumnStatistics, ScalarValue}; +use crate::physical_expr::PhysicalExpr; +use datafusion_common::error::DataFusionError; +use datafusion_common::stats::Precision; +use datafusion_common::{Column, Statistics}; +use datafusion_common::{ColumnStatistics, ScalarValue}; + +/// An expression that has its own statistics, such as `get_field(s, 'a')`, +/// together with the binding that the statistics source returned for it. +/// +/// The source creates the binding when the pruning predicate asks whether +/// `expr` has statistics. The predicate then passes the same value back to +/// the `*_for_expr` methods of [`PruningStatistics`]. So the source reads the +/// statistics from its own binding and does not look `expr` up again. +/// +/// Two values are equal when their expressions are equal. The binding is +/// not compared. +#[derive(Clone)] +pub struct StatsExpr { + expr: Arc, + binding: Arc, +} + +impl StatsExpr { + /// Creates a statistics key for `expr` with the source's `binding`. + pub fn new(expr: Arc, binding: Arc) -> Self { + Self { expr, binding } + } + + /// The expression, for example `get_field(s, 'a')`. + pub fn expr(&self) -> &Arc { + &self.expr + } + + /// The binding as `T`, or `None` when another source created it. + /// + /// Only the type identifies the source, so a source must bind a private + /// type. + pub fn binding(&self) -> Option<&T> { + self.binding.downcast_ref() + } +} + +impl fmt::Debug for StatsExpr { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("StatsExpr").field(&self.expr).finish() + } +} + +impl fmt::Display for StatsExpr { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.expr.fmt(f) + } +} + +impl PartialEq for StatsExpr { + fn eq(&self, other: &Self) -> bool { + self.expr.eq(&other.expr) + } +} + +impl Eq for StatsExpr {} + +impl Hash for StatsExpr { + fn hash(&self, state: &mut H) { + self.expr.hash(state); + } +} /// A source of runtime statistical information to [`PruningPredicate`]s. /// @@ -127,6 +193,59 @@ pub trait PruningStatistics { column: &Column, values: &HashSet, ) -> Option; + + /// Return the minimum values of the expression `expr`, if known. + /// + /// `expr` is an expression that the pruning predicate treats as having + /// its own statistics instead of being computed from column statistics. + /// Examples are a struct field access `get_field(s, 'a')`, or a shredded + /// variant access `variant_get(v, 'a')`. It carries the binding that this + /// source created for it (see [`StatsExpr`]). Columns in the expression + /// refer to the schema the pruning predicate was built with. + /// + /// The contract matches [`Self::min_values`]: each non-null entry must + /// be a lower bound for every non-null value of `expr` in its container. + /// + /// The default returns `None`, so pruning keeps every container. + fn min_values_for_expr(&self, _expr: &StatsExpr) -> Option { + None + } + + /// Return the maximum values of the expression `expr`, if known. + /// + /// See [`Self::min_values_for_expr`]. + fn max_values_for_expr(&self, _expr: &StatsExpr) -> Option { + None + } + + /// Return the number of rows where `expr` evaluates to null, if known. + /// + /// See [`Self::min_values_for_expr`]. + fn null_counts_for_expr(&self, _expr: &StatsExpr) -> Option { + None + } + + /// Returns what is known about the literal `values` in the expression + /// `expr`, as [`Self::contained`] does for a column. + /// + /// For each container: + /// * `true` if every value of `expr` is one of `values` + /// * `false` if no value of `expr` is any of `values` + /// * `null` if neither is known + /// + /// Return `null`, never `false` or `true`, for a container that the + /// source cannot answer. Pruning negates the result for `NOT IN`, so a + /// guessed `false` would prune wrongly there. + /// + /// The default returns `None`. + #[allow(clippy::allow_attributes, clippy::mutable_key_type)] // ScalarValue has interior mutability but is intentionally used as hash key + fn contained_for_expr( + &self, + _expr: &StatsExpr, + _values: &HashSet, + ) -> Option { + None + } } /// Prune files based on their partition values. @@ -191,7 +310,7 @@ impl PartitionPruningStatistics { /// # use std::sync::Arc; /// # use datafusion_common::ScalarValue; /// # use arrow::datatypes::{DataType, Field}; - /// # use datafusion_common::pruning::PartitionPruningStatistics; + /// # use datafusion_physical_expr_common::pruning::PartitionPruningStatistics; /// /// let partition_values = vec![ /// vec![ScalarValue::from(1i32), ScalarValue::from(2i32)], @@ -519,13 +638,42 @@ impl PruningStatistics for CompositePruningStatistics { } None } + + fn min_values_for_expr(&self, expr: &StatsExpr) -> Option { + self.statistics + .iter() + .find_map(|stats| stats.min_values_for_expr(expr)) + } + + fn max_values_for_expr(&self, expr: &StatsExpr) -> Option { + self.statistics + .iter() + .find_map(|stats| stats.max_values_for_expr(expr)) + } + + fn null_counts_for_expr(&self, expr: &StatsExpr) -> Option { + self.statistics + .iter() + .find_map(|stats| stats.null_counts_for_expr(expr)) + } + + #[allow(clippy::allow_attributes, clippy::mutable_key_type)] // ScalarValue has interior mutability but is intentionally used as hash key + fn contained_for_expr( + &self, + expr: &StatsExpr, + values: &HashSet, + ) -> Option { + self.statistics + .iter() + .find_map(|stats| stats.contained_for_expr(expr, values)) + } } #[cfg(test)] #[expect(deprecated)] #[allow(clippy::allow_attributes, clippy::mutable_key_type)] // ScalarValue has interior mutability but is intentionally used as hash key mod tests { - use crate::{ + use datafusion_common::{ ColumnStatistics, cast::{as_int32_array, as_uint64_array}, }; diff --git a/datafusion/pruning/Cargo.toml b/datafusion/pruning/Cargo.toml index 0d6e6e49c01d0..f9081f357f839 100644 --- a/datafusion/pruning/Cargo.toml +++ b/datafusion/pruning/Cargo.toml @@ -32,6 +32,7 @@ log = { workspace = true } [dev-dependencies] criterion = { workspace = true } datafusion-expr = { workspace = true } +datafusion-functions = { workspace = true } datafusion-functions-nested = { workspace = true } insta = { workspace = true } itertools = { workspace = true } diff --git a/datafusion/pruning/src/file_pruner.rs b/datafusion/pruning/src/file_pruner.rs index 85e43049ed7ce..129f4a536f062 100644 --- a/datafusion/pruning/src/file_pruner.rs +++ b/datafusion/pruning/src/file_pruner.rs @@ -7,10 +7,11 @@ use std::sync::Arc; use arrow::datatypes::{FieldRef, SchemaRef}; -use datafusion_common::{Result, internal_datafusion_err, pruning::PrunableStatistics}; +use datafusion_common::{Result, internal_datafusion_err}; use datafusion_datasource::PartitionedFile; use datafusion_physical_expr::DynamicFilterTracking; use datafusion_physical_expr_common::physical_expr::PhysicalExpr; +use datafusion_physical_expr_common::pruning::PrunableStatistics; use datafusion_physical_plan::metrics::Count; use log::debug; diff --git a/datafusion/pruning/src/lib.rs b/datafusion/pruning/src/lib.rs index 40be3376c86c8..41ec66f220c15 100644 --- a/datafusion/pruning/src/lib.rs +++ b/datafusion/pruning/src/lib.rs @@ -14,5 +14,6 @@ mod string_in_list; pub use file_pruner::FilePruner; pub use pruning_predicate::{ MAX_IN_LIST_SIZE, PredicateRewriter, PruningPredicate, PruningPredicateBuilder, - PruningStatistics, RequiredColumns, UnhandledPredicateHook, build_pruning_predicate, + PruningStatistics, RequiredColumns, StatisticsExprMatcher, StatsExpr, + UnhandledPredicateHook, build_pruning_predicate, }; diff --git a/datafusion/pruning/src/pruning_predicate.rs b/datafusion/pruning/src/pruning_predicate.rs index b7325d90d5672..a0c46490e9c36 100644 --- a/datafusion/pruning/src/pruning_predicate.rs +++ b/datafusion/pruning/src/pruning_predicate.rs @@ -6,6 +6,7 @@ //! based on statistics (e.g. Parquet Row Groups) //! //! [`Expr`]: https://docs.rs/datafusion/latest/datafusion/logical_expr/enum.Expr.html +use std::any::Any; use std::collections::HashSet; use std::sync::Arc; @@ -21,8 +22,8 @@ use arrow::{ record_batch::{RecordBatch, RecordBatchOptions}, }; // pub use for backwards compatibility -pub use datafusion_common::pruning::PruningStatistics; use datafusion_physical_expr::simplifier::PhysicalExprSimplifier; +pub use datafusion_physical_expr_common::pruning::{PruningStatistics, StatsExpr}; use datafusion_physical_plan::metrics::Count; use log::{debug, trace}; @@ -35,7 +36,7 @@ use datafusion_common::{ }; use datafusion_expr_common::casts::try_cast_literal_to_type; use datafusion_expr_common::operator::Operator; -use datafusion_physical_expr::utils::{Guarantee, LiteralGuarantee}; +use datafusion_physical_expr::utils::{Guarantee, LiteralGuarantee, collect_columns}; use datafusion_physical_expr::{PhysicalExprRef, expressions as phys_expr}; use datafusion_physical_expr_common::physical_expr::snapshot_physical_expr_opt; use datafusion_physical_plan::joins::HashTableLookupExpr; @@ -369,10 +370,17 @@ pub struct PruningPredicate { /// /// See [`PruningPredicate::literal_guarantees`] for more details. literal_guarantees: Vec, + /// Like `literal_guarantees`, for expressions with their own statistics + /// (see [`StatisticsExprMatcher`]). + expr_literal_guarantees: Vec, /// Maximum IN-list size used to build this predicate. max_in_list_size: usize, /// Whether its logical inverse can safely prove every row matches. can_be_inverted_for_full_match: bool, + /// Decides which expressions have their own statistics. + statistics_expr_matcher: Option>, + /// The distinct expressions in `orig_expr` that are statistics keys. + stats_key_exprs: Vec, } #[derive(Default)] @@ -416,6 +424,7 @@ pub struct PruningPredicateBuilder<'a> { file_schema: Option, error_counter: Option<&'a Count>, max_in_list_size: usize, + statistics_expr_matcher: Option>, } impl<'a> PruningPredicateBuilder<'a> { @@ -425,9 +434,24 @@ impl<'a> PruningPredicateBuilder<'a> { file_schema: None, error_counter: None, max_in_list_size: MAX_IN_LIST_SIZE, + statistics_expr_matcher: None, } } + /// Treat the expressions that `matcher` accepts as having their own + /// statistics, read through [`PruningStatistics::min_values_for_expr`] + /// and related methods. + /// + /// Without a matcher (`None`, the default), only columns have + /// statistics. + pub fn with_statistics_expr_matcher( + mut self, + matcher: Option>, + ) -> Self { + self.statistics_expr_matcher = matcher; + self + } + /// Set the schema of the container that will be pruned (typically the /// parquet file schema). pub fn with_file_schema(mut self, file_schema: SchemaRef) -> Self { @@ -533,19 +557,25 @@ impl<'a> PruningPredicateBuilder<'a> { // build predicate expression once let mut required_columns = RequiredColumns::new(); let mut properties = PruningExpressionProperties::default(); + let ctx = PredicateBuildContext { + schema: &file_schema, + unhandled_hook: &unhandled_hook, + max_in_list_size: self.max_in_list_size, + statistics_expr_matcher: self.statistics_expr_matcher.as_deref(), + }; let predicate_expr = build_predicate_expression( &predicate, - &file_schema, + &ctx, &mut required_columns, - &unhandled_hook, - self.max_in_list_size, &mut properties, ); let predicate_schema = required_columns.schema(); // Simplify the newly created predicate to get rid of redundant casts, comparisons, etc. let predicate_expr = PhysicalExprSimplifier::new(&predicate_schema).simplify(predicate_expr)?; - let literal_guarantees = LiteralGuarantee::analyze(&predicate); + let (literal_guarantees, expr_literal_guarantees) = + analyze_literal_guarantees(&predicate, &ctx); + let stats_key_exprs = collect_stats_key_exprs(&predicate, &ctx); Ok(PruningPredicate { schema: file_schema, @@ -553,12 +583,51 @@ impl<'a> PruningPredicateBuilder<'a> { required_columns, orig_expr: predicate, literal_guarantees, + expr_literal_guarantees, max_in_list_size: self.max_in_list_size, can_be_inverted_for_full_match: !properties.has_filter_semantics_only, + statistics_expr_matcher: self.statistics_expr_matcher, + stats_key_exprs, }) } } +/// Decides which expressions have their own statistics. +/// +/// A statistics source can know statistics for an expression that pruning +/// cannot compute from column statistics. For example, Parquet stores +/// statistics for each struct field, so it knows the bounds of +/// `get_field(s, 'a')`. A matcher tells [`PruningPredicate`] to treat such an +/// expression as one unit and ask the source for its statistics. +/// +/// The matcher runs while the predicate is built. A source can build one +/// matcher per file and match only the expressions that the file has +/// statistics for. When the matcher rejects an expression, the predicate +/// looks for keys in its children. For example, `CAST(e AS Int64)` can use +/// the statistics of `e`. A source may still return `None` for a matched +/// expression, and then nothing is pruned for it. +/// +/// The binding that the matcher returns is the only link between a key and +/// its statistics. The source finds its binding again with +/// [`StatsExpr::binding`], which checks only the type. So use a private type +/// for the binding: two sources that bind a common type, such as `()` or +/// an Arrow array, could read each other's bindings in a composite source. +pub trait StatisticsExprMatcher: std::fmt::Debug + Send + Sync { + /// Returns a binding if `expr` is a statistics key, or `None` to let the + /// predicate use keys inside `expr` instead. + /// + /// The predicate stores the binding in a [`StatsExpr`] and passes it to + /// the `*_for_expr` methods of [`PruningStatistics`]. The source reads the + /// statistics from the binding, so it never looks `expr` up again. + /// + /// The predicate calls `bind` for many nodes of the predicate while it is + /// built, so rejecting an expression must be cheap. + /// + /// Pruning only uses a bound expression that reads exactly one column + /// and has a non-nested type. + fn bind(&self, expr: &Arc) -> Option>; +} + /// Rewrites predicates that [`PredicateRewriter`] can not handle, e.g. certain /// complex expressions or predicates that reference columns that are not in the /// schema. @@ -679,6 +748,25 @@ impl PruningPredicate { } } + for ExprLiteralGuarantee { + expr, + guarantee, + literals, + } in &self.expr_literal_guarantees + { + if let Some(results) = statistics.contained_for_expr(expr, literals) { + match guarantee { + Guarantee::In => builder.combine_array(&results), + Guarantee::NotIn => { + builder.combine_array(&arrow::compute::not(&results)?) + } + } + if builder.check_all_pruned() { + return Ok(builder.build()); + } + } + } + // Next, try to prove the predicate can't be true for the containers based // on min/max values @@ -717,6 +805,21 @@ impl PruningPredicate { &self.literal_guarantees } + /// Returns the distinct expressions with their own statistics (see + /// [`StatisticsExprMatcher`]) that have literal guarantees, such as + /// `get_field(s, 'a')` for `get_field(s, 'a') = 5`. Like + /// [`Self::literal_guarantees`], all of the guarantees must hold for the + /// expression to possibly be `true`. Use this list for example to load only the bloom filters a predicate can use. + pub fn literal_exprs(&self) -> Vec { + let mut exprs: Vec = vec![]; + for guarantee in &self.expr_literal_guarantees { + if !exprs.contains(&guarantee.expr) { + exprs.push(guarantee.expr.clone()); + } + } + exprs + } + /// Returns true if this pruning predicate can not prune anything. /// /// This happens if the predicate is a literal `true` and @@ -724,7 +827,9 @@ impl PruningPredicate { /// /// This can happen when a predicate is simplified to a constant `true` pub fn always_true(&self) -> bool { - is_always_true(&self.predicate_expr) && self.literal_guarantees.is_empty() + is_always_true(&self.predicate_expr) + && self.literal_guarantees.is_empty() + && self.expr_literal_guarantees.is_empty() } /// Returns the configured maximum IN-list size used to build this predicate. @@ -732,6 +837,18 @@ impl PruningPredicate { self.max_in_list_size } + /// The matcher this predicate was built with, if any. + pub fn statistics_expr_matcher(&self) -> Option<&Arc> { + self.statistics_expr_matcher.as_ref() + } + + /// Returns the distinct expressions of the original predicate that are + /// statistics keys (see [`StatisticsExprMatcher`]), such as + /// `get_field(s, 'a')`. Columns are not included. + pub fn stats_key_exprs(&self) -> &[StatsExpr] { + &self.stats_key_exprs + } + /// Returns whether pruning the logical inverse can safely prove that every /// row in a container satisfies the original predicate. pub fn can_be_inverted_for_full_match(&self) -> bool { @@ -761,6 +878,111 @@ impl PruningPredicate { } } +/// A [`LiteralGuarantee`] on an expression with its own statistics, such as +/// `get_field(s, 'a') IN (1, 2)`. +#[derive(Debug, Clone)] +struct ExprLiteralGuarantee { + /// The expression, for example `get_field(s, 'a')` + expr: StatsExpr, + /// Whether `expr` must, or must not, be one of `literals` + guarantee: Guarantee, + /// The literal values + literals: HashSet, +} + +/// Prefix of the placeholder columns that stand in for statistics keys +/// while [`LiteralGuarantee::analyze`] runs. +const STATS_EXPR_PLACEHOLDER: &str = "__datafusion_pruning_stats_expr_"; + +/// Returns the literal guarantees of `predicate` on columns and on matched +/// expressions. +/// +/// [`LiteralGuarantee::analyze`] only understands columns. Each distinct +/// matched expression is replaced with a placeholder column of a reserved +/// name, so that the analysis treats it as one column, and the placeholder +/// guarantees are mapped back to their expressions. +fn analyze_literal_guarantees( + predicate: &Arc, + ctx: &PredicateBuildContext, +) -> (Vec, Vec) { + // A real column with a placeholder name would be mistaken for a key. + if ctx.statistics_expr_matcher.is_none() + || collect_columns(predicate) + .iter() + .any(|c| c.name().starts_with(STATS_EXPR_PLACEHOLDER)) + { + return (LiteralGuarantee::analyze(predicate), vec![]); + } + let mut keys: Vec = vec![]; + let replaced = Arc::clone(predicate) + .transform_down(|expr| { + let Some(StatsKey { + expr: Some(key), .. + }) = matched_stats_key(&expr, ctx) + else { + return Ok(Transformed::no(expr)); + }; + let idx = keys.iter().position(|k| k == &key).unwrap_or_else(|| { + keys.push(key.clone()); + keys.len() - 1 + }); + let placeholder = + phys_expr::Column::new(&format!("{STATS_EXPR_PLACEHOLDER}{idx}"), 0); + Ok(Transformed::new( + Arc::new(placeholder), + true, + TreeNodeRecursion::Jump, + )) + }) + .data(); + let Ok(replaced) = replaced else { + return (LiteralGuarantee::analyze(predicate), vec![]); + }; + let mut column_guarantees = vec![]; + let mut expr_guarantees = vec![]; + for guarantee in LiteralGuarantee::analyze(&replaced) { + match guarantee + .column + .name + .strip_prefix(STATS_EXPR_PLACEHOLDER) + .and_then(|idx| idx.parse::().ok()) + .and_then(|idx| keys.get(idx)) + { + Some(key) => expr_guarantees.push(ExprLiteralGuarantee { + expr: key.clone(), + guarantee: guarantee.guarantee, + literals: guarantee.literals, + }), + None => column_guarantees.push(guarantee), + } + } + (column_guarantees, expr_guarantees) +} + +/// Returns the distinct expressions in `predicate` that are statistics keys, +/// outermost first. The children of a key are not searched. +fn collect_stats_key_exprs( + predicate: &Arc, + ctx: &PredicateBuildContext, +) -> Vec { + let mut keys: Vec = vec![]; + predicate + .apply(|expr| { + let Some(StatsKey { + expr: Some(key), .. + }) = matched_stats_key(expr, ctx) + else { + return Ok(TreeNodeRecursion::Continue); + }; + if !keys.contains(&key) { + keys.push(key); + } + Ok(TreeNodeRecursion::Jump) + }) + .expect("the visitor never fails"); + keys +} + /// Builds the return `Vec` for [`PruningPredicate::prune`]. #[derive(Debug)] struct BoolVecBuilder { @@ -857,6 +1079,11 @@ pub struct RequiredColumns { /// * The field the statistics value should be placed in for /// pruning predicate evaluation (e.g. `min_value` or `max_value`) columns: Vec<(phys_expr::Column, StatisticsType, Field)>, + /// The expression of each entry in `columns`, at the same index, when + /// the statistics are for an expression with its own statistics (such + /// as `get_field(s, 'a')`) rather than for the column itself. The + /// column in `columns` is then the one column the expression reads. + stats_exprs: Vec>, } impl RequiredColumns { @@ -873,6 +1100,12 @@ impl RequiredColumns { /// * `a > 5 OR b < 10` returns `None` /// * `true` returns None pub fn single_column(&self) -> Option<&phys_expr::Column> { + // An expression with its own statistics is not the column itself, so + // callers that read per-column statistics (such as the page index) + // must not treat it as one. + if self.stats_exprs.iter().any(Option::is_some) { + return None; + } if self.columns.windows(2).all(|w| { // check if all columns are the same (ignoring statistics and field) let c1 = &w[0].0; @@ -885,6 +1118,21 @@ impl RequiredColumns { } } + /// Returns `Some((column, expr))` if every statistic of this predicate is + /// for the same column or the same expression. + /// + /// Unlike [`Self::single_column`], this accepts an expression with its + /// own statistics (see [`StatisticsExprMatcher`]). `expr` is `None` for + /// the column itself. + pub fn single_key(&self) -> Option<(&phys_expr::Column, Option<&StatsExpr>)> { + let (first, rest) = self.columns.split_first()?; + let first_expr = self.stats_exprs[0].as_ref(); + rest.iter() + .zip(&self.stats_exprs[1..]) + .all(|((c, _, _), e)| c == &first.0 && e.as_ref() == first_expr) + .then_some((&first.0, first_expr)) + } + /// Returns a schema that describes the columns required to evaluate this /// pruning predicate. /// The schema contains the fields for each column in `self.columns` with @@ -908,9 +1156,16 @@ impl RequiredColumns { self.columns.iter() } + /// Drops entries appended after the first `len`. + fn truncate(&mut self, len: usize) { + self.columns.truncate(len); + self.stats_exprs.truncate(len); + } + fn find_stat_column( &self, column: &phys_expr::Column, + stats_expr: Option<&StatsExpr>, statistics_type: StatisticsType, ) -> Option { match statistics_type { @@ -926,32 +1181,39 @@ impl RequiredColumns { .columns .iter() .enumerate() - .find(|(_i, (c, t, _f))| c == column && t == &statistics_type) + .find(|(i, (c, t, _f))| { + c == column + && t == &statistics_type + && self.stats_exprs[*i].as_ref() == stats_expr + }) .map(|(i, (_c, _t, _f))| i), } } - /// Rewrites column_expr so that all appearances of column - /// are replaced with a reference to either the min or max - /// statistics column, while keeping track that a reference to the statistics - /// column is required + /// Rewrites `column_expr` so that every appearance of `key` (a column, + /// or an expression with its own statistics) is replaced with a + /// reference to its `stat_type` statistics column, and records that the + /// statistics column is required. /// - /// for example, an expression like `col("foo") > 5`, when called - /// with Max would result in an expression like `col("foo_max") > - /// 5` with the appropriate entry noted in self.columns - fn stat_column_expr( + /// For example, `col("foo") > 5` with Max becomes `col("foo_max") > 5`. + fn stat_key_expr( &mut self, - column: &phys_expr::Column, + key: &StatsKey, column_expr: &Arc, field: &Field, stat_type: StatisticsType, ) -> Result> { - let (idx, need_to_insert) = match self.find_stat_column(column, stat_type) { - Some(idx) => (idx, false), - None => (self.columns.len(), true), - }; + let column = &key.column; + let (idx, need_to_insert) = + match self.find_stat_column(column, key.expr.as_ref(), stat_type) { + Some(idx) => (idx, false), + None => (self.columns.len(), true), + }; - let column_name = column.name(); + let column_name = match &key.expr { + None => column.name().to_string(), + Some(expr) => expr.expr().to_string(), + }; let stat_column_name = match stat_type { StatisticsType::Min => format!("{column_name}_min"), StatisticsType::Max => format!("{column_name}_max"), @@ -968,54 +1230,24 @@ impl RequiredColumns { let stat_field = Field::new(stat_column.name(), field.data_type().clone(), nullable); self.columns.push((column.clone(), stat_type, stat_field)); + self.stats_exprs.push(key.expr.clone()); + } + match &key.expr { + None => rewrite_column_expr(Arc::clone(column_expr), column, &stat_column), + Some(expr) => { + rewrite_stats_expr(Arc::clone(column_expr), expr.expr(), &stat_column) + } } - rewrite_column_expr(Arc::clone(column_expr), column, &stat_column) - } - - /// rewrite col --> col_min - fn min_column_expr( - &mut self, - column: &phys_expr::Column, - column_expr: &Arc, - field: &Field, - ) -> Result> { - self.stat_column_expr(column, column_expr, field, StatisticsType::Min) - } - - /// rewrite col --> col_max - fn max_column_expr( - &mut self, - column: &phys_expr::Column, - column_expr: &Arc, - field: &Field, - ) -> Result> { - self.stat_column_expr(column, column_expr, field, StatisticsType::Max) - } - - /// rewrite col --> col_null_count - fn null_count_column_expr( - &mut self, - column: &phys_expr::Column, - column_expr: &Arc, - field: &Field, - ) -> Result> { - self.stat_column_expr(column, column_expr, field, StatisticsType::NullCount) - } - - /// rewrite col --> col_row_count - fn row_count_column_expr( - &mut self, - column: &phys_expr::Column, - column_expr: &Arc, - field: &Field, - ) -> Result> { - self.stat_column_expr(column, column_expr, field, StatisticsType::RowCount) } } impl From> for RequiredColumns { fn from(columns: Vec<(phys_expr::Column, StatisticsType, Field)>) -> Self { - Self { columns } + let stats_exprs = vec![None; columns.len()]; + Self { + columns, + stats_exprs, + } } } @@ -1050,17 +1282,25 @@ fn build_statistics_record_batch( ) -> Result { let mut arrays = Vec::::with_capacity(required_columns.columns.len()); // For each needed statistics column: - for (column, statistics_type, stat_field) in required_columns.iter() { + for ((column, statistics_type, stat_field), stats_expr) in required_columns + .iter() + .zip(required_columns.stats_exprs.iter()) + { let column = Column::from_name(column.name()); let data_type = stat_field.data_type(); let num_containers = statistics.num_containers(); - let array = match statistics_type { - StatisticsType::Min => statistics.min_values(&column), - StatisticsType::Max => statistics.max_values(&column), - StatisticsType::NullCount => statistics.null_counts(&column), - StatisticsType::RowCount => statistics.row_counts(), + let array = match (statistics_type, stats_expr) { + (StatisticsType::Min, None) => statistics.min_values(&column), + (StatisticsType::Max, None) => statistics.max_values(&column), + (StatisticsType::NullCount, None) => statistics.null_counts(&column), + (StatisticsType::Min, Some(expr)) => statistics.min_values_for_expr(expr), + (StatisticsType::Max, Some(expr)) => statistics.max_values_for_expr(expr), + (StatisticsType::NullCount, Some(expr)) => { + statistics.null_counts_for_expr(expr) + } + (StatisticsType::RowCount, _) => statistics.row_counts(), }; let array = array.unwrap_or_else(|| new_null_array(data_type, num_containers)); @@ -1092,11 +1332,11 @@ fn build_statistics_record_batch( } struct PruningExpressionBuilder<'a> { - column: phys_expr::Column, + key: StatsKey, column_expr: Arc, op: Operator, scalar_expr: Arc, - field: &'a Field, + field: Field, required_columns: &'a mut RequiredColumns, } @@ -1111,15 +1351,15 @@ impl<'a> PruningExpressionBuilder<'a> { required_columns: &'a mut RequiredColumns, ) -> Result { // find column name; input could be a more complicated expression - let (column_expr, scalar_expr, column, correct_operator) = match ( + let (column_expr, scalar_expr, key, correct_operator) = match ( left_columns, right_columns, ) { - (ColumnReferenceCount::One(column), ColumnReferenceCount::Zero) => { - (left, right, column, op) + (ColumnReferenceCount::One(key), ColumnReferenceCount::Zero) => { + (left, right, key, op) } - (ColumnReferenceCount::Zero, ColumnReferenceCount::One(column)) => { - (right, left, column, reverse_operator(op)?) + (ColumnReferenceCount::Zero, ColumnReferenceCount::One(key)) => { + (right, left, key, reverse_operator(op)?) } (ColumnReferenceCount::One(_), ColumnReferenceCount::One(_)) => { // both sides have one column - not supported @@ -1140,14 +1380,17 @@ impl<'a> PruningExpressionBuilder<'a> { } }; - let (column_expr, correct_operator, scalar_expr) = - rewrite_expr_to_prunable(column_expr, correct_operator, scalar_expr, schema)?; - let Some((_, field)) = schema.column_with_name(column.name()) else { - return plan_err!("Field not found in schema"); - }; + let (column_expr, correct_operator, scalar_expr) = rewrite_expr_to_prunable( + column_expr, + correct_operator, + scalar_expr, + schema, + key.expr.as_ref().map(StatsExpr::expr), + )?; + let field = key.field(schema)?; Ok(Self { - column, + key, column_expr, op: correct_operator, scalar_expr, @@ -1165,13 +1408,21 @@ impl<'a> PruningExpressionBuilder<'a> { } fn min_column_expr(&mut self) -> Result> { - self.required_columns - .min_column_expr(&self.column, &self.column_expr, self.field) + self.required_columns.stat_key_expr( + &self.key, + &self.column_expr, + &self.field, + StatisticsType::Min, + ) } fn max_column_expr(&mut self) -> Result> { - self.required_columns - .max_column_expr(&self.column, &self.column_expr, self.field) + self.required_columns.stat_key_expr( + &self.key, + &self.column_expr, + &self.field, + StatisticsType::Max, + ) } /// This function is to simply retune the `null_count` physical expression no matter what the @@ -1181,16 +1432,16 @@ impl<'a> PruningExpressionBuilder<'a> { /// cast(x as int) < 10 => x_null_count, /// try_cast(x as float) < 10.0 => x_null_count fn null_count_column_expr(&mut self) -> Result> { - // Retune to [`phys_expr::Column`] - let column_expr = Arc::new(self.column.clone()) as _; + let key_expr = self.key.to_expr(); // null_count is DataType::UInt64, which is different from the column's data type (i.e. self.field) - let null_count_field = &Field::new(self.field.name(), DataType::UInt64, true); + let null_count_field = Field::new(self.field.name(), DataType::UInt64, true); - self.required_columns.null_count_column_expr( - &self.column, - &column_expr, - null_count_field, + self.required_columns.stat_key_expr( + &self.key, + &key_expr, + &null_count_field, + StatisticsType::NullCount, ) } @@ -1201,16 +1452,16 @@ impl<'a> PruningExpressionBuilder<'a> { /// cast(x as int) < 10 => x_row_count, /// try_cast(x as float) < 10.0 => x_row_count fn row_count_column_expr(&mut self) -> Result> { - // Retune to [`phys_expr::Column`] - let column_expr = Arc::new(self.column.clone()) as _; + let key_expr = self.key.to_expr(); // row_count is DataType::UInt64, which is different from the column's data type (i.e. self.field) - let row_count_field = &Field::new(self.field.name(), DataType::UInt64, true); + let row_count_field = Field::new(self.field.name(), DataType::UInt64, true); - self.required_columns.row_count_column_expr( - &self.column, - &column_expr, - row_count_field, + self.required_columns.stat_key_expr( + &self.key, + &key_expr, + &row_count_field, + StatisticsType::RowCount, ) } } @@ -1232,13 +1483,15 @@ fn rewrite_expr_to_prunable( op: Operator, scalar_expr: &PhysicalExprRef, schema: &Schema, + key_expr: Option<&PhysicalExprRef>, ) -> Result<(PhysicalExprRef, Operator, PhysicalExprRef)> { if !is_compare_op(op) { return plan_err!("rewrite_expr_to_prunable only support compare expression"); } - if column_expr.downcast_ref::().is_some() { - // `col op lit()` + if is_stats_leaf(column_expr, key_expr) { + // `col op lit()`, or `expr op lit()` for an expression with its own + // statistics Ok((Arc::clone(column_expr), op, Arc::clone(scalar_expr))) } else if let Some(cast) = column_expr.downcast_ref::() { // `cast(col) op lit()` @@ -1248,16 +1501,13 @@ fn rewrite_expr_to_prunable( op, scalar_expr, schema, + key_expr, )?; let left = Arc::new(phys_expr::CastExpr::new_with_target_field( left, Arc::clone(cast.target_field()), None, )); - // PruningPredicate does not support pruning on nested fields yet. - // End-to-end nested-field pruning also requires Parquet statistics - // extraction to agree with PruningPredicate on a stats representation - // for nested field expressions. Ok((left, op, right)) } else if let Some(try_cast) = column_expr.downcast_ref::() { // `try_cast(col) op lit()` @@ -1267,6 +1517,7 @@ fn rewrite_expr_to_prunable( op, scalar_expr, schema, + key_expr, )?; let left = Arc::new(phys_expr::TryCastExpr::new( left, @@ -1276,7 +1527,7 @@ fn rewrite_expr_to_prunable( } else if let Some(neg) = column_expr.downcast_ref::() { // `-col > lit()` --> `col < -lit()` let (left, op, right) = - rewrite_expr_to_prunable(neg.arg(), op, scalar_expr, schema)?; + rewrite_expr_to_prunable(neg.arg(), op, scalar_expr, schema, key_expr)?; let right = Arc::new(phys_expr::NegativeExpr::new(right)); Ok((left, reverse_operator(op)?, right)) } else if let Some(not) = column_expr.downcast_ref::() { @@ -1292,7 +1543,7 @@ fn rewrite_expr_to_prunable( "Not with operator other than Eq / NotEq / IsDistinctFrom / IsNotDistinctFrom is not supported" ); } - if not.arg().downcast_ref::().is_some() { + if is_stats_leaf(not.arg(), key_expr) { let left = Arc::clone(not.arg()); let right = Arc::new(phys_expr::NotExpr::new(Arc::clone(scalar_expr))); Ok((left, reverse_operator(op)?, right)) @@ -1310,9 +1561,19 @@ fn rewrite_cast_child_to_prunable( op: Operator, scalar_expr: &PhysicalExprRef, schema: &Schema, + key_expr: Option<&PhysicalExprRef>, ) -> Result<(PhysicalExprRef, Operator, PhysicalExprRef)> { verify_support_type_for_prune(&cast_child_expr.data_type(schema)?, cast_type)?; - rewrite_expr_to_prunable(cast_child_expr, op, scalar_expr, schema) + rewrite_expr_to_prunable(cast_child_expr, op, scalar_expr, schema, key_expr) +} + +/// Whether `expr` is what statistics are read for: a column, or `key_expr` +/// (an expression with its own statistics). +fn is_stats_leaf(expr: &PhysicalExprRef, key_expr: Option<&PhysicalExprRef>) -> bool { + match key_expr { + Some(key_expr) => expr == key_expr, + None => expr.downcast_ref::().is_some(), + } } fn is_compare_op(op: Operator) -> bool { @@ -1376,6 +1637,25 @@ fn rewrite_column_expr( .data() } +/// Replaces every occurrence of `stats_expr` in `e` with `column_new`. +fn rewrite_stats_expr( + e: Arc, + stats_expr: &Arc, + column_new: &phys_expr::Column, +) -> Result> { + e.transform_down(|expr| { + if &expr == stats_expr { + return Ok(Transformed::new( + Arc::new(column_new.clone()), + true, + TreeNodeRecursion::Jump, + )); + } + Ok(Transformed::no(expr)) + }) + .data() +} + fn reverse_operator(op: Operator) -> Result { op.swap().ok_or_else(|| { internal_datafusion_err!( @@ -1389,21 +1669,23 @@ fn reverse_operator(op: Operator) -> Result { /// if the column may contain values, and false if definitely does not /// contain values fn build_single_column_expr( - column: &phys_expr::Column, + key: &StatsKey, schema: &Schema, required_columns: &mut RequiredColumns, is_not: bool, // if true, treat as !col ) -> Option> { - let field = schema.field_with_name(column.name()).ok()?; + // The type of the expression, not of its root column: a boolean struct + // field has a struct root. + let field = key.field(schema).ok()?; if *field.data_type() == DataType::Boolean { - let col_ref = Arc::new(column.clone()) as _; + let key_expr = key.to_expr(); let min = required_columns - .min_column_expr(column, &col_ref, field) + .stat_key_expr(key, &key_expr, &field, StatisticsType::Min) .ok()?; let max = required_columns - .max_column_expr(column, &col_ref, field) + .stat_key_expr(key, &key_expr, &field, StatisticsType::Max) .ok()?; // remember -- we want an expression that is: @@ -1435,47 +1717,48 @@ fn build_single_column_expr( /// thus can prune the row group / value fn build_is_null_column_expr( expr: &Arc, - schema: &Schema, + ctx: &PredicateBuildContext, required_columns: &mut RequiredColumns, with_not: bool, ) -> Option> { - if let Some(col) = expr.downcast_ref::() { - let field = schema.field_with_name(col.name()).ok()?; - - let null_count_field = &Field::new(field.name(), DataType::UInt64, true); - if with_not { - if let Ok(row_count_expr) = - required_columns.row_count_column_expr(col, expr, null_count_field) - { - required_columns - .null_count_column_expr(col, expr, null_count_field) - .map(|null_count_column_expr| { - // IsNotNull(column) => null_count != row_count - Arc::new(phys_expr::BinaryExpr::new( - null_count_column_expr, - Operator::NotEq, - row_count_expr, - )) as _ - }) - .ok() - } else { - None - } - } else { - required_columns - .null_count_column_expr(col, expr, null_count_field) - .map(|null_count_column_expr| { - // IsNull(column) => null_count > 0 - Arc::new(phys_expr::BinaryExpr::new( - null_count_column_expr, - Operator::Gt, - Arc::new(phys_expr::Literal::new(ScalarValue::UInt64(Some(0)))), - )) as _ - }) - .ok() - } + let key = as_stats_key(expr, ctx)?; + let name = key.field(ctx.schema).ok()?.name().clone(); + let null_count_field = &Field::new(name, DataType::UInt64, true); + if with_not { + let row_count_expr = required_columns + .stat_key_expr(&key, expr, null_count_field, StatisticsType::RowCount) + .ok()?; + let null_count_expr = required_columns + .stat_key_expr(&key, expr, null_count_field, StatisticsType::NullCount) + .ok()?; + // IsNotNull(column) => null_count != row_count + Some(Arc::new(phys_expr::BinaryExpr::new( + null_count_expr, + Operator::NotEq, + row_count_expr, + ))) } else { - None + let null_count_expr = required_columns + .stat_key_expr(&key, expr, null_count_field, StatisticsType::NullCount) + .ok()?; + // IsNull(column) => null_count > 0 + Some(Arc::new(phys_expr::BinaryExpr::new( + null_count_expr, + Operator::Gt, + Arc::new(phys_expr::Literal::new(ScalarValue::UInt64(Some(0)))), + ))) + } +} + +/// Returns the [`StatsKey`] for `expr` if it is a column, or an expression +/// that `matcher` gives its own statistics. +fn as_stats_key( + expr: &Arc, + ctx: &PredicateBuildContext, +) -> Option { + match expr.downcast_ref::() { + Some(column) => Some(StatsKey::column(column.clone())), + None => matched_stats_key(expr, ctx), } } @@ -1498,34 +1781,36 @@ impl CompactInListDomain { /// Statistics expressions for `column`: its min, its max, and "not every row is /// NULL". Appends to `required_columns`, rolling the appends back if any part -/// cannot be built, since [`RequiredColumns::stat_column_expr`] only appends. +/// cannot be built, since [`RequiredColumns::stat_key_expr`] only appends. fn min_max_non_null_exprs( - column: &phys_expr::Column, + key: &StatsKey, column_expr: &Arc, field: &Field, - schema: &Schema, + ctx: &PredicateBuildContext, required_columns: &mut RequiredColumns, ) -> Option<(PhysicalExprRef, PhysicalExprRef, PhysicalExprRef)> { let appended = required_columns.columns.len(); let statistics = (|| { let min = required_columns - .min_column_expr(column, column_expr, field) + .stat_key_expr(key, column_expr, field, StatisticsType::Min) .ok()?; let max = required_columns - .max_column_expr(column, column_expr, field) + .stat_key_expr(key, column_expr, field, StatisticsType::Max) .ok()?; // A cast on `column_expr` (widening it towards min/max's target type) - // does not affect nullability, so check it on the bare column beneath. - let bare_expr = match column_expr.downcast_ref::() { - Some(cast) => cast.expr(), - None => column_expr, - }; - let non_null = - build_is_null_column_expr(bare_expr, schema, required_columns, true)?; + // does not affect nullability, so check it on the key beneath. + let key_expr = key.to_expr(); + let bare_expr = + match (&key.expr, column_expr.downcast_ref::()) { + (Some(_), _) => &key_expr, + (None, Some(cast)) => cast.expr(), + (None, None) => column_expr, + }; + let non_null = build_is_null_column_expr(bare_expr, ctx, required_columns, true)?; Some((min, max, non_null)) })(); if statistics.is_none() { - required_columns.columns.truncate(appended); + required_columns.truncate(appended); } statistics } @@ -1536,7 +1821,7 @@ fn min_max_non_null_exprs( /// and built once with the join's hash table. fn build_hash_lookup_pruning_expr( lookup: &HashTableLookupExpr, - schema: &Schema, + ctx: &PredicateBuildContext, required_columns: &mut RequiredColumns, ) -> Option> { let bitmap = Arc::clone(lookup.pruning_bitmap()?); @@ -1546,21 +1831,19 @@ fn build_hash_lookup_pruning_expr( }; // The schema adapter often wraps the column in a same-type or widening cast // (a nullable table column over a REQUIRED file column, or a narrower file - // type). `stat_column_expr` rewrites only the inner `Column`, keeping it. - let column = match column_expr.downcast_ref::() { - Some(cast) => { - let column = cast.expr().downcast_ref::()?; - let from = schema.fields().get(column.index())?.data_type(); - cast.is_bigger_cast(from).then_some(column)? - } - None => column_expr.downcast_ref::()?, - }; - let field = schema.fields().get(column.index())?; - if field.name() != column.name() { + // type). `stat_key_expr` rewrites only the key under it, keeping the cast. + let cast = column_expr.downcast_ref::(); + let key_expr = cast.map_or(column_expr, |cast| cast.expr()); + let key = as_stats_key(key_expr, ctx)?; + // The statistics have the type of the key itself, not of the cast. + let field = key.field_at_index(ctx.schema)?; + if let Some(cast) = cast + && !cast.is_bigger_cast(field.data_type()) + { return None; } let (min, max, non_null) = - min_max_non_null_exprs(column, column_expr, field, schema, required_columns)?; + min_max_non_null_exprs(&key, column_expr, &field, ctx, required_columns)?; Some(Arc::new(phys_expr::BinaryExpr::new( non_null, Operator::And, @@ -1585,7 +1868,7 @@ fn build_hash_lookup_pruning_expr( /// but prevents inversion from proving that a container is fully matched. fn build_compact_in_list_expr( in_list: &phys_expr::InListExpr, - schema: &Schema, + ctx: &PredicateBuildContext, required_columns: &mut RequiredColumns, properties: &mut PruningExpressionProperties, ) -> Option> { @@ -1594,15 +1877,12 @@ fn build_compact_in_list_expr( } else { SetMembership::In }; - let column = in_list.expr().downcast_ref::()?; - let field = schema.fields().get(column.index())?; + let key = as_stats_key(in_list.expr(), ctx)?; + let field = key.field_at_index(ctx.schema)?; let data_type = match field.data_type() { DataType::Dictionary(_, value) => value.as_ref(), data_type => data_type, }; - if field.name() != column.name() { - return None; - } let mut domain = if data_type.is_string() { CompactInListDomain::String(Vec::with_capacity(in_list.list().len())) } else if matches!( @@ -1645,7 +1925,7 @@ fn build_compact_in_list_expr( )))); } let (min, max, non_null) = - min_max_non_null_exprs(column, in_list.expr(), field, schema, required_columns)?; + min_max_non_null_exprs(&key, in_list.expr(), &field, ctx, required_columns)?; let may_match = match domain { CompactInListDomain::String(values) => { Arc::new(StringInListPruningExpr::new(membership, min, max, values)) @@ -1738,17 +2018,26 @@ impl PredicateRewriter { ) -> Arc { let mut required_columns = RequiredColumns::new(); let mut properties = PruningExpressionProperties::default(); - build_predicate_expression( - expr, - &Arc::new(schema.clone()), - &mut required_columns, - &self.unhandled_hook, - self.max_in_list_size, - &mut properties, - ) + let schema = Arc::new(schema.clone()); + let ctx = PredicateBuildContext { + schema: &schema, + unhandled_hook: &self.unhandled_hook, + max_in_list_size: self.max_in_list_size, + statistics_expr_matcher: None, + }; + build_predicate_expression(expr, &ctx, &mut required_columns, &mut properties) } } +/// Read-only settings for [`build_predicate_expression`]. +struct PredicateBuildContext<'a> { + schema: &'a SchemaRef, + unhandled_hook: &'a Arc, + max_in_list_size: usize, + /// Decides which expressions have their own statistics. + statistics_expr_matcher: Option<&'a dyn StatisticsExprMatcher>, +} + /// Translate logical filter expression into pruning predicate /// expression that will evaluate to FALSE if it can be determined no /// rows between the min/max values could pass the predicates. @@ -1763,42 +2052,35 @@ impl PredicateRewriter { /// checks. Longer lists fall back to `unhandled_hook`. fn build_predicate_expression( expr: &Arc, - schema: &SchemaRef, + ctx: &PredicateBuildContext, required_columns: &mut RequiredColumns, - unhandled_hook: &Arc, - max_in_list_size: usize, properties: &mut PruningExpressionProperties, ) -> Arc { if is_always_false(expr) { - // Shouldn't return `unhandled_hook.handle(expr)` + // Shouldn't return `ctx.unhandled_hook.handle(expr)` // Because it will transfer false to true. return Arc::clone(expr); } // predicate expression can only be a binary expression if let Some(is_null) = expr.downcast_ref::() { - return build_is_null_column_expr(is_null.arg(), schema, required_columns, false) - .unwrap_or_else(|| unhandled_hook.handle(expr)); + return build_is_null_column_expr(is_null.arg(), ctx, required_columns, false) + .unwrap_or_else(|| ctx.unhandled_hook.handle(expr)); } if let Some(is_not_null) = expr.downcast_ref::() { - return build_is_null_column_expr( - is_not_null.arg(), - schema, - required_columns, - true, - ) - .unwrap_or_else(|| unhandled_hook.handle(expr)); + return build_is_null_column_expr(is_not_null.arg(), ctx, required_columns, true) + .unwrap_or_else(|| ctx.unhandled_hook.handle(expr)); } - if let Some(col) = expr.downcast_ref::() { - return build_single_column_expr(col, schema, required_columns, false) - .unwrap_or_else(|| unhandled_hook.handle(expr)); + if let Some(key) = as_stats_key(expr, ctx) { + return build_single_column_expr(&key, ctx.schema, required_columns, false) + .unwrap_or_else(|| ctx.unhandled_hook.handle(expr)); } if let Some(not) = expr.downcast_ref::() { // match !col (don't do so recursively) - if let Some(col) = not.arg().downcast_ref::() { - return build_single_column_expr(col, schema, required_columns, true) - .unwrap_or_else(|| unhandled_hook.handle(expr)); + if let Some(key) = as_stats_key(not.arg(), ctx) { + return build_single_column_expr(&key, ctx.schema, required_columns, true) + .unwrap_or_else(|| ctx.unhandled_hook.handle(expr)); } else { - return unhandled_hook.handle(expr); + return ctx.unhandled_hook.handle(expr); } } if let Some(in_list) = expr.downcast_ref::() { @@ -1807,13 +2089,13 @@ fn build_predicate_expression( // performance threshold; compact pruning is opt-in via a raised cap. // The compact form covers both `IN` and `NOT IN`. if in_list.list().len() > MAX_IN_LIST_SIZE - && in_list.list().len() <= max_in_list_size + && in_list.list().len() <= ctx.max_in_list_size && let Some(pruning_expr) = - build_compact_in_list_expr(in_list, schema, required_columns, properties) + build_compact_in_list_expr(in_list, ctx, required_columns, properties) { return pruning_expr; } - if !in_list.list().is_empty() && in_list.list().len() <= max_in_list_size { + if !in_list.list().is_empty() && in_list.list().len() <= ctx.max_in_list_size { let eq_op = if in_list.negated() { Operator::NotEq } else { @@ -1838,19 +2120,17 @@ fn build_predicate_expression( .unwrap(); return build_predicate_expression( &change_expr, - schema, + ctx, required_columns, - unhandled_hook, - max_in_list_size, properties, ); } else { - return unhandled_hook.handle(expr); + return ctx.unhandled_hook.handle(expr); } } if let Some(lookup) = expr.downcast_ref::() { - return build_hash_lookup_pruning_expr(lookup, schema, required_columns) - .unwrap_or_else(|| unhandled_hook.handle(expr)); + return build_hash_lookup_pruning_expr(lookup, ctx, required_columns) + .unwrap_or_else(|| ctx.unhandled_hook.handle(expr)); } // A partitioned hash join hides its per-partition filters under a `CASE` on the // repartition hash. A row takes exactly one branch, so a container may match @@ -1859,13 +2139,13 @@ fn build_predicate_expression( if let Some(case) = expr.downcast_ref::() { // Only a Boolean `CASE` is a predicate; anything else is a value for // whatever compares it to handle. - if !matches!(case.data_type(schema), Ok(DataType::Boolean)) { - return unhandled_hook.handle(expr); + if !matches!(case.data_type(ctx.schema), Ok(DataType::Boolean)) { + return ctx.unhandled_hook.handle(expr); } // Without an `ELSE`, unmatched rows are UNKNOWN: not a match, but not // FALSE either, which full-match inference must be able to tell apart. if case.else_expr().is_none() { - return unhandled_hook.handle(expr); + return ctx.unhandled_hook.handle(expr); } return case .when_then_expr() @@ -1873,19 +2153,12 @@ fn build_predicate_expression( .map(|(_, then)| then) .chain(case.else_expr()) .map(|branch| { - build_predicate_expression( - branch, - schema, - required_columns, - unhandled_hook, - max_in_list_size, - properties, - ) + build_predicate_expression(branch, ctx, required_columns, properties) }) .reduce(|acc, branch| { Arc::new(phys_expr::BinaryExpr::new(acc, Operator::Or, branch)) as _ }) - .unwrap_or_else(|| unhandled_hook.handle(expr)); + .unwrap_or_else(|| ctx.unhandled_hook.handle(expr)); } let (left, op, right) = { @@ -1897,7 +2170,7 @@ fn build_predicate_expression( ) } else if let Some(like_expr) = expr.downcast_ref::() { if like_expr.case_insensitive() { - return unhandled_hook.handle(expr); + return ctx.unhandled_hook.handle(expr); } let op = match (like_expr.negated(), like_expr.case_insensitive()) { (false, false) => Operator::LikeMatch, @@ -1911,27 +2184,15 @@ fn build_predicate_expression( Arc::clone(like_expr.pattern()), ) } else { - return unhandled_hook.handle(expr); + return ctx.unhandled_hook.handle(expr); } }; if op == Operator::And || op == Operator::Or { - let left_expr = build_predicate_expression( - &left, - schema, - required_columns, - unhandled_hook, - max_in_list_size, - properties, - ); - let right_expr = build_predicate_expression( - &right, - schema, - required_columns, - unhandled_hook, - max_in_list_size, - properties, - ); + let left_expr = + build_predicate_expression(&left, ctx, required_columns, properties); + let right_expr = + build_predicate_expression(&right, ctx, required_columns, properties); // simplify boolean expression if applicable let expr = match (&left_expr, op, &right_expr) { (left, Operator::And, right) @@ -1954,15 +2215,15 @@ fn build_predicate_expression( return expr; } - let left_columns = ColumnReferenceCount::from_expression(&left); - let right_columns = ColumnReferenceCount::from_expression(&right); + let left_columns = ColumnReferenceCount::from_expression(&left, ctx); + let right_columns = ColumnReferenceCount::from_expression(&right, ctx); let expr_builder = PruningExpressionBuilder::try_new( &left, &right, left_columns, right_columns, op, - schema, + ctx.schema, required_columns, ); let mut expr_builder = match expr_builder { @@ -1971,12 +2232,61 @@ fn build_predicate_expression( // this can still produce a useful predicate when multiple conditions are joined using AND Err(e) => { debug!("Error building pruning expression: {e}"); - return unhandled_hook.handle(expr); + return ctx.unhandled_hook.handle(expr); } }; build_statistics_expr(&mut expr_builder) - .unwrap_or_else(|_| unhandled_hook.handle(expr)) + .unwrap_or_else(|_| ctx.unhandled_hook.handle(expr)) +} + +/// What a set of statistics describes: a column, or an expression that has +/// its own statistics (see [`RequiredColumns`]). +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +struct StatsKey { + /// The column, or the one column that `expr` reads. + column: phys_expr::Column, + /// `None` for the column itself. + expr: Option, +} + +impl StatsKey { + fn column(column: phys_expr::Column) -> Self { + Self { column, expr: None } + } + + /// The expression whose statistics are read. + fn to_expr(&self) -> Arc { + match &self.expr { + Some(expr) => Arc::clone(expr.expr()), + None => Arc::new(self.column.clone()), + } + } + + /// The field of the key in `schema`: the schema field of a column, + /// found by name, or a nullable field with the type of an expression. + fn field(&self, schema: &Schema) -> Result { + match &self.expr { + None => match schema.column_with_name(self.column.name()) { + Some((_, field)) => Ok(field.clone()), + None => plan_err!("Field not found in schema"), + }, + Some(expr) => { + let expr = expr.expr(); + Ok(Field::new(expr.to_string(), expr.data_type(schema)?, true)) + } + } + } + + /// Like [`Self::field`], but finds a column by its index and returns + /// `None` when the field at that index has a different name. + fn field_at_index(&self, schema: &Schema) -> Option { + if self.expr.is_none() { + let field = schema.fields().get(self.column.index())?; + return (field.name() == self.column.name()).then(|| field.as_ref().clone()); + } + self.field(schema).ok() + } } /// Count of distinct column references in an expression. @@ -1992,24 +2302,35 @@ fn build_predicate_expression( enum ColumnReferenceCount { /// no column references Zero, - /// Only one column reference - One(phys_expr::Column), + /// Only one column (or expression with its own statistics) reference + One(StatsKey), /// More than one column reference Many, } impl ColumnReferenceCount { /// Count the number of distinct column references in an expression - fn from_expression(expr: &Arc) -> Self { - let mut seen = HashSet::::new(); + fn from_expression( + expr: &Arc, + ctx: &PredicateBuildContext, + ) -> Self { + let mut seen = HashSet::::new(); expr.apply(|expr| { - if let Some(column) = expr.downcast_ref::() { - seen.insert(column.clone()); - if seen.len() > 1 { - return Ok(TreeNodeRecursion::Stop); + let key = if let Some(key) = matched_stats_key(expr, ctx) { + // The expression is one unit. Its columns must not also + // count as separate references, so skip its children. + seen.insert(key); + TreeNodeRecursion::Jump + } else { + if let Some(column) = expr.downcast_ref::() { + seen.insert(StatsKey::column(column.clone())); } + TreeNodeRecursion::Continue + }; + if seen.len() > 1 { + return Ok(TreeNodeRecursion::Stop); } - Ok(TreeNodeRecursion::Continue) + Ok(key) }) // pre_visit always returns OK, so this will always too .expect("no way to return error during recursion"); @@ -2023,6 +2344,30 @@ impl ColumnReferenceCount { } } +/// Returns a [`StatsKey`] for `expr` if `matcher` accepts it, it reads +/// exactly one column, and its type is not nested. +fn matched_stats_key( + expr: &Arc, + ctx: &PredicateBuildContext, +) -> Option { + if expr.downcast_ref::().is_some() { + return None; + } + let binding = ctx.statistics_expr_matcher?.bind(expr)?; + if expr.data_type(ctx.schema).ok()?.is_nested() { + return None; + } + let mut columns = collect_columns(expr).into_iter(); + let column = columns.next()?; + if columns.next().is_some() { + return None; + } + Some(StatsKey { + column, + expr: Some(StatsExpr::new(Arc::clone(expr), binding)), + }) +} + fn build_statistics_expr( expr_builder: &mut PruningExpressionBuilder, ) -> Result> { @@ -6876,9 +7221,14 @@ mod tests { let left_input = logical2physical(&left_input, &schema); let right_input = lit(ScalarValue::Int32(Some(12))); let right_input = logical2physical(&right_input, &schema); - let (result_left, _, result_right) = - rewrite_expr_to_prunable(&left_input, Operator::Eq, &right_input, &schema) - .unwrap(); + let (result_left, _, result_right) = rewrite_expr_to_prunable( + &left_input, + Operator::Eq, + &right_input, + &schema, + None, + ) + .unwrap(); assert_eq!(result_left.to_string(), left_input.to_string()); assert_eq!(result_right.to_string(), right_input.to_string()); @@ -6887,9 +7237,14 @@ mod tests { let left_input = logical2physical(&left_input, &schema); let right_input = lit(ScalarValue::Decimal128(Some(12), 20, 3)); let right_input = logical2physical(&right_input, &schema); - let (result_left, _, result_right) = - rewrite_expr_to_prunable(&left_input, Operator::Gt, &right_input, &schema) - .unwrap(); + let (result_left, _, result_right) = rewrite_expr_to_prunable( + &left_input, + Operator::Gt, + &right_input, + &schema, + None, + ) + .unwrap(); // The rewrite rebuilds the cast with its nullable target field assert_eq!(result_left.to_string(), "CAST(a@0 AS Decimal128(20, 3);N)"); assert_eq!(result_right.to_string(), right_input.to_string()); @@ -6899,9 +7254,14 @@ mod tests { let left_input = logical2physical(&left_input, &schema); let right_input = lit(ScalarValue::Int64(Some(12))); let right_input = logical2physical(&right_input, &schema); - let (result_left, _, result_right) = - rewrite_expr_to_prunable(&left_input, Operator::Gt, &right_input, &schema) - .unwrap(); + let (result_left, _, result_right) = rewrite_expr_to_prunable( + &left_input, + Operator::Gt, + &right_input, + &schema, + None, + ) + .unwrap(); assert_eq!(result_left.to_string(), left_input.to_string()); assert_eq!(result_right.to_string(), right_input.to_string()); @@ -6985,8 +7345,13 @@ mod tests { let left_input = logical2physical(&left_input, &schema); let right_input = lit(ScalarValue::Int64(Some(12))); let right_input = logical2physical(&right_input, &schema); - let result = - rewrite_expr_to_prunable(&left_input, Operator::Gt, &right_input, &schema); + let result = rewrite_expr_to_prunable( + &left_input, + Operator::Gt, + &right_input, + &schema, + None, + ); assert!(result.is_err()); // other expr @@ -6994,8 +7359,13 @@ mod tests { let left_input = logical2physical(&left_input, &schema); let right_input = lit(ScalarValue::Int64(Some(12))); let right_input = logical2physical(&right_input, &schema); - let result = - rewrite_expr_to_prunable(&left_input, Operator::Gt, &right_input, &schema); + let result = rewrite_expr_to_prunable( + &left_input, + Operator::Gt, + &right_input, + &schema, + None, + ); assert!(result.is_err()); // TODO: add other negative test for other case and op } @@ -7498,14 +7868,312 @@ mod tests { let expr = logical2physical(expr, schema); let unhandled_hook = Arc::new(ConstantUnhandledPredicateHook::default()) as _; let mut properties = PruningExpressionProperties::default(); - build_predicate_expression( - &expr, - &Arc::new(schema.clone()), - required_columns, - &unhandled_hook, - MAX_IN_LIST_SIZE, - &mut properties, - ) + let schema = Arc::new(schema.clone()); + let ctx = PredicateBuildContext { + schema: &schema, + unhandled_hook: &unhandled_hook, + max_in_list_size: MAX_IN_LIST_SIZE, + statistics_expr_matcher: None, + }; + build_predicate_expression(&expr, &ctx, required_columns, &mut properties) + } + + /// Matches `get_field` calls, as a statistics source for struct fields + /// would. + #[derive(Debug)] + struct GetFieldMatcher; + + impl StatisticsExprMatcher for GetFieldMatcher { + fn bind( + &self, + expr: &Arc, + ) -> Option> { + expr.downcast_ref::() + .is_some_and(|f| f.name() == "get_field") + .then(|| Arc::new(()) as _) + } + } + + fn struct_schema() -> SchemaRef { + let s = DataType::Struct( + vec![ + Field::new("a", DataType::Int32, true), + Field::new("b", DataType::Int32, true), + Field::new("flag", DataType::Boolean, true), + ] + .into(), + ); + Arc::new(Schema::new(vec![ + Field::new("s", s, true), + Field::new("c", DataType::Int32, true), + ])) + } + + fn build_with_matcher(expr: &Expr, matcher: bool) -> PruningPredicate { + let schema = struct_schema(); + let matcher = matcher.then(|| Arc::new(GetFieldMatcher) as _); + PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(&schema)) + .with_statistics_expr_matcher(matcher) + .try_build(logical2physical(expr, &schema)) + .unwrap() + } + + /// Binds `get_field(s, 'a')` to the maximum of each container. + #[derive(Debug)] + struct MaxBindingMatcher; + + /// The private binding type of [`MaxBindingMatcher`]. + struct Maxes(Int32Array); + + impl StatisticsExprMatcher for MaxBindingMatcher { + fn bind( + &self, + expr: &Arc, + ) -> Option> { + GetFieldMatcher.bind(expr)?; + Some(Arc::new(Maxes(Int32Array::from(vec![3, 10])))) + } + } + + /// Two containers that know only what the bindings tell them. + struct BindingStatistics; + + impl PruningStatistics for BindingStatistics { + fn min_values(&self, _: &Column) -> Option { + None + } + fn max_values(&self, _: &Column) -> Option { + None + } + fn num_containers(&self) -> usize { + 2 + } + fn null_counts(&self, _: &Column) -> Option { + None + } + fn row_counts(&self) -> Option { + None + } + fn contained( + &self, + _: &Column, + _: &HashSet, + ) -> Option { + None + } + fn max_values_for_expr(&self, expr: &StatsExpr) -> Option { + let Maxes(maxes) = expr.binding::()?; + Some(Arc::new(maxes.clone())) + } + } + + #[test] + fn statistics_read_the_binding_of_the_matcher() { + use datafusion_functions::core::expr_fn::get_field; + let schema = struct_schema(); + let expr = get_field(col("s"), "a").gt(lit(5)); + let predicate = PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(&schema)) + .with_statistics_expr_matcher(Some(Arc::new(MaxBindingMatcher))) + .try_build(logical2physical(&expr, &schema)) + .unwrap(); + // The first container has max 3, so `> 5` cannot hold there. + assert_eq!(predicate.prune(&BindingStatistics).unwrap(), [false, true]); + } + + /// Binds `TRY_CAST(.. AS Int64)` when `outer` is set, and `get_field`. + #[derive(Debug)] + struct CastOrFieldMatcher { + outer: bool, + } + + impl StatisticsExprMatcher for CastOrFieldMatcher { + fn bind( + &self, + expr: &Arc, + ) -> Option> { + if self.outer && expr.downcast_ref::().is_some() { + return Some(Arc::new(())); + } + GetFieldMatcher.bind(expr) + } + } + + fn key_of_try_cast_predicate(outer: bool) -> String { + use datafusion_functions::core::expr_fn::get_field; + let schema = struct_schema(); + let expr = try_cast(get_field(col("s"), "a"), DataType::Int64).gt(lit(5i64)); + let predicate = PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(&schema)) + .with_statistics_expr_matcher(Some(Arc::new(CastOrFieldMatcher { outer }))) + .try_build(logical2physical(&expr, &schema)) + .unwrap(); + let (_, key) = predicate.required_columns().single_key().unwrap(); + key.unwrap().to_string() + } + + #[test] + fn bound_outer_expression_is_the_key() { + assert_eq!( + key_of_try_cast_predicate(true), + "TRY_CAST(get_field(s@0, a) AS Int64)" + ); + } + + #[test] + fn unbound_outer_expression_falls_back_to_inner_key() { + assert_eq!(key_of_try_cast_predicate(false), "get_field(s@0, a)"); + } + + #[test] + fn matched_expression_reads_its_own_statistics() { + use datafusion_functions::core::expr_fn::get_field; + let expr = get_field(col("s"), "a").gt(lit(5)); + let predicate = build_with_matcher(&expr, true); + assert_eq!( + predicate.predicate_expr().to_string(), + "get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_max@0 > 5" + ); + let (column, key_expr) = predicate.required_columns().single_key().unwrap(); + assert_eq!(column.name(), "s"); + assert_eq!(key_expr.unwrap().to_string(), "get_field(s@0, a)"); + // A key expression is not the column itself. + assert!(predicate.required_columns().single_column().is_none()); + + // Without a matcher, nothing can be pruned. + assert!(build_with_matcher(&expr, false).always_true()); + } + + #[test] + fn matched_expression_is_null() { + use datafusion_functions::core::expr_fn::get_field; + let a = || get_field(col("s"), "a"); + let predicate = build_with_matcher(&a().is_null(), true); + assert_eq!( + predicate.predicate_expr().to_string(), + "get_field(s@0, a)_null_count@0 > 0" + ); + let predicate = build_with_matcher(&a().is_not_null(), true); + assert_eq!( + predicate.predicate_expr().to_string(), + "get_field(s@0, a)_null_count@1 != row_count@0" + ); + } + + #[test] + fn matched_expression_under_cast() { + use datafusion_functions::core::expr_fn::get_field; + // The schema adapter wraps a drifted struct field in a cast. + let expr = cast(get_field(col("s"), "a"), DataType::Float64).gt(lit(6.5)); + let predicate = build_with_matcher(&expr, true); + assert_eq!( + predicate.predicate_expr().to_string(), + "get_field(s@0, a)_null_count@1 != row_count@2 \ + AND CAST(get_field(s@0, a)_max@0 AS Float64;N) > 6.5" + ); + } + + #[test] + fn matched_boolean_expression() { + use datafusion_functions::core::expr_fn::get_field; + let flag = || get_field(col("s"), "flag"); + let predicate = build_with_matcher(&flag(), true); + assert_eq!( + predicate.predicate_expr().to_string(), + "get_field(s@0, flag)_min@0 OR get_field(s@0, flag)_max@1" + ); + let predicate = build_with_matcher(&flag().not(), true); + assert_eq!( + predicate.predicate_expr().to_string(), + "NOT get_field(s@0, flag)_min@0 OR NOT get_field(s@0, flag)_max@1" + ); + } + + #[test] + fn matched_expression_compact_in_list() { + use datafusion_functions::core::expr_fn::get_field; + let schema = struct_schema(); + let list: Vec = (30..51).map(lit).collect(); + let expr = get_field(col("s"), "a").in_list(list, false); + let predicate = PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(&schema)) + .with_max_in_list_size(100) + .with_statistics_expr_matcher(Some(Arc::new(GetFieldMatcher))) + .try_build(logical2physical(&expr, &schema)) + .unwrap(); + // One compact check instead of 21 per-value comparisons. + assert_eq!( + predicate.predicate_expr().to_string(), + "get_field(s@0, a)_null_count@3 != row_count@2 AND \ + IN_SET_INTERSECTS(get_field(s@0, a)_min@0, get_field(s@0, a)_max@1, 21 values)" + ); + } + + #[test] + fn matched_expression_literal_guarantees() { + use datafusion_functions::core::expr_fn::get_field; + let a = || get_field(col("s"), "a"); + let b = || get_field(col("s"), "b"); + let guarantees = |expr: &Expr| { + let predicate = build_with_matcher(expr, true); + // Placeholders never show up as column guarantees. + assert!(predicate.literal_guarantees().is_empty(), "{expr}"); + predicate + .expr_literal_guarantees + .iter() + .map(|g| format!("{} {:?} {}", g.expr, g.guarantee, g.literals.len())) + .collect::>() + }; + assert_eq!( + guarantees(&a().eq(lit(1)).or(a().eq(lit(2)))), + ["get_field(s@0, a) In 2"] + ); + assert_eq!( + guarantees(&a().not_eq(lit(1)).and(b().eq(lit(2)))), + ["get_field(s@0, a) NotIn 1", "get_field(s@0, b) In 1"] + ); + // Two different keys in an OR guarantee nothing about either. + assert!(guarantees(&a().eq(lit(1)).or(b().eq(lit(2)))).is_empty()); + // A cast key compares converted values, not the stored ones. + assert!(guarantees(&cast(a(), DataType::Int64).eq(lit(1i64))).is_empty()); + } + + #[test] + fn expr_literal_guarantee_alone_is_not_always_true() { + use datafusion_functions::core::expr_fn::get_field; + let schema = struct_schema(); + let expr = get_field(col("s"), "a").in_list(vec![lit(1), lit(2)], false); + // A cap of zero disables the min/max rewrite of IN, so only the + // literal guarantee can prune. + let predicate = PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(&schema)) + .with_max_in_list_size(0) + .with_statistics_expr_matcher(Some(Arc::new(GetFieldMatcher))) + .try_build(logical2physical(&expr, &schema)) + .unwrap(); + assert!(is_always_true(predicate.predicate_expr())); + assert!(!predicate.always_true()); + assert_eq!(predicate.literal_exprs().len(), 1); + } + + #[test] + fn matched_expressions_not_prunable() { + use datafusion_functions::core::expr_fn::get_field; + let a = || get_field(col("s"), "a"); + let b = || get_field(col("s"), "b"); + for expr in [ + // Two different keys in one comparison. + a().gt(b()), + (a() + b()).gt(lit(5)), + (a() + col("c")).gt(lit(5)), + ] { + assert!(build_with_matcher(&expr, true).always_true(), "{expr}"); + } + // Two keys in an OR are fine, but not a single key. + let predicate = build_with_matcher(&a().gt(lit(1)).or(col("c").lt(lit(2))), true); + assert!(!predicate.always_true()); + assert!(predicate.required_columns().single_key().is_none()); } #[test] @@ -7600,6 +8268,27 @@ mod tests { Ok(()) } + #[test] + fn test_hash_lookup_pruning_on_struct_field() -> Result<()> { + use datafusion_functions::core::expr_fn::get_field; + let s = DataType::Struct(vec![Field::new("a", DataType::Int64, true)].into()); + let schema = Arc::new(Schema::new(vec![Field::new("s", s, true)])); + let key = logical2physical(&get_field(col("s"), "a"), &schema); + let lookup = hash_lookup(&key, &[10, 20, 30, 100_000])?; + + let predicate = PruningPredicateBuilder::new() + .with_file_schema(Arc::clone(&schema)) + .with_statistics_expr_matcher(Some(Arc::new(GetFieldMatcher))) + .try_build(lookup)?; + // The bitmap term reads the struct field's own statistics. + assert_eq!( + predicate.predicate_expr().to_string(), + "get_field(s@0, a)_null_count@3 != row_count@2 AND \ + KEY_RANGE_BITMAP(get_field(s@0, a)_min@0, get_field(s@0, a)_max@1, 4/131072 buckets)" + ); + Ok(()) + } + #[rstest] #[case::widening_i32_to_i64(DataType::Int32, DataType::Int64, true)] #[case::widening_u32_to_i64(DataType::UInt32, DataType::Int64, true)] diff --git a/datafusion/sqllogictest/test_files/parquet_struct_field_pruning.slt b/datafusion/sqllogictest/test_files/parquet_struct_field_pruning.slt new file mode 100644 index 0000000000000..ae15b5a8f2a87 --- /dev/null +++ b/datafusion/sqllogictest/test_files/parquet_struct_field_pruning.slt @@ -0,0 +1,498 @@ +# 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 + +# Row group pruning with statistics for predicates on struct fields +# (`get_field(s, 'a')`, written `s['a']`). + +statement ok +CREATE TABLE src AS VALUES +-- ***** Row Group 0: a in [1, 3] ***** + (1, 100), + (2, 200), + (3, 300), +-- ***** Row Group 1: a in [10, 12] ***** + (10, 100), + (11, 200), + (12, 300), +-- ***** Row Group 2: null struct, a = 20, null a ***** + (NULL, NULL), + (20, 400), + (-1, 500), +-- ***** Row Group 3: a in [30, 32] ***** + (30, 100), + (31, 200), + (32, 300); + +# Row 7 (column1 = NULL) is a null struct. Row 9 (column1 = -1) is a non-null +# struct with a null `a`. +statement ok +COPY ( + SELECT + CASE + WHEN column1 IS NULL THEN NULL + WHEN column1 = -1 THEN named_struct('a', CAST(NULL AS INT), 'b', column2) + ELSE named_struct('a', column1, 'b', column2) + END AS s, + column1 AS id + FROM src +) +TO 'test_files/scratch/parquet_struct_field_pruning/data.parquet' +STORED AS PARQUET +OPTIONS ('format.max_row_group_size' '3'); + +statement ok +DROP TABLE src; + +statement ok +CREATE EXTERNAL TABLE t +STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/data.parquet'; + +statement ok +set datafusion.explain.analyze_level = summary; + +statement ok +set datafusion.explain.analyze_categories = 'rows'; + +# Results are correct. +query ?I rowsort +SELECT s, id FROM t WHERE s['a'] > 15; +---- +{a: 20, b: 400} 20 +{a: 30, b: 100} 30 +{a: 31, b: 200} 31 +{a: 32, b: 300} 32 + +query I rowsort +SELECT id FROM t WHERE s['a'] IS NULL; +---- +-1 +NULL + +# Row groups 0 and 1 are pruned. +query TT +EXPLAIN ANALYZE SELECT * FROM t WHERE s['a'] > 15; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 > 15, projection=[s@1, id@2], metrics=[output_rows=4, selectivity=66.67% (4/6)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=6] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) > 15, pruning_predicate=get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_max@0 > 15, required_guarantees=[], metrics=[output_rows=6, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 2 matched, page_index_pages_pruned=2 total → 2 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=13.43% (452/3.37 K)] + +# Only row group 0 matches. +query TT +EXPLAIN ANALYZE SELECT * FROM t WHERE s['a'] <= 2; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 <= 2, projection=[s@1, id@2], metrics=[output_rows=2, selectivity=66.67% (2/3)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=3] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) <= 2, pruning_predicate=get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_min@0 <= 2, required_guarantees=[], metrics=[output_rows=3, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 1 matched, page_index_pages_pruned=1 total → 1 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=7.04% (237/3.37 K)] + +# Equality, with the literal on the left. +query TT +EXPLAIN ANALYZE SELECT * FROM t WHERE 11 = s['a']; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 = 11, projection=[s@1, id@2], metrics=[output_rows=1, selectivity=33.33% (1/3)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=3] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) = 11, pruning_predicate=get_field(s@0, a)_null_count@2 != row_count@3 AND get_field(s@0, a)_min@0 <= 11 AND 11 <= get_field(s@0, a)_max@1, required_guarantees=[], metrics=[output_rows=3, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 1 matched, page_index_pages_pruned=1 total → 1 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=7.04% (237/3.37 K)] + +# Row group 2 holds only one non-null `a`, so `s['a'] = 20` keeps it. +query TT +EXPLAIN ANALYZE SELECT * FROM t WHERE s['a'] = 20; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 = 20, projection=[s@1, id@2], metrics=[output_rows=1, selectivity=33.33% (1/3)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=3] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) = 20, pruning_predicate=get_field(s@0, a)_null_count@2 != row_count@3 AND get_field(s@0, a)_min@0 <= 20 AND 20 <= get_field(s@0, a)_max@1, required_guarantees=[], metrics=[output_rows=3, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 1 matched, page_index_pages_pruned=1 total → 1 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=6.39% (215/3.37 K)] + +# Two different struct fields in one comparison are not prunable. +query TT +EXPLAIN ANALYZE SELECT * FROM t WHERE s['a'] > s['b']; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_2@1 < __datafusion_extracted_1@0, projection=[s@2, id@3], metrics=[output_rows=0, selectivity=0% (0/12)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=12] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, get_field(s@0, b) as __datafusion_extracted_2, s, id], file_type=parquet, predicate=get_field(s@0, b) < get_field(s@0, a), metrics=[output_rows=12, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 4 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=27.52% (926/3.37 K)] + +# A struct field combined with a plain column in OR. +query TT +EXPLAIN ANALYZE SELECT * FROM t WHERE s['a'] > 25 OR id < 2; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 > 25 OR id@2 < 2, projection=[s@1, id@2], metrics=[output_rows=5, selectivity=55.56% (5/9)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=9] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) > 25 OR id@1 < 2, pruning_predicate=get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_max@0 > 25 OR id_null_count@4 != row_count@2 AND id_min@3 < 2, required_guarantees=[], metrics=[output_rows=9, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 3 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=20.48% (689/3.37 K)] + +# An IN list longer than 20 values uses the compact form, when the limit +# allows it. Only row group 3 (`a` in [30, 32]) can match. A table reads +# the limit when it is created, so `t_in` is created after the `set`. +statement ok +set datafusion.execution.parquet.max_in_list_size = 100; + +statement ok +CREATE EXTERNAL TABLE t_in +STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/data.parquet'; + +query TT +EXPLAIN ANALYZE SELECT * FROM t_in WHERE s['a'] IN (30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50); +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 IN (SET) ([30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]), projection=[s@1, id@2], metrics=[output_rows=3, selectivity=100% (3/3)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=3] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s, id], file_type=parquet, predicate=get_field(s@0, a) IN (SET) ([30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]), pruning_predicate=get_field(s@0, a)_null_count@3 != row_count@2 AND IN_SET_INTERSECTS(get_field(s@0, a)_min@0, get_field(s@0, a)_max@1, 21 values), required_guarantees=[], metrics=[output_rows=3, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=4 total → 1 matched, page_index_pages_pruned=1 total → 1 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=7.04% (237/3.37 K)] + +statement ok +DROP TABLE t_in; + +statement ok +reset datafusion.execution.parquet.max_in_list_size; + +statement ok +DROP TABLE t; + +# Two files with one row group each. The row group of the file with +# `a` in [30, 32] is pruned by statistics, so the scan reads no data pages +# from it. File-level pruning (`files_ranges_pruned_statistics`) is not +# covered: it reads `Statistics`, which has no struct field statistics. +statement ok +COPY (SELECT named_struct('a', column1) AS s FROM (VALUES (1), (2), (3))) +TO 'test_files/scratch/parquet_struct_field_pruning/two_files/low.parquet' +STORED AS PARQUET; + +statement ok +COPY (SELECT named_struct('a', column1) AS s FROM (VALUES (30), (31), (32))) +TO 'test_files/scratch/parquet_struct_field_pruning/two_files/high.parquet' +STORED AS PARQUET; + +statement ok +CREATE EXTERNAL TABLE two_files +STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/two_files/'; + +query ? +SELECT s FROM two_files WHERE s['a'] < 10 ORDER BY s['a']; +---- +{a: 1} +{a: 2} +{a: 3} + +query TT +EXPLAIN ANALYZE SELECT * FROM two_files WHERE s['a'] < 10; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 < 10, projection=[s@1], metrics=[output_rows=3, selectivity=100% (3/3)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=2, metrics=[output_rows=3] +03)----DataSourceExec: file_groups={2 groups: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/two_files/high.parquet], [WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/two_files/low.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s], file_type=parquet, predicate=get_field(s@0, a) < 10, pruning_predicate=get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_min@0 < 10, required_guarantees=[], metrics=[output_rows=3, files_ranges_pruned_statistics=2 total → 2 matched, row_groups_pruned_statistics=2 total → 1 matched -> 1 fully matched, page_index_pages_pruned=0 total → 0 matched, page_index_pages_skipped_by_fully_matched=1, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=13.34% (79/592)] + +statement ok +DROP TABLE two_files; + +# One row group with 10 pages of 10 rows each. Page i holds `a` in +# [10 * i, 10 * i + 9], so `s['a'] >= 85` can skip 8 of the 10 pages. +statement ok +COPY (SELECT named_struct('a', value) AS s FROM generate_series(0, 99)) +TO 'test_files/scratch/parquet_struct_field_pruning/pages.parquet' +STORED AS PARQUET +OPTIONS ( + 'format.max_row_group_size' '100', + 'format.data_page_row_count_limit' '10', + 'format.write_batch_size' '10' +); + +statement ok +CREATE EXTERNAL TABLE pages +STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/pages.parquet'; + +query I +SELECT count(*) FROM pages WHERE s['a'] >= 85; +---- +15 + +query TT +EXPLAIN ANALYZE SELECT * FROM pages WHERE s['a'] >= 85; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 >= 85, projection=[s@1], metrics=[output_rows=15, selectivity=75% (15/20)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=20] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/pages.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s], file_type=parquet, predicate=get_field(s@0, a) >= 85, pruning_predicate=get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_max@0 >= 85, required_guarantees=[], metrics=[output_rows=20, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=1 total → 1 matched, page_index_pages_pruned=10 total → 2 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=18.32% (260/1.42 K)] + +statement ok +DROP TABLE pages; + +# Dynamic TopK: 5 row groups of 3 rows, `s['a']` = 14 down to 0, so the +# first row group holds the top 3. After it, the TopK filter +# `s['a'] IS NULL OR s['a'] > 12` can skip the other 4 row groups. +statement ok +COPY (SELECT named_struct('a', 14 - value) AS s, 14 - value AS v FROM generate_series(0, 14)) +TO 'test_files/scratch/parquet_struct_field_pruning/topk.parquet' +STORED AS PARQUET +OPTIONS ('format.max_row_group_size' '3'); + +statement ok +CREATE EXTERNAL TABLE topk +STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/topk.parquet'; + +statement ok +set datafusion.execution.parquet.pushdown_filters = true; + +statement ok +set datafusion.execution.target_partitions = 1; + +# `row_groups_pruned_dynamic_filter` is an uncategorized metric. +statement ok +set datafusion.explain.analyze_categories = 'rows,uncategorized'; + +query I +SELECT s['a'] FROM topk ORDER BY s['a'] DESC LIMIT 3; +---- +14 +13 +12 + +# The same query on a plain column, for comparison. +query TT +EXPLAIN ANALYZE SELECT v FROM topk ORDER BY v DESC LIMIT 3; +---- +Plan with Metrics +01)SortExec: TopK(fetch=3), expr=[v@0 DESC], preserve_partitioning=[false], filter=[v@0 IS NULL OR v@0 > 12], metrics=[output_rows=3] +02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/topk.parquet]]}, projection=[v], file_type=parquet, predicate=DynamicFilter [ v@1 IS NULL OR v@1 > 12 ], sort_order_for_reorder=[v@0 DESC], reverse_row_groups=true, dynamic_rg_pruning=eligible, pruning_predicate=v_null_count@0 > 0 OR v_null_count@0 != row_count@2 AND v_max@1 > 12, required_guarantees=[], metrics=[output_rows=3, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=5 total → 5 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, row_groups_pruned_dynamic_filter=4, scan_efficiency_ratio=2.66% (73/2.75 K)] + +query TT +EXPLAIN ANALYZE SELECT s['a'] FROM topk ORDER BY s['a'] DESC LIMIT 3; +---- +Plan with Metrics +01)SortExec: TopK(fetch=3), expr=[topk.s[a]@0 DESC], preserve_partitioning=[false], filter=[topk.s[a]@0 IS NULL OR topk.s[a]@0 > 12], metrics=[output_rows=3] +02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/topk.parquet]]}, projection=[get_field(s@0, a) as topk.s[a]], file_type=parquet, predicate=DynamicFilter [ get_field(s@0, a) IS NULL OR get_field(s@0, a) > 12 ], dynamic_rg_pruning=eligible, pruning_predicate=get_field(s@0, a)_null_count@0 > 0 OR get_field(s@0, a)_null_count@0 != row_count@2 AND get_field(s@0, a)_max@1 > 12, required_guarantees=[], metrics=[output_rows=3, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=5 total → 5 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, row_groups_pruned_dynamic_filter=4, scan_efficiency_ratio=2.87% (79/2.75 K)] + +statement ok +reset datafusion.execution.parquet.pushdown_filters; + +statement ok +set datafusion.execution.target_partitions = 4; + +statement ok +set datafusion.explain.analyze_categories = 'rows'; + +statement ok +DROP TABLE topk; + +# Struct type drift: the file stores `s.a` as INT, the table declares +# DOUBLE. The schema adapter rewrites `s['a']` to +# `CAST(get_field(s, 'a') AS DOUBLE)` for this file. Comparing with 6.5 +# keeps the cast, because 6.5 has no INT equivalent. +statement ok +COPY (SELECT named_struct('a', CAST(value AS INT)) AS s FROM generate_series(0, 8)) +TO 'test_files/scratch/parquet_struct_field_pruning/drift/data.parquet' +STORED AS PARQUET +OPTIONS ('format.max_row_group_size' '3'); + +statement ok +CREATE EXTERNAL TABLE drift (s STRUCT) +STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/drift/'; + +query R +SELECT s['a'] FROM drift WHERE s['a'] > 6.5 ORDER BY s['a']; +---- +7 +8 + +# Row groups 0 and 1 (`a` in [0, 5]) can be pruned. +query TT +EXPLAIN ANALYZE SELECT * FROM drift WHERE s['a'] > 6.5; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 > 6.5, projection=[s@1], metrics=[output_rows=2, selectivity=66.67% (2/3)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=3] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/drift/data.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s], file_type=parquet, predicate=get_field(s@0, a) > 6.5, pruning_predicate=get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_max@0 > 6.5, required_guarantees=[], metrics=[output_rows=3, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=3 total → 1 matched, page_index_pages_pruned=1 total → 1 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=7.13% (71/996)] + +statement ok +DROP TABLE drift; + +# Bloom filters on struct fields. Each row group spans a wide range, so +# min/max cannot rule out `s['a'] = 50`, but the bloom filters can. +# +# | Row group | s.a | s.i8 | s.d | s.dec | +# |-----------|---------|--------|---------------------------|--------------| +# | 0 | 1, 100 | 1, 100 | 2024-01-01, 2024-04-09 | 1.00, 100.00 | +# | 1 | 2, 99 | 2, 99 | 2024-01-02, 2024-04-08 | 2.00, 99.00 | +statement ok +COPY ( + SELECT named_struct( + 'a', column1, + 'i8', CAST(column1 AS TINYINT), + 'd', CAST('2024-01-01' AS DATE) + CAST(column1 - 1 AS INT), + 'dec', CAST(column1 AS DECIMAL(10, 2)) + ) AS s + FROM (VALUES (1), (100), (2), (99)) +) +TO 'test_files/scratch/parquet_struct_field_pruning/bloom.parquet' +STORED AS PARQUET +OPTIONS ( + 'format.max_row_group_size' '2', + 'format.bloom_filter_on_write' 'true' +); + +statement ok +CREATE EXTERNAL TABLE bloom +STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/bloom.parquet'; + +# Both row groups can be skipped by their bloom filters. +query TT +EXPLAIN ANALYZE SELECT * FROM bloom WHERE s['a'] = 50; +---- +Plan with Metrics +01)FilterExec: __datafusion_extracted_1@0 = 50, projection=[s@1], metrics=[output_rows=0, selectivity=N/A (0/0)] +02)--RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, metrics=[output_rows=0] +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/bloom.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, s], file_type=parquet, predicate=get_field(s@0, a) = 50, pruning_predicate=get_field(s@0, a)_null_count@2 != row_count@3 AND get_field(s@0, a)_min@0 <= 50 AND 50 <= get_field(s@0, a)_max@1, required_guarantees=[], metrics=[output_rows=0, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=2 total → 2 matched, row_groups_pruned_bloom_filter=2 total → 0 matched, page_index_pages_pruned=0 total → 0 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=3.37% (94/2.79 K)] + +# `!=` can never be proven false by a bloom filter. +query I +SELECT count(*) FROM bloom WHERE s['a'] != 50; +---- +4 + +# Values that are present are found for every field type. +query I +SELECT count(*) FROM bloom WHERE s['a'] = 99; +---- +1 + +query I +SELECT count(*) FROM bloom WHERE s['i8'] = 99; +---- +1 + +query I +SELECT count(*) FROM bloom WHERE s['d'] = DATE '2024-04-08'; +---- +1 + +query I +SELECT count(*) FROM bloom WHERE s['dec'] = 99.00; +---- +1 + +statement ok +DROP TABLE bloom; + +# Hash join dynamic filter. The build side `u` has ids 0, 5000 and 9999, so +# its bounds [0, 9999] cover all 10 row groups of `hj`, but its key bitmap +# only reaches row groups 0, 5 and 9. A hash-lookup filter (forced by an +# IN-list limit of 0) carries that bitmap to the probe-side scan. +statement ok +COPY (SELECT named_struct('a', value) AS s, value AS v FROM generate_series(0, 9999) ORDER BY value) +TO 'test_files/scratch/parquet_struct_field_pruning/hj.parquet' +STORED AS PARQUET +OPTIONS ('format.max_row_group_size' '1000'); + +statement ok +CREATE EXTERNAL TABLE hj +STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/hj.parquet'; + +statement ok +CREATE TABLE u(id BIGINT) AS VALUES (0), (5000), (9999); + +statement ok +set datafusion.execution.target_partitions = 1; + +statement ok +set datafusion.optimizer.hash_join_inlist_pushdown_max_size = 0; + +statement ok +set datafusion.optimizer.hash_join_inlist_pushdown_max_distinct_values = 0; + +query I +SELECT hj.v FROM u JOIN hj ON hj.s['a'] = u.id ORDER BY hj.v; +---- +0 +5000 +9999 + +# The same join on a plain column, for comparison. +query TT +EXPLAIN ANALYZE SELECT hj.v FROM u JOIN hj ON hj.v = u.id; +---- +Plan with Metrics +01)HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(id@0, v@0)], projection=[v@1], metrics=[output_rows=3, avg_fanout=100% (3/3), probe_hit_rate=0.1% (3/3.00 K)] +02)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] +03)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/hj.parquet]]}, projection=[v], output_ordering=[v@0 ASC NULLS LAST], file_type=parquet, predicate=DynamicFilter [ v@1 >= 0 AND v@1 <= 9999 AND hash_lookup ], dynamic_rg_pruning=eligible, pruning_predicate=v_null_count@1 != row_count@2 AND v_max@0 >= 0 AND v_null_count@1 != row_count@2 AND v_min@3 <= 9999 AND v_null_count@1 != row_count@2 AND KEY_RANGE_BITMAP(v_min@3, v_max@0, 3/16384 buckets), required_guarantees=[], metrics=[output_rows=3.00 K, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=10 total → 3 matched, page_index_pages_pruned=3 total → 3 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=14.55% (7.59 K/52.19 K)] + +query TT +EXPLAIN ANALYZE SELECT hj.v FROM u JOIN hj ON hj.s['a'] = u.id; +---- +Plan with Metrics +01)HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(id@0, __datafusion_extracted_1@0)], projection=[v@2], metrics=[output_rows=3, avg_fanout=100% (3/3), probe_hit_rate=0.1% (3/3.00 K)] +02)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] +03)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/parquet_struct_field_pruning/hj.parquet]]}, projection=[get_field(s@0, a) as __datafusion_extracted_1, v], output_ordering=[v@1 ASC NULLS LAST], file_type=parquet, predicate=DynamicFilter [ get_field(s@0, a) >= 0 AND get_field(s@0, a) <= 9999 AND hash_lookup ], dynamic_rg_pruning=eligible, pruning_predicate=get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_max@0 >= 0 AND get_field(s@0, a)_null_count@1 != row_count@2 AND get_field(s@0, a)_min@3 <= 9999 AND get_field(s@0, a)_null_count@1 != row_count@2 AND KEY_RANGE_BITMAP(get_field(s@0, a)_min@3, get_field(s@0, a)_max@0, 3/16384 buckets), required_guarantees=[], metrics=[output_rows=3.00 K, files_ranges_pruned_statistics=1 total → 1 matched, row_groups_pruned_statistics=10 total → 3 matched, page_index_pages_pruned=3 total → 3 matched, limit_pruned_row_groups=0 total → 0 matched, scan_efficiency_ratio=29.15% (15.21 K/52.19 K)] + +statement ok +reset datafusion.optimizer.hash_join_inlist_pushdown_max_size; + +statement ok +reset datafusion.optimizer.hash_join_inlist_pushdown_max_distinct_values; + +statement ok +set datafusion.execution.target_partitions = 4; + +statement ok +DROP TABLE u; + +statement ok +DROP TABLE hj; + +statement ok +reset datafusion.explain.analyze_level; + +statement ok +reset datafusion.explain.analyze_categories; + +# A struct field can be NULL when the struct column itself is not +# nullable. A row group is fully matched only if the field has no nulls. +statement ok +COPY (SELECT named_struct('a', column1) AS s, column2 AS id FROM (VALUES (1, 1), (CAST(NULL AS INT), 2), (3, 3))) +TO 'test_files/scratch/parquet_struct_field_pruning/full_match/f.parquet' +STORED AS PARQUET; + +statement ok +CREATE EXTERNAL TABLE full_match STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/full_match/f.parquet'; + +statement ok +set datafusion.execution.parquet.pushdown_filters = true; + +query I +SELECT id FROM full_match WHERE s['a'] <= 5 ORDER BY id; +---- +1 +3 + +statement ok +set datafusion.execution.parquet.pushdown_filters = false; + +# A real column whose name looks like a statistics placeholder must not +# take the bloom filter guarantees of a struct field. +statement ok +COPY (SELECT column1 AS "__datafusion_pruning_stats_expr_0", named_struct('a', column2) AS s FROM (VALUES (99, 7), (6, 8))) +TO 'test_files/scratch/parquet_struct_field_pruning/placeholder/f.parquet' +STORED AS PARQUET OPTIONS ('format.bloom_filter_on_write' 'true'); + +statement ok +CREATE EXTERNAL TABLE placeholder STORED AS PARQUET +LOCATION 'test_files/scratch/parquet_struct_field_pruning/placeholder/f.parquet'; + +query I +SELECT count(*) FROM placeholder WHERE "__datafusion_pruning_stats_expr_0" = 99 AND s['a'] > 0; +---- +1 + +query I +SELECT count(*) FROM placeholder WHERE s['a'] > 0 AND "__datafusion_pruning_stats_expr_0" IN (99, 100); +---- +1 diff --git a/datafusion/sqllogictest/test_files/projection_pushdown.slt b/datafusion/sqllogictest/test_files/projection_pushdown.slt index 2d5a554430b94..7454d2e96e2f0 100644 --- a/datafusion/sqllogictest/test_files/projection_pushdown.slt +++ b/datafusion/sqllogictest/test_files/projection_pushdown.slt @@ -279,7 +279,7 @@ logical_plan physical_plan 01)ProjectionExec: expr=[id@0 as id, __datafusion_extracted_2@1 as simple_struct.s[label]] 02)--FilterExec: __datafusion_extracted_1@0 > 150, projection=[id@1, __datafusion_extracted_2@2] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id, get_field(s@1, label) as __datafusion_extracted_2], file_type=parquet, predicate=get_field(s@1, value) > 150 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id, get_field(s@1, label) as __datafusion_extracted_2], file_type=parquet, predicate=get_field(s@1, value) > 150, pruning_predicate=get_field(s@1, value)_null_count@1 != row_count@2 AND get_field(s@1, value)_max@0 > 150, required_guarantees=[] # Verify correctness query IT @@ -839,7 +839,7 @@ logical_plan physical_plan 01)ProjectionExec: expr=[id@0 as id, __datafusion_extracted_2@1 as nullable_struct.s[label]] 02)--FilterExec: __datafusion_extracted_1@0 IS NOT NULL, projection=[id@1, __datafusion_extracted_2@2] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/nullable.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id, get_field(s@1, label) as __datafusion_extracted_2], file_type=parquet, predicate=get_field(s@1, value) IS NOT NULL +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/nullable.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id, get_field(s@1, label) as __datafusion_extracted_2], file_type=parquet, predicate=get_field(s@1, value) IS NOT NULL, pruning_predicate=get_field(s@1, value)_null_count@1 != row_count@0, required_guarantees=[] # Verify correctness query IT @@ -1447,7 +1447,7 @@ logical_plan physical_plan 01)HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(id@0, id@0)] 02)--FilterExec: __datafusion_extracted_1@0 > 150, projection=[id@1] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id], file_type=parquet, predicate=get_field(s@1, value) > 150 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id], file_type=parquet, predicate=get_field(s@1, value) > 150, pruning_predicate=get_field(s@1, value)_null_count@1 != row_count@2 AND get_field(s@1, value)_max@0 > 150, required_guarantees=[] 04)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/join_right.parquet]]}, projection=[id], file_type=parquet, predicate=DynamicFilter [ empty ], dynamic_rg_pruning=eligible # Verify correctness - id matches and value > 150 @@ -1486,9 +1486,9 @@ logical_plan physical_plan 01)HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(id@0, id@0)] 02)--FilterExec: __datafusion_extracted_1@0 > 100, projection=[id@1] -03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id], file_type=parquet, predicate=get_field(s@1, value) > 100 +03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id], file_type=parquet, predicate=get_field(s@1, value) > 100, pruning_predicate=get_field(s@1, value)_null_count@1 != row_count@2 AND get_field(s@1, value)_max@0 > 100, required_guarantees=[] 04)--FilterExec: __datafusion_extracted_2@0 > 3, projection=[id@1] -05)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/join_right.parquet]]}, projection=[get_field(s@1, level) as __datafusion_extracted_2, id], file_type=parquet, predicate=get_field(s@1, level) > 3 AND DynamicFilter [ empty ], dynamic_rg_pruning=eligible +05)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/join_right.parquet]]}, projection=[get_field(s@1, level) as __datafusion_extracted_2, id], file_type=parquet, predicate=get_field(s@1, level) > 3 AND DynamicFilter [ empty ], dynamic_rg_pruning=eligible, pruning_predicate=get_field(s@1, level)_null_count@1 != row_count@2 AND get_field(s@1, level)_max@0 > 3, required_guarantees=[] # Verify correctness - id matches, value > 100, and level > 3 # Matching ids where value > 100: 2(200), 3(150), 4(300), 5(250) @@ -1594,7 +1594,7 @@ physical_plan 01)ProjectionExec: expr=[id@0 as id, __datafusion_extracted_2@1 as simple_struct.s[value], __datafusion_extracted_3@2 as join_right.s[level]] 02)--HashJoinExec: mode=CollectLeft, join_type=Right, on=[(id@0, id@1)], projection=[id@3, __datafusion_extracted_2@2, __datafusion_extracted_3@1] 03)----FilterExec: __datafusion_extracted_1@0 > 5, projection=[id@1, __datafusion_extracted_3@2] -04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/join_right.parquet]]}, projection=[get_field(s@1, level) as __datafusion_extracted_1, id, get_field(s@1, level) as __datafusion_extracted_3], file_type=parquet, predicate=get_field(s@1, level) > 5 +04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/join_right.parquet]]}, projection=[get_field(s@1, level) as __datafusion_extracted_1, id, get_field(s@1, level) as __datafusion_extracted_3], file_type=parquet, predicate=get_field(s@1, level) > 5, pruning_predicate=get_field(s@1, level)_null_count@1 != row_count@2 AND get_field(s@1, level)_max@0 > 5, required_guarantees=[] 05)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_2, id], file_type=parquet # Verify correctness - left join with level > 5 condition @@ -1727,7 +1727,7 @@ logical_plan 05)--------TableScan: simple_struct projection=[id, s], partial_filters=[get_field(simple_struct.s, Utf8("value")) > Int64(200)] physical_plan 01)FilterExec: __datafusion_extracted_1@0 > 200, projection=[id@1] -02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id], file_type=parquet, predicate=get_field(s@1, value) > 200 +02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/simple.parquet]]}, projection=[get_field(s@1, value) as __datafusion_extracted_1, id], file_type=parquet, predicate=get_field(s@1, value) > 200, pruning_predicate=get_field(s@1, value)_null_count@1 != row_count@2 AND get_field(s@1, value)_max@0 > 200, required_guarantees=[] # Verify correctness query I @@ -2557,7 +2557,7 @@ physical_plan 04)------SortExec: expr=[device@0 ASC NULLS LAST, timestamp@2 ASC NULLS LAST], preserve_partitioning=[false] 05)--------ProjectionExec: expr=[__datafusion_extracted_1@0 as device, __datafusion_extracted_2@1 as user, timestamp@2 as timestamp] 06)----------FilterExec: date@2 = 2025-01-03 AND __datafusion_extracted_1@0 IS NOT NULL AND __datafusion_extracted_1@0 != AND __datafusion_extracted_2@1 IS NOT NULL AND __datafusion_extracted_2@1 != , projection=[__datafusion_extracted_1@0, __datafusion_extracted_2@1, timestamp@3] -07)------------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/events.parquet]]}, projection=[get_field(ids@2, id1) as __datafusion_extracted_1, get_field(structs@3, var1) as __datafusion_extracted_2, date, timestamp], file_type=parquet, predicate=date@0 = 2025-01-03 AND get_field(ids@2, id1) IS NOT NULL AND get_field(ids@2, id1) != AND get_field(structs@3, var1) IS NOT NULL AND get_field(structs@3, var1) != , pruning_predicate=date_null_count@2 != row_count@3 AND date_min@0 <= 2025-01-03 AND 2025-01-03 <= date_max@1, required_guarantees=[date in (2025-01-03)] +07)------------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/projection_pushdown/events.parquet]]}, projection=[get_field(ids@2, id1) as __datafusion_extracted_1, get_field(structs@3, var1) as __datafusion_extracted_2, date, timestamp], file_type=parquet, predicate=date@0 = 2025-01-03 AND get_field(ids@2, id1) IS NOT NULL AND get_field(ids@2, id1) != AND get_field(structs@3, var1) IS NOT NULL AND get_field(structs@3, var1) != , pruning_predicate=date_null_count@2 != row_count@3 AND date_min@0 <= 2025-01-03 AND 2025-01-03 <= date_max@1 AND get_field(ids@2, id1)_null_count@4 != row_count@3 AND get_field(ids@2, id1)_null_count@4 != row_count@3 AND (get_field(ids@2, id1)_min@5 != OR != get_field(ids@2, id1)_max@6) AND get_field(structs@3, var1)_null_count@7 != row_count@3 AND get_field(structs@3, var1)_null_count@7 != row_count@3 AND (get_field(structs@3, var1)_min@8 != OR != get_field(structs@3, var1)_max@9), required_guarantees=[date in (2025-01-03)] statement ok DROP TABLE events_pq; diff --git a/docs/source/library-user-guide/upgrading/57.0.0.md b/docs/source/library-user-guide/upgrading/57.0.0.md index 9621d51aa9f23..2411e4643ac81 100644 --- a/docs/source/library-user-guide/upgrading/57.0.0.md +++ b/docs/source/library-user-guide/upgrading/57.0.0.md @@ -12,6 +12,26 @@ SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one in this section pertains to features and changes that have already been merged to the main branch and are awaiting release in this version. +### `PruningStatistics` moved to `datafusion-physical-expr-common` + +The `PruningStatistics` trait and its helpers `PartitionPruningStatistics`, +`PrunableStatistics` and `CompositePruningStatistics` moved from +`datafusion_common::pruning` to `datafusion_physical_expr_common::pruning`. +The trait needs to name `PhysicalExpr`, which `datafusion-common` cannot do. + +The old path has no deprecated re-export. `datafusion-physical-expr-common` +depends on `datafusion-common`, so a re-export would be a dependency cycle. +`datafusion_pruning::PruningStatistics` is unchanged. + +Update the imports: + +```rust +// Before +use datafusion_common::pruning::PruningStatistics; +// After +use datafusion_physical_expr_common::pruning::PruningStatistics; +``` + ### Removed temporary aggregation migration flag The `datafusion.execution.enable_migration_aggregate` flag provided a temporary