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 bbdd672..5be1110 100644 --- a/crates/datafusion/src/read/file_scan_task_provider/eager.rs +++ b/crates/datafusion/src/read/file_scan_task_provider/eager.rs @@ -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>, @@ -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, }; @@ -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 { + 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::*; @@ -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) -> FileScanTask { + task(record_count, 2, None, vec![]) + } + + /// A task for `length` bytes of a two-byte file. + fn task( + record_count: Option, + length: u64, + predicate: Option, + deletes: Vec, + ) -> 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() + } } diff --git a/crates/datafusion/tests/file_scan_task_provider.rs b/crates/datafusion/tests/file_scan_task_provider.rs index c9c3447..622543a 100644 --- a/crates/datafusion/tests/file_scan_task_provider.rs +++ b/crates/datafusion/tests/file_scan_task_provider.rs @@ -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. @@ -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(()) } diff --git a/crates/datafusion/tests/statistics.rs b/crates/datafusion/tests/statistics.rs index eafa31b..87c7f29 100644 --- a/crates/datafusion/tests/statistics.rs +++ b/crates/datafusion/tests/statistics.rs @@ -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<()> { @@ -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(*)] + 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(()) + } }