Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
6402820
test: add slt for statistics pruning on struct fields
adriangb Nov 25, 2026
4d70bd8
refactor: move PruningStatistics to datafusion-physical-expr-common
adriangb Nov 25, 2026
0ee45b7
feat: add expression statistics methods to PruningStatistics
adriangb Nov 25, 2026
d7a2923
refactor: pass read-only pruning predicate settings as a context
adriangb Nov 25, 2026
ffe9e21
refactor: key pruning statistics by a column or an expression
adriangb Nov 25, 2026
07ca515
feat: let a matcher mark expressions that have their own statistics
adriangb Nov 25, 2026
fec95c5
feat: prune Parquet row groups with expression statistics resolvers
adriangb Nov 25, 2026
a735fe4
feat: prune Parquet pages with expression statistics resolvers
adriangb Nov 25, 2026
eac45c1
test: prune row groups with a resolver from outside DataFusion
adriangb Nov 25, 2026
19bbc7a
test: add slt for dynamic TopK on a struct field
adriangb Nov 25, 2026
e4fe468
feat: give the dynamic row group pruner the scan's statistics resolvers
adriangb Nov 25, 2026
9279e59
feat: prune IS [NOT] NULL on expressions with their own statistics
adriangb Nov 25, 2026
223b5b1
test: add slt for struct field pruning under type drift
adriangb Nov 25, 2026
3539306
feat: prune CAST, TRY_CAST and NOT over expressions with own statistics
adriangb Nov 25, 2026
3338792
feat: prune boolean expressions with their own statistics
adriangb Nov 25, 2026
479efb3
test: add slt for a long IN list on a struct field
adriangb Nov 25, 2026
0bf822d
feat: use the compact IN-list pruning form for statistics keys
adriangb Nov 25, 2026
29c0bca
feat: literal guarantees for expressions with their own statistics
adriangb Nov 25, 2026
c682eb8
test: add slt for bloom filters on struct fields
adriangb Nov 25, 2026
16afa88
feat: prune Parquet row groups with bloom filters on struct fields
adriangb Nov 25, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion datafusion-examples/examples/data_io/parquet_index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand All @@ -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::*;
Expand Down
2 changes: 1 addition & 1 deletion datafusion-examples/examples/query_planning/pruning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down
2 changes: 1 addition & 1 deletion datafusion/catalog-listing/src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand Down
1 change: 0 additions & 1 deletion datafusion/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
255 changes: 255 additions & 0 deletions datafusion/core/tests/parquet/expr_statistics_resolver.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,255 @@
// 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 resolver 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, 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::prelude::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::{
ExprStatisticsKind, ParquetLeafStatistics, ParquetStatisticsResolver,
leaf_index_by_path,
};
use datafusion_execution::object_store::ObjectStoreUrl;
use datafusion_expr::{
ColumnarValue, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature, Volatility,
col, lit,
};
use datafusion_physical_expr::expressions::{Column, Literal};
use datafusion_physical_expr::{PhysicalExpr, ScalarFunctionExpr};
use datafusion_physical_plan::ExecutionPlan;
use datafusion_physical_plan::metrics::MetricValue;
use parquet::arrow::ArrowWriter;
use parquet::file::properties::WriterProperties;
use tempfile::NamedTempFile;

use crate::parquet::utils::MetricsFinder;

/// Returns `v.typed_value.<key>`. 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<DataType> {
Ok(DataType::Int64)
}

fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
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<dyn PhysicalExpr>) -> Option<(&str, &str)> {
let func = expr.downcast_ref::<ScalarFunctionExpr>()?;
if func.name() != "fake_variant_get" {
return None;
}
let [column, key] = func.args() else {
return None;
};
let column = column.downcast_ref::<Column>()?;
let ScalarValue::Utf8(Some(key)) = key.downcast_ref::<Literal>()?.value() else {
return None;
};
Some((column.name(), key.as_str()))
}
}

impl ParquetStatisticsResolver for FakeVariantResolver {
fn matches(&self, expr: &Arc<dyn PhysicalExpr>) -> bool {
Self::args(expr).is_some()
}

fn statistics(
&self,
expr: &Arc<dyn PhysicalExpr>,
kind: ExprStatisticsKind,
statistics: &dyn ParquetLeafStatistics,
) -> Option<ArrayRef> {
let (column, key) = Self::args(expr)?;
let parquet_schema = statistics.parquet_schema();
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"])?;
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(typed, &typed_field)?,
ExprStatisticsKind::Max => statistics.leaf_maxes(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(fallback, &fallback_field)?;
let rows = statistics.row_counts()?;
let fallback_nulls = fallback_nulls.as_any().downcast_ref::<UInt64Array>()?;
let rows = rows.as_any().downcast_ref::<UInt64Array>()?;
// 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, &not_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<dyn ExecutionPlan> = 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())
}

#[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));
}
1 change: 1 addition & 0 deletions datafusion/core/tests/parquet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading