From 155a40394d997ed1753874aa3419d3012282b07a Mon Sep 17 00:00:00 2001 From: "alex.bianchi" Date: Fri, 4 Dec 2026 01:09:09 +0000 Subject: [PATCH] feat: add eager Iceberg column statistics --- crates/datafusion/README.md | 36 ++ crates/datafusion/src/config.rs | 4 + .../src/read/file_scan_task_provider/eager.rs | 57 +++- .../src/read/file_scan_task_provider/lazy.rs | 28 +- .../src/read/file_scan_task_provider/mod.rs | 1 + .../file_scan_task_provider/statistics.rs | 184 ++++++++++ crates/datafusion/tests/statistics.rs | 316 ++++++++++++++++++ 7 files changed, 618 insertions(+), 8 deletions(-) create mode 100644 crates/datafusion/src/read/file_scan_task_provider/statistics.rs diff --git a/crates/datafusion/README.md b/crates/datafusion/README.md index 134a8eff..7c742758 100644 --- a/crates/datafusion/README.md +++ b/crates/datafusion/README.md @@ -20,3 +20,39 @@ # Apache Iceberg DataFusion Integration This crate contains the integration of Apache DataFusion and Apache Iceberg. + +## Eager column statistics + +Column statistics are opt-in: + +```rust +use datafusion::prelude::SessionConfig; +use iceberg_datafusion::IcebergDataFusionConfig; + +let config = SessionConfig::new() + .with_option_extension(IcebergDataFusionConfig::default()) + .set_bool("iceberg.execution.eager_file_planning", true) + .set_bool("iceberg.execution.column_stats_enabled", true); +``` + +Discovery retains projected columns' file metrics in the native Iceberg tasks. +`EagerFileScanTaskProvider` aggregates bounds, null counts and byte estimates for +its complete assignment or for the requested partition. Reconstructing a provider +from assigned task groups preserves these file metrics without reopening manifests. +Missing metrics stay unknown. Bounds are inexact; floating-point bounds require a +known zero NaN count. Predicates, deletes and file splits leave column statistics +unknown for the affected assignment because file metrics describe the unfiltered +whole file. + +Fixed-width byte estimates use Arrow widths and record counts, not compressed +Parquet sizes. For other columns, file column sizes provide inexact estimates. +The common data source applies its fetch limit to the provider's statistics. + +When available, discovery also reads distinct-value estimates from the selected +snapshot's Theta blob metadata (`ndv`); it does not open Puffin files. These estimates +belong to the complete snapshot scan. They are not copied to individual partitions +(unless there is only one), and reconstructing a provider from groups drops them. +Snapshot NDVs are neither summed across files nor treated as worker-local counts. + +Lazy scans keep their existing snapshot row estimates; enabling this option does +not perform eager discovery or provide lazy column-statistics estimates. diff --git a/crates/datafusion/src/config.rs b/crates/datafusion/src/config.rs index a1cbb6d6..62238742 100644 --- a/crates/datafusion/src/config.rs +++ b/crates/datafusion/src/config.rs @@ -67,6 +67,10 @@ config_namespace! { /// Discover file tasks in TableProvider::scan instead of at execution, and /// split them across up to the session's target partitions. pub eager_file_planning: bool, default = false + /// Retain projected file column metrics for eager statistics. Snapshot Theta + /// NDVs apply only to the complete scan, not individual file assignments. + /// Lazy scans still report snapshot row estimates without column statistics. + pub column_stats_enabled: bool, default = false /// Maximum concurrent data files per output partition. Zero is treated as one. /// Set to `auto` to use Iceberg's execution-host parallelism. pub data_file_concurrency_limit: DataFileConcurrencyLimit, default = DataFileConcurrencyLimit::default() diff --git a/crates/datafusion/src/read/file_scan_task_provider/eager.rs b/crates/datafusion/src/read/file_scan_task_provider/eager.rs index eb2ce374..e0407d24 100644 --- a/crates/datafusion/src/read/file_scan_task_provider/eager.rs +++ b/crates/datafusion/src/read/file_scan_task_provider/eager.rs @@ -17,7 +17,7 @@ use datafusion::arrow::datatypes::Schema; use datafusion::common::stats::Precision; -use datafusion::common::{Result, Statistics, exec_err}; +use datafusion::common::{HashMap, Result, Statistics, exec_err}; use datafusion::physical_plan::Partitioning; use futures::StreamExt; use futures::stream::BoxStream; @@ -27,15 +27,21 @@ use std::fmt::Formatter; use std::sync::Arc; use super::provider::{FileScanTaskProvider, FileScanTaskProviderContext}; +use super::statistics::column_statistics; /// Files discovered before execution, in groups that each become one output /// partition. Group order and empty groups are retained. /// Row counts sum the retained file record counts. The sum is exact when every /// task reads a whole file with no row predicate and no deletes, and an upper -/// bound otherwise. +/// bound otherwise. Optional file column metrics are aggregated for the requested +/// assignment only when every task reads all records. Snapshot NDVs are available +/// only on the complete provider produced by discovery, not reconstructed groups. #[derive(Debug)] pub struct EagerFileScanTaskProvider { file_scan_tasks: Vec>, + // Snapshot NDVs are not additive. Only discovery of the complete snapshot + // installs these; reconstruction from assigned groups intentionally omits them. + pub(super) snapshot_ndvs: HashMap, } impl EagerFileScanTaskProvider { @@ -50,7 +56,10 @@ impl EagerFileScanTaskProvider { "An Iceberg task provider requires at least one file group" ); } - Ok(Self { file_scan_tasks }) + Ok(Self { + file_scan_tasks, + snapshot_ndvs: HashMap::new(), + }) } /// All file tasks, in partition order and then group order. @@ -99,16 +108,50 @@ impl FileScanTaskProvider for EagerFileScanTaskProvider { let rows = groups.iter().flatten().try_fold(0_usize, |rows, task| { rows.checked_add(usize::try_from(task.record_count()?).ok()?) }); + let whole_files = groups.iter().flatten().all(returns_every_record); // Predicates and deletes may reduce a positive count, but cannot add rows. let num_rows = match rows { Some(0) => Precision::Exact(0), - Some(rows) if groups.iter().flatten().all(returns_every_record) => { - Precision::Exact(rows) - } + Some(rows) if whole_files => Precision::Exact(rows), Some(rows) => Precision::Inexact(rows), None => Precision::Absent, }; - Ok(Statistics::new_unknown(schema).with_num_rows(num_rows)) + let mut statistics = Statistics::new_unknown(schema).with_num_rows(num_rows); + // File metrics describe whole files, not the rows left by a predicate, + // delete file or split. Keep those scans' column statistics unknown. + if whole_files { + statistics.column_statistics = + column_statistics(groups.iter().flatten(), schema); + // A snapshot NDV belongs to the whole scan. A single partition can + // use it only when that partition is the whole assignment. + if !self.snapshot_ndvs.is_empty() + && (partition.is_none() || self.groups().len() == 1) + && let Some(task) = self.tasks().next() + { + for (field, column) in schema + .fields() + .iter() + .zip(&mut statistics.column_statistics) + { + if let Some(ndv) = task + .schema() + .field_id_by_name(field.name()) + .and_then(|id| self.snapshot_ndvs.get(&id)) + { + column.distinct_count = Precision::Inexact(*ndv); + } + } + } + if !statistics.column_statistics.is_empty() { + statistics.total_byte_size = statistics + .column_statistics + .iter() + .fold(Precision::Exact(0), |total, column| { + total.add(&column.byte_size) + }); + } + } + Ok(statistics) } fn fmt_as(&self, f: &mut Formatter) -> std::fmt::Result { diff --git a/crates/datafusion/src/read/file_scan_task_provider/lazy.rs b/crates/datafusion/src/read/file_scan_task_provider/lazy.rs index 955c5dbc..2b47119b 100644 --- a/crates/datafusion/src/read/file_scan_task_provider/lazy.rs +++ b/crates/datafusion/src/read/file_scan_task_provider/lazy.rs @@ -30,12 +30,14 @@ use datafusion::prelude::Expr; use futures::stream::BoxStream; use futures::{StreamExt, TryStreamExt, stream}; use iceberg::expr::Predicate; +use iceberg::metadata_columns::is_metadata_column_name; use iceberg::scan::{FileScanTask, FileScanTaskStream, TableScan}; use iceberg::spec::SnapshotRef; use iceberg::table::Table; use super::eager::EagerFileScanTaskProvider; use super::provider::{FileScanTaskProvider, FileScanTaskProviderContext}; +use super::statistics::snapshot_ndvs; use crate::IcebergDataFusionConfig; use crate::read::convert_filters_to_predicate; use crate::to_datafusion_error; @@ -56,6 +58,7 @@ pub struct LazyFileScanTaskProvider { projection: Vec, predicate: Option, target_partitions: usize, + column_stats_enabled: bool, } /// Sibling state for one execution, initialized when its first reader is polled. @@ -129,7 +132,12 @@ impl LazyFileScanTaskProvider { if groups.is_empty() { groups.push(Vec::new()); } - EagerFileScanTaskProvider::try_new(groups) + let mut provider = EagerFileScanTaskProvider::try_new(groups)?; + if self.column_stats_enabled { + provider.snapshot_ndvs = + snapshot_ndvs(self.table.metadata(), self.snapshot()); + } + Ok(provider) } /// Table retained for discovery, including its metadata and storage access. @@ -254,7 +262,24 @@ impl FileScanTaskProviderBuilder { } // TableScan resolves and retains the snapshot without discovering files. // Keep that same scan for execution and its snapshot for statistics. + let execution = &IcebergDataFusionConfig::from_config_or_default( + self.context.session_config(), + ) + .execution; + let column_stats_enabled = execution.column_stats_enabled; let mut scan = self.table.scan().select(&projection); + if column_stats_enabled { + scan = scan.with_column_stats( + self.projected_schema + .fields() + .iter() + .filter(|field| { + !field.data_type().is_nested() + && !is_metadata_column_name(field.name()) + }) + .map(|field| field.name()), + ); + } if let Some(snapshot_id) = self.snapshot_id { scan = scan.snapshot_id(snapshot_id); } @@ -270,6 +295,7 @@ impl FileScanTaskProviderBuilder { snapshot_id: self.snapshot_id, predicate: self.predicate, target_partitions, + column_stats_enabled, }; if IcebergDataFusionConfig::from_config_or_default(self.context.session_config()) .execution diff --git a/crates/datafusion/src/read/file_scan_task_provider/mod.rs b/crates/datafusion/src/read/file_scan_task_provider/mod.rs index bbcd343e..47102a7c 100644 --- a/crates/datafusion/src/read/file_scan_task_provider/mod.rs +++ b/crates/datafusion/src/read/file_scan_task_provider/mod.rs @@ -17,6 +17,7 @@ mod eager; mod lazy; mod provider; +mod statistics; pub use eager::EagerFileScanTaskProvider; pub use lazy::{FileScanTaskProviderBuilder, LazyFileScanTaskProvider}; diff --git a/crates/datafusion/src/read/file_scan_task_provider/statistics.rs b/crates/datafusion/src/read/file_scan_task_provider/statistics.rs new file mode 100644 index 00000000..3f2c264d --- /dev/null +++ b/crates/datafusion/src/read/file_scan_task_provider/statistics.rs @@ -0,0 +1,184 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use datafusion::arrow::datatypes::{Field, Schema}; +use datafusion::common::stats::Precision; +use datafusion::common::{ColumnStatistics, HashMap, ScalarValue, Statistics}; +use iceberg::puffin::APACHE_DATASKETCHES_THETA_V1; +use iceberg::scan::FileScanTask; +use iceberg::spec::{Datum, PrimitiveLiteral, PrimitiveType, SnapshotRef, TableMetadata}; + +/// Merge only the supplied files. Missing metrics stay unknown rather than +/// silently treating a file without metrics as contributing zero. +pub(super) fn column_statistics<'a>( + mut tasks: impl Iterator, + schema: &Schema, +) -> Vec { + let Some(first) = tasks.next() else { + return Statistics::unknown_column(schema); + }; + // Without metrics for one file, every aggregate column is unknown. This + // also avoids walking every column of every file when metrics are disabled. + if first.column_stats().is_none() { + return Statistics::unknown_column(schema); + } + let mut columns: Vec<_> = schema + .fields() + .iter() + .map(|field| file_column_statistics(first, field)) + .collect(); + for task in tasks { + if task.column_stats().is_none() { + return Statistics::unknown_column(schema); + } + for (column, field) in columns.iter_mut().zip(schema.fields()) { + let next = file_column_statistics(task, field); + column.null_count = column.null_count.add(&next.null_count); + column.min_value = column.min_value.min(&next.min_value); + column.max_value = column.max_value.max(&next.max_value); + column.byte_size = column.byte_size.add(&next.byte_size); + } + } + columns +} + +fn file_column_statistics(task: &FileScanTask, field: &Field) -> ColumnStatistics { + let mut column = ColumnStatistics::new_unknown(); + let Some(metrics) = task.column_stats() else { + return column; + }; + let Some(id) = task.schema().field_id_by_name(field.name()) else { + return column; + }; + column.null_count = metrics + .null_value_counts() + .get(&id) + .and_then(|value| usize::try_from(*value).ok()) + .map(Precision::Exact) + .unwrap_or(Precision::Absent); + // Iceberg bounds exclude NaNs. They are not bounds on the entire Arrow + // column unless we know there are no NaNs. + if !field.data_type().is_floating() || metrics.nan_value_counts().get(&id) == Some(&0) + { + let bound = |value: &Datum| { + datum_to_scalar(value).and_then(|value| value.cast_to(field.data_type()).ok()) + }; + column.min_value = metrics + .lower_bounds() + .get(&id) + .and_then(bound) + .map(Precision::Inexact) + .unwrap_or(Precision::Absent); + column.max_value = metrics + .upper_bounds() + .get(&id) + .and_then(bound) + .map(Precision::Inexact) + .unwrap_or(Precision::Absent); + } + // Fixed-width estimates follow DataFusion's Arrow-width convention. For + // other columns, file sizes are only an inexact size estimate. + column.byte_size = match field.data_type().primitive_width() { + Some(width) => task + .record_count() + .and_then(|rows| usize::try_from(rows).ok()) + .and_then(|rows| rows.checked_mul(width)) + .map(Precision::Exact), + None => metrics + .column_sizes() + .get(&id) + .and_then(|bytes| usize::try_from(*bytes).ok()) + .map(Precision::Inexact), + } + .unwrap_or(Precision::Absent); + column +} + +/// Read the estimate from metadata, without opening a Puffin file or merging +/// sketches. It is valid for the selected snapshot, not each output partition. +pub(super) fn snapshot_ndvs( + metadata: &TableMetadata, + snapshot: Option<&SnapshotRef>, +) -> HashMap { + let mut ndvs = HashMap::new(); + let Some(snapshot) = snapshot else { + return ndvs; + }; + let Some(statistics) = metadata.statistics_for_snapshot(snapshot.snapshot_id()) + else { + return ndvs; + }; + for blob in &statistics.blob_metadata { + if blob.r#type != APACHE_DATASKETCHES_THETA_V1 + || blob.snapshot_id != snapshot.snapshot_id() + { + continue; + } + let [field] = blob.fields.as_slice() else { + continue; + }; + if let Some(ndv) = blob + .properties + .get("ndv") + .and_then(|value| value.parse().ok()) + { + ndvs.insert(*field, ndv); + } + } + ndvs +} + +fn datum_to_scalar(datum: &Datum) -> Option { + match (datum.data_type(), datum.literal()) { + (PrimitiveType::Boolean, PrimitiveLiteral::Boolean(value)) => { + Some(ScalarValue::Boolean(Some(*value))) + } + (PrimitiveType::Int, PrimitiveLiteral::Int(value)) => { + Some(ScalarValue::Int32(Some(*value))) + } + (PrimitiveType::Long, PrimitiveLiteral::Long(value)) => { + Some(ScalarValue::Int64(Some(*value))) + } + (PrimitiveType::Float, PrimitiveLiteral::Float(value)) => { + Some(ScalarValue::Float32(Some(value.into_inner()))) + } + (PrimitiveType::Double, PrimitiveLiteral::Double(value)) => { + Some(ScalarValue::Float64(Some(value.into_inner()))) + } + (PrimitiveType::String, PrimitiveLiteral::String(value)) => { + Some(ScalarValue::Utf8(Some(value.clone()))) + } + (PrimitiveType::Date, PrimitiveLiteral::Int(value)) => { + Some(ScalarValue::Date32(Some(*value))) + } + (PrimitiveType::Timestamp, PrimitiveLiteral::Long(value)) => { + Some(ScalarValue::TimestampMicrosecond(Some(*value), None)) + } + (PrimitiveType::Timestamptz, PrimitiveLiteral::Long(value)) => Some( + ScalarValue::TimestampMicrosecond(Some(*value), Some("UTC".into())), + ), + ( + PrimitiveType::Decimal { precision, scale }, + PrimitiveLiteral::Int128(value), + ) => Some(ScalarValue::Decimal128( + Some(*value), + *precision as u8, + *scale as i8, + )), + _ => None, + } +} diff --git a/crates/datafusion/tests/statistics.rs b/crates/datafusion/tests/statistics.rs index e69a9819..b304c7dd 100644 --- a/crates/datafusion/tests/statistics.rs +++ b/crates/datafusion/tests/statistics.rs @@ -17,9 +17,25 @@ #[cfg(test)] mod tests { + use std::any::Any; + use std::collections::HashMap; use std::sync::Arc; + use datafusion::arrow::array::{ArrayRef, Int64Array, RecordBatch}; + use datafusion::datasource::source::DataSourceExec; + use iceberg::puffin::APACHE_DATASKETCHES_THETA_V1; + use iceberg::spec::{ + BlobMetadata, NestedField, PrimitiveType, Schema, StatisticsFile, Type, + }; + use iceberg::table::Table; + use iceberg::{Runtime, TableIdent}; + use iceberg_datafusion::read::{EagerFileScanTaskProvider, IcebergDataSource}; + use iceberg_datafusion::{IcebergCatalogProvider, to_datafusion_error}; + use iceberg_datafusion_test_tools::{FixtureCatalog, FixtureTable}; + use parquet::file::properties::{EnabledStatistics, WriterProperties}; + use datafusion::error::Result; + use datafusion::physical_plan::ExecutionPlan; use iceberg_datafusion::{IcebergDataFusionConfig, IcebergTableProviderFactory}; use iceberg_datafusion_test_tools::{ IcebergTestHarness, ReadCountingStorageFactory, create_taxi_table, @@ -100,6 +116,255 @@ mod tests { Ok(()) } + #[tokio::test] + async fn eager_column_statistics_follow_projection_and_fetch() -> Result<()> { + let mut table = empty_items().await?; + table + .append() + .file(items(vec![1, 2, 3], vec![Some(10), None, Some(30)])?) + .file(items(vec![4, 5, 6], vec![Some(40), None, Some(60)])?) + .commit() + .await?; + let harness = IcebergTestHarness::builder() + .with_iceberg_table_factory(IcebergTableProviderFactory::new()) + .with_table(table) + .with_session_extension(|mut state| { + state + .config() + .get_or_insert_default() + .options_mut() + .extensions + .insert(IcebergDataFusionConfig::default()); + state + }) + .with_config_option("iceberg.execution.eager_file_planning", true) + .with_config_option("iceberg.execution.column_stats_enabled", true) + .with_config_option("datafusion.execution.target_partitions", 1) + .build() + .await?; + // Only value (field id 2) is projected, not the id column's bounds. + let plan = harness.physical_plan("SELECT value FROM items").await?; + insta::assert_snapshot!(harness.source_statistics(&plan)?, @" + all partitions (1): Rows=Exact(6), Bytes=Exact(48), [(Col[0]: Min=Inexact(Int64(10)) Max=Inexact(Int64(60)) Null=Exact(2) ScanBytes=Exact(48))] + partition 0: Rows=Exact(6), Bytes=Exact(48), [(Col[0]: Min=Inexact(Int64(10)) Max=Inexact(Int64(60)) Null=Exact(2) ScanBytes=Exact(48))] + "); + + let limited = harness + .physical_plan("SELECT value FROM items LIMIT 2") + .await?; + insta::assert_snapshot!(harness.source_statistics(&limited)?, @" + all partitions (1): Rows=Exact(2), Bytes=Inexact(16), [(Col[0]: Min=Inexact(Int64(10)) Max=Inexact(Int64(60)) Null=Inexact(2) ScanBytes=Inexact(16))] + partition 0: Rows=Exact(2), Bytes=Inexact(16), [(Col[0]: Min=Inexact(Int64(10)) Max=Inexact(Int64(60)) Null=Inexact(2) ScanBytes=Inexact(16))] + "); + Ok(()) + } + + #[tokio::test] + async fn eager_column_statistics_follow_assignments_but_snapshot_ndvs_do_not() + -> Result<()> { + let mut fixture = empty_items().await?; + let files = fixture + .append() + .file(items(vec![1, 2, 3], vec![Some(10), None, Some(30)])?) + .file(items(vec![4, 5, 6], vec![Some(40), None, Some(60)])?) + .commit() + .await?; + fixture + .append() + .file(items(vec![7, 8], vec![Some(70), Some(80)])?) + .commit() + .await?; + // Snapshot 1 has four distinct non-null values; snapshot 2 has six. + // These metadata-only NDVs need no Puffin file to be opened. + let metadata = fixture + .table() + .metadata() + .clone() + .into_builder(None) + .set_statistics(theta_statistics(1, 2, 4)) + .set_statistics(theta_statistics(2, 2, 6)) + .build() + .map_err(to_datafusion_error)? + .metadata; + let table = Table::builder() + .runtime(Runtime::current()) + .identifier(fixture.ident().clone()) + .file_io(fixture.table().file_io().clone()) + .metadata(metadata) + .build() + .map_err(to_datafusion_error)?; + let catalog = IcebergCatalogProvider::static_builder() + .add_snapshot(table, 1) + .build()?; + let harness = IcebergTestHarness::builder() + .with_catalog("history", Arc::new(catalog)) + .with_session_extension(|mut state| { + state + .config() + .get_or_insert_default() + .options_mut() + .extensions + .insert(IcebergDataFusionConfig::default()); + state + }) + .with_config_option("iceberg.execution.eager_file_planning", true) + .with_config_option("iceberg.execution.column_stats_enabled", true) + .with_config_option("datafusion.execution.target_partitions", 1) + .build() + .await?; + let plan = harness + .physical_plan("SELECT * FROM history.default.items") + .await?; + insta::assert_snapshot!(harness.source_statistics(&plan)?, @" + all partitions (1): Rows=Exact(6), Bytes=Exact(96), [(Col[0]: Min=Inexact(Int64(1)) Max=Inexact(Int64(6)) Null=Exact(0) ScanBytes=Exact(48)),(Col[1]: Min=Inexact(Int64(10)) Max=Inexact(Int64(60)) Null=Exact(2) Distinct=Inexact(4) ScanBytes=Exact(48))] + partition 0: Rows=Exact(6), Bytes=Exact(96), [(Col[0]: Min=Inexact(Int64(1)) Max=Inexact(Int64(6)) Null=Exact(0) ScanBytes=Exact(48)),(Col[1]: Min=Inexact(Int64(10)) Max=Inexact(Int64(60)) Null=Exact(2) Distinct=Inexact(4) ScanBytes=Exact(48))] + "); + + let source = iceberg_source(&plan).unwrap(); + let provider = (source.file_scan_task_provider() as &dyn Any) + .downcast_ref::() + .unwrap(); + let first = provider + .tasks() + .find(|task| task.data_file_path() == files[0].file_path()) + .unwrap() + .clone(); + let second = provider + .tasks() + .find(|task| task.data_file_path() == files[1].file_path()) + .unwrap() + .clone(); + // Assign the second file first and retain an empty output partition. + // File metrics follow these groups; the whole-snapshot NDV must not. + let assigned = source.with_file_scan_task_provider(Arc::new( + EagerFileScanTaskProvider::try_new(vec![vec![second], vec![first], vec![]])?, + ))?; + let assigned: Arc = DataSourceExec::from_data_source(assigned); + insta::assert_snapshot!(harness.source_statistics(&assigned)?, @" + all partitions (3): Rows=Exact(6), Bytes=Exact(96), [(Col[0]: Min=Inexact(Int64(1)) Max=Inexact(Int64(6)) Null=Exact(0) ScanBytes=Exact(48)),(Col[1]: Min=Inexact(Int64(10)) Max=Inexact(Int64(60)) Null=Exact(2) ScanBytes=Exact(48))] + partition 0: Rows=Exact(3), Bytes=Exact(48), [(Col[0]: Min=Inexact(Int64(4)) Max=Inexact(Int64(6)) Null=Exact(0) ScanBytes=Exact(24)),(Col[1]: Min=Inexact(Int64(40)) Max=Inexact(Int64(60)) Null=Exact(1) ScanBytes=Exact(24))] + partition 1: Rows=Exact(3), Bytes=Exact(48), [(Col[0]: Min=Inexact(Int64(1)) Max=Inexact(Int64(3)) Null=Exact(0) ScanBytes=Exact(24)),(Col[1]: Min=Inexact(Int64(10)) Max=Inexact(Int64(30)) Null=Exact(1) ScanBytes=Exact(24))] + partition 2: Rows=Exact(0), Bytes=Exact(0), [(Col[0]:),(Col[1]:)] + "); + Ok(()) + } + + #[tokio::test] + async fn eager_column_statistics_with_predicates_stay_unknown() -> Result<()> { + let mut table = empty_items().await?; + table + .append() + .file(items(vec![1, 2, 3], vec![Some(10), None, Some(30)])?) + .file(items(vec![4, 5, 6], vec![Some(40), None, Some(60)])?) + .commit() + .await?; + let harness = IcebergTestHarness::builder() + .with_iceberg_table_factory(IcebergTableProviderFactory::new()) + .with_table(table) + .with_session_extension(|mut state| { + state + .config() + .get_or_insert_default() + .options_mut() + .extensions + .insert(IcebergDataFusionConfig::default()); + state + }) + .with_config_option("iceberg.execution.eager_file_planning", true) + .with_config_option("iceberg.execution.column_stats_enabled", true) + .with_config_option("datafusion.execution.target_partitions", 1) + .build() + .await?; + let plan = harness + .physical_plan("SELECT value FROM items WHERE value >= 30") + .await?; + insta::assert_snapshot!(harness.source_statistics(&plan)?, @" + all partitions (1): Rows=Inexact(6), Bytes=Inexact(48), [(Col[0]:)] + partition 0: Rows=Inexact(6), Bytes=Inexact(48), [(Col[0]:)] + "); + Ok(()) + } + + #[tokio::test] + async fn eager_column_statistics_with_deletes_stay_unknown() -> Result<()> { + let mut table = empty_items().await?; + let files = table + .append() + .file(items(vec![1, 2, 3], vec![Some(10), None, Some(30)])?) + .file(items(vec![4, 5, 6], vec![Some(40), None, Some(60)])?) + .commit() + .await?; + // Removing a null row makes the manifest's null count stale. + table.delete_positions(&[(&files[0], 1)]).await?; + let harness = IcebergTestHarness::builder() + .with_iceberg_table_factory(IcebergTableProviderFactory::new()) + .with_table(table) + .with_session_extension(|mut state| { + state + .config() + .get_or_insert_default() + .options_mut() + .extensions + .insert(IcebergDataFusionConfig::default()); + state + }) + .with_config_option("iceberg.execution.eager_file_planning", true) + .with_config_option("iceberg.execution.column_stats_enabled", true) + .with_config_option("datafusion.execution.target_partitions", 1) + .build() + .await?; + let plan = harness.scan().await?; + insta::assert_snapshot!(harness.source_statistics(&plan)?, @" + all partitions (1): Rows=Inexact(6), Bytes=Inexact(96), [(Col[0]:),(Col[1]:)] + partition 0: Rows=Inexact(6), Bytes=Inexact(96), [(Col[0]:),(Col[1]:)] + "); + Ok(()) + } + + #[tokio::test] + async fn eager_column_statistics_do_not_ignore_files_with_missing_metrics() + -> Result<()> { + let mut table = empty_items().await?; + table + .append() + .file(items(vec![1, 2, 3], vec![Some(10), None, Some(30)])?) + .commit() + .await?; + table + .append() + .writer_properties( + WriterProperties::builder() + .set_statistics_enabled(EnabledStatistics::None) + .build(), + ) + .file(items(vec![4, 5, 6], vec![Some(40), None, Some(60)])?) + .commit() + .await?; + let harness = IcebergTestHarness::builder() + .with_iceberg_table_factory(IcebergTableProviderFactory::new()) + .with_table(table) + .with_session_extension(|mut state| { + state + .config() + .get_or_insert_default() + .options_mut() + .extensions + .insert(IcebergDataFusionConfig::default()); + state + }) + .with_config_option("iceberg.execution.eager_file_planning", true) + .with_config_option("iceberg.execution.column_stats_enabled", true) + .with_config_option("datafusion.execution.target_partitions", 1) + .build() + .await?; + let plan = harness.scan().await?; + insta::assert_snapshot!(harness.source_statistics(&plan)?, @" + all partitions (1): Rows=Exact(6), Bytes=Exact(96), [(Col[0]: ScanBytes=Exact(48)),(Col[1]: ScanBytes=Exact(48))] + partition 0: Rows=Exact(6), Bytes=Exact(96), [(Col[0]: ScanBytes=Exact(48)),(Col[1]: ScanBytes=Exact(48))] + "); + Ok(()) + } + async fn eager_taxi_harness( storage: &ReadCountingStorageFactory, ) -> Result { @@ -174,4 +439,55 @@ mod tests { assert_ne!(storage.take_reads(), 0); Ok(()) } + + fn iceberg_source(plan: &Arc) -> Option<&IcebergDataSource> { + plan.downcast_ref::() + .and_then(|exec| exec.data_source().downcast_ref::()) + .or_else(|| plan.children().into_iter().find_map(iceberg_source)) + } + + async fn empty_items() -> Result { + let schema = Schema::builder() + .with_fields(vec![ + NestedField::required(1, "id", Type::Primitive(PrimitiveType::Long)) + .into(), + NestedField::optional(2, "value", Type::Primitive(PrimitiveType::Long)) + .into(), + ]) + .build() + .map_err(to_datafusion_error)?; + FixtureCatalog::try_new() + .await? + .table( + TableIdent::from_strs(["default", "items"]) + .map_err(to_datafusion_error)?, + schema, + ) + .create() + .await + } + + fn items(ids: Vec, values: Vec>) -> Result { + Ok(RecordBatch::try_from_iter([ + ("id", Arc::new(Int64Array::from(ids)) as ArrayRef), + ("value", Arc::new(Int64Array::from(values)) as ArrayRef), + ])?) + } + + fn theta_statistics(snapshot_id: i64, field_id: i32, ndv: usize) -> StatisticsFile { + StatisticsFile { + snapshot_id, + statistics_path: format!("not-opened-{snapshot_id}.puffin"), + file_size_in_bytes: 0, + file_footer_size_in_bytes: 0, + key_metadata: None, + blob_metadata: vec![BlobMetadata { + r#type: APACHE_DATASKETCHES_THETA_V1.to_owned(), + snapshot_id, + sequence_number: snapshot_id, + fields: vec![field_id], + properties: HashMap::from([("ndv".to_owned(), ndv.to_string())]), + }], + } + } }