Skip to content
Open
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
87 changes: 83 additions & 4 deletions crates/datafusion/src/read/file_scan_task_provider/eager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ use super::provider::{FileScanTaskProvider, FileScanTaskProviderContext};

/// Files discovered before execution, in groups that each become one output
/// partition. Group order and empty groups are retained.
/// Row estimates sum the retained file record counts before predicates and deletes.
/// 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.
#[derive(Debug)]
pub struct EagerFileScanTaskProvider {
file_scan_tasks: Vec<Vec<FileScanTask>>,
Expand Down Expand Up @@ -97,8 +99,10 @@ impl FileScanTaskProvider for EagerFileScanTaskProvider {
rows.checked_add(usize::try_from(task.record_count()?).ok()?)
});
// Predicates and deletes may reduce a positive count, but cannot add rows.
let exact = groups.iter().flatten().all(returns_every_record);
let num_rows = match rows {
Some(0) => Precision::Exact(0),
Some(rows) if exact => Precision::Exact(rows),
Some(rows) => Precision::Inexact(rows),
None => Precision::Absent,
};
Expand Down Expand Up @@ -129,9 +133,20 @@ impl FileScanTaskProvider for EagerFileScanTaskProvider {
}
}

/// Whether `task` reads a whole file with no row predicate and no deletes, so it
/// returns exactly its record count.
fn returns_every_record(task: &FileScanTask) -> bool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked if we could potentially use delete metadata do cover more cases, but it'd go beyond what other engines do. Makes sense to stick with this.

  • Spark + Iceberg Java: For an eligible COUNT(*), Spark evaluates the aggregate from Iceberg file metrics and returns a local result. If any planned task has an attached delete, it declines the pushdown for the whole aggregate. That includes both v2 position deletes and v3 deletion vectors. Spark scan builder · Java delete index
  • Trino: It keeps the aggregate in the plan. For a whole-file split with no residual filter or deletes, COUNT(*) needs no data columns, so Trino can synthesize pages from the manifest’s row count. If a split has v2 position deletes or a v3 DV, it takes the regular reader path and applies the deletes. That decision is per split, so eligible clean files can still take the shortcut in the same query. Trino page source

task.predicate().is_none()
&& task.deletes().is_empty()
&& task.start() == 0
&& task.length() == task.file_size_in_bytes()
}

#[cfg(test)]
mod tests {
use iceberg::spec::{DataFileFormat, Schema as IcebergSchema};
use iceberg::expr::BoundPredicate;
use iceberg::scan::FileScanTaskDeleteFile;
use iceberg::spec::{DataContentType, DataFileFormat, Schema as IcebergSchema};

use super::*;

Expand All @@ -155,19 +170,83 @@ mod tests {
Ok(())
}

#[test]
fn whole_files_without_predicates_or_deletes_have_an_exact_row_count() -> Result<()> {
let provider = EagerFileScanTaskProvider::try_new(vec![
vec![file_task(Some(10)), file_task(Some(5))],
vec![file_task(Some(7))],
])?;
let schema = Schema::empty();
assert_eq!(
provider.partition_statistics(None, &schema)?.num_rows,
Precision::Exact(22)
);
assert_eq!(
provider.partition_statistics(Some(1), &schema)?.num_rows,
Precision::Exact(7)
);
Ok(())
}

#[test]
fn a_task_that_may_drop_rows_makes_only_its_partition_inexact() -> Result<()> {
let with_predicate = task(Some(10), 2, Some(BoundPredicate::AlwaysTrue), vec![]);
let with_delete = task(Some(10), 2, None, vec![position_delete_file()]);
let half_the_file = task(Some(10), 1, None, vec![]);
for inexact in [with_predicate, with_delete, half_the_file] {
let provider = EagerFileScanTaskProvider::try_new(vec![
vec![inexact],
vec![file_task(Some(7))],
])?;
let schema = Schema::empty();
assert_eq!(
provider.partition_statistics(None, &schema)?.num_rows,
Precision::Inexact(17)
);
assert_eq!(
provider.partition_statistics(Some(1), &schema)?.num_rows,
Precision::Exact(7)
);
}
Ok(())
}

// Only metadata is inspected; these files are never opened.
fn file_task(record_count: Option<u64>) -> FileScanTask {
task(record_count, 2, None, vec![])
}

/// A task for `length` bytes of a two-byte file.
fn task(
record_count: Option<u64>,
length: u64,
predicate: Option<BoundPredicate>,
deletes: Vec<FileScanTaskDeleteFile>,
) -> FileScanTask {
FileScanTask::builder()
.with_file_size_in_bytes(1)
.with_file_size_in_bytes(2)
.with_start(0)
.with_length(1)
.with_length(length)
.with_record_count(record_count)
.with_data_file_path("data.parquet".to_string())
.with_data_file_format(DataFileFormat::Parquet)
.with_schema(Arc::new(IcebergSchema::builder().build().unwrap()))
.with_project_field_ids(vec![])
.with_predicate(predicate)
.with_deletes(deletes)
.with_case_sensitive(true)
.build()
.unwrap()
}

fn position_delete_file() -> FileScanTaskDeleteFile {
FileScanTaskDeleteFile::builder()
.with_file_path("deletes.parquet".to_string())
.with_file_size_in_bytes(1)
.with_file_type(DataContentType::PositionDeletes)
.with_file_format(DataFileFormat::Parquet)
.with_partition_spec_id(0)
.build()
.unwrap()
}
}
10 changes: 5 additions & 5 deletions crates/datafusion/tests/file_scan_task_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,9 +229,9 @@ async fn eager_file_statistics_apply_fetch_per_partition() -> Result<()> {
// Each of the two file groups contributes three rows to the assignment.
let plan = harness.physical_plan("SELECT id FROM items").await?;
insta::assert_snapshot!(harness.source_statistics(&plan)?, @"
all partitions (2): Rows=Inexact(6), Bytes=Inexact(48), [(Col[0]:)]
partition 0: Rows=Inexact(3), Bytes=Inexact(24), [(Col[0]:)]
partition 1: Rows=Inexact(3), Bytes=Inexact(24), [(Col[0]:)]
all partitions (2): Rows=Exact(6), Bytes=Exact(48), [(Col[0]:)]
partition 0: Rows=Exact(3), Bytes=Exact(24), [(Col[0]:)]
partition 1: Rows=Exact(3), Bytes=Exact(24), [(Col[0]:)]
");

// Fetch caps each source partition at two rows, not the whole assignment.
Expand All @@ -240,8 +240,8 @@ async fn eager_file_statistics_apply_fetch_per_partition() -> Result<()> {
.await?;
insta::assert_snapshot!(harness.source_statistics(&plan)?, @"
all partitions (2): Rows=Inexact(4), Bytes=Inexact(32), [(Col[0]:)]
partition 0: Rows=Inexact(2), Bytes=Inexact(16), [(Col[0]:)]
partition 1: Rows=Inexact(2), Bytes=Inexact(16), [(Col[0]:)]
partition 0: Rows=Exact(2), Bytes=Exact(16), [(Col[0]:)]
partition 1: Rows=Exact(2), Bytes=Exact(16), [(Col[0]:)]
");
Ok(())
}
Expand Down
53 changes: 52 additions & 1 deletion crates/datafusion/tests/statistics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,13 @@

#[cfg(test)]
mod tests {
use std::sync::Arc;

use datafusion::error::Result;
use iceberg_datafusion::{IcebergDataFusionConfig, IcebergTableProviderFactory};
use iceberg_datafusion_test_tools::{IcebergTestHarness, create_taxi_table};
use iceberg_datafusion_test_tools::{
IcebergTestHarness, ReadCountingStorageFactory, create_taxi_table,
};

#[tokio::test]
async fn reports_the_snapshot_row_count_to_datafusion() -> Result<()> {
Expand Down Expand Up @@ -78,4 +82,51 @@ mod tests {
");
Ok(())
}

#[tokio::test]
async fn eager_count_star_is_answered_without_reading_data_files() -> Result<()> {
let storage = ReadCountingStorageFactory::default();
let harness = IcebergTestHarness::builder()
.with_iceberg_table_factory(
IcebergTableProviderFactory::new_with_storage_factory(Arc::new(
storage.clone(),
)),
)
.with_table(create_taxi_table().await?)
.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("datafusion.execution.target_partitions", 2)
.build()
.await?;

// Taxi has seven daily files of 25,000 rows and no deletes.
let (plan, _) = harness.query("SELECT count(*) FROM taxi").await?;
insta::assert_snapshot!(plan, @"
ProjectionExec: expr=[175000 as count(*)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we add a test for the inexact case that shows the full plan as well?

PlaceholderRowExec
");
assert_eq!(storage.take_reads(), 0);

// A pushed-down predicate may drop rows, so the files are still read.
let (_, rows) = harness
.query("SELECT count(*) FROM taxi WHERE pickup_date = DATE '2024-01-10'")
.await?;
insta::assert_snapshot!(rows, @"
+----------+
| count(*) |
+----------+
| 25000 |
+----------+
");
assert_ne!(storage.take_reads(), 0);
Ok(())
}
}