Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
36 changes: 36 additions & 0 deletions crates/datafusion/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
4 changes: 4 additions & 0 deletions crates/datafusion/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
57 changes: 50 additions & 7 deletions crates/datafusion/src/read/file_scan_task_provider/eager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<Vec<FileScanTask>>,
// 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<i32, usize>,
}

impl EagerFileScanTaskProvider {
Expand All @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down
28 changes: 27 additions & 1 deletion crates/datafusion/src/read/file_scan_task_provider/lazy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -56,6 +58,7 @@ pub struct LazyFileScanTaskProvider {
projection: Vec<String>,
predicate: Option<Predicate>,
target_partitions: usize,
column_stats_enabled: bool,
}

/// Sibling state for one execution, initialized when its first reader is polled.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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);
}
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions crates/datafusion/src/read/file_scan_task_provider/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
mod eager;
mod lazy;
mod provider;
mod statistics;

pub use eager::EagerFileScanTaskProvider;
pub use lazy::{FileScanTaskProviderBuilder, LazyFileScanTaskProvider};
Expand Down
Loading