gabotechs commented on code in PR #113:
URL:
https://github.com/apache/datafusion-iceberg/pull/113#discussion_r4611129599
##########
crates/datafusion/src/read/scan.rs:
##########
@@ -15,162 +15,210 @@
// specific language governing permissions and limitations
// under the License.
-use std::pin::Pin;
+use std::fmt::{Debug, Formatter};
use std::sync::Arc;
-use datafusion::arrow::array::RecordBatch;
+use super::file_scan_task_provider::{FileScanTaskProvider,
FileScanTaskProviderContext};
+use crate::to_datafusion_error;
+
use datafusion::arrow::datatypes::SchemaRef as ArrowSchemaRef;
-use datafusion::common::Statistics;
use datafusion::common::tree_node::TreeNodeRecursion;
+use datafusion::common::{Statistics, exec_datafusion_err, exec_err};
use datafusion::datasource::source::DataSource;
use datafusion::error::Result;
use datafusion::execution::{SendableRecordBatchStream, TaskContext};
use datafusion::physical_expr::projection::ProjectionExprs;
use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr};
+use datafusion::physical_plan::limit::LimitStream;
+use datafusion::physical_plan::metrics::{BaselineMetrics,
ExecutionPlanMetricsSet};
use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
use datafusion::physical_plan::{DisplayFormatType, Partitioning};
-use datafusion::prelude::Expr;
-use futures::{Stream, TryStreamExt};
-use iceberg::expr::Predicate;
-use iceberg::table::Table;
-
-use super::predicate::convert_filters_to_predicate;
-use crate::to_datafusion_error;
+use datafusion::prelude::SessionConfig;
+use futures::TryStreamExt;
+use iceberg::arrow::{ArrowReader, ArrowReaderBuilder};
+use iceberg::io::FileIO;
-/// Manages the scanning process of an Iceberg [`Table`], encapsulating the
-/// necessary details and computed properties required for execution planning.
-#[derive(Debug, Clone)]
+/// Reads the tasks of a [`FileScanTaskProvider`] using a process-local reader.
+///
+/// The source does not require a table. Lazy discovery retains its table in
the
+/// provider; eager and remote providers can supply tasks without one. The
reader
+/// is shared across partitions, including its loaded delete files and
settings.
+#[derive(Clone)]
pub struct IcebergDataSource {
- /// A table in the catalog.
- table: Table,
- /// Snapshot of the table to scan.
- snapshot_id: Option<i64>,
- /// Schema returned by this data source after projection.
schema: ArrowSchemaRef,
- /// Projection column names in the output schema.
- projection: Vec<String>,
- /// Filter to apply to the table scan
- predicate: Option<Predicate>,
- /// Optional limit on the number of rows to return
+ file_io: FileIO,
+ reader: ArrowReader,
fetch: Option<usize>,
+ file_scan_task_provider: Arc<dyn FileScanTaskProvider>,
+ metrics: ExecutionPlanMetricsSet,
+}
+
+impl Debug for IcebergDataSource {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("IcebergDataSource")
+ .field("schema", &self.schema)
+ .field("fetch", &self.fetch)
+ .field("file_scan_task_provider", &self.file_scan_task_provider)
+ .finish_non_exhaustive()
+ }
}
impl IcebergDataSource {
- /// Starts building a source that scans `table` and returns the columns of
- /// `schema`, all of them unless
[`IcebergDataSourceBuilder::with_projection`]
- /// selects some. Columns are read from Iceberg by name.
- pub fn builder(table: Table, schema: ArrowSchemaRef) ->
IcebergDataSourceBuilder {
+ /// Starts source construction with session reader settings and explicit
local
+ /// storage/runtime resources. `reader` must use the supplied `file_io`.
+ /// Batch size and page-index settings come from `config`; file concurrency
+ /// defaults to one because DataFusion runs partitions concurrently.
+ /// A later [`IcebergDataSourceBuilder::with_reader`] overrides these
defaults.
+ /// No discovery or current-runtime lookup is performed, even with eager
+ /// planning enabled: the caller supplies the task provider explicitly.
+ pub fn builder(
+ config: &SessionConfig,
+ schema: ArrowSchemaRef,
+ file_io: FileIO,
+ reader: ArrowReaderBuilder,
+ ) -> IcebergDataSourceBuilder {
IcebergDataSourceBuilder {
- table,
schema,
- projection: None,
- snapshot_id: None,
- predicate: None,
+ file_io,
+ reader: reader
+ .with_batch_size(config.batch_size())
+ .with_row_selection_enabled(
+ config.options().execution.parquet.enable_page_index,
+ )
+ .with_data_file_concurrency_limit(1)
+ .build(),
fetch: None,
+ file_scan_task_provider: None,
Review Comment:
Given that `file_scan_task_provider` is actually required and it should not
be an `Option`, and that `fetch` is already handled at the
`DataSource::with_fetch` trait level, I think we've trimmed down this builder
to nothing to be worth providing as a builder pattern.
The `FileScanTaskProviderBuilder` seems to be all the building we really
need.
I'm fine with still keeping the `IcebergDataSource::builder`, just in case
in the future something truly optional actually pops up.
##########
crates/datafusion/src/read/scan.rs:
##########
@@ -15,162 +15,210 @@
// specific language governing permissions and limitations
// under the License.
-use std::pin::Pin;
+use std::fmt::{Debug, Formatter};
use std::sync::Arc;
-use datafusion::arrow::array::RecordBatch;
+use super::file_scan_task_provider::{FileScanTaskProvider,
FileScanTaskProviderContext};
+use crate::to_datafusion_error;
+
use datafusion::arrow::datatypes::SchemaRef as ArrowSchemaRef;
-use datafusion::common::Statistics;
use datafusion::common::tree_node::TreeNodeRecursion;
+use datafusion::common::{Statistics, exec_datafusion_err, exec_err};
use datafusion::datasource::source::DataSource;
use datafusion::error::Result;
use datafusion::execution::{SendableRecordBatchStream, TaskContext};
use datafusion::physical_expr::projection::ProjectionExprs;
use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr};
+use datafusion::physical_plan::limit::LimitStream;
+use datafusion::physical_plan::metrics::{BaselineMetrics,
ExecutionPlanMetricsSet};
use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
use datafusion::physical_plan::{DisplayFormatType, Partitioning};
-use datafusion::prelude::Expr;
-use futures::{Stream, TryStreamExt};
-use iceberg::expr::Predicate;
-use iceberg::table::Table;
-
-use super::predicate::convert_filters_to_predicate;
-use crate::to_datafusion_error;
+use datafusion::prelude::SessionConfig;
+use futures::TryStreamExt;
+use iceberg::arrow::{ArrowReader, ArrowReaderBuilder};
+use iceberg::io::FileIO;
-/// Manages the scanning process of an Iceberg [`Table`], encapsulating the
-/// necessary details and computed properties required for execution planning.
-#[derive(Debug, Clone)]
+/// Reads the tasks of a [`FileScanTaskProvider`] using a process-local reader.
+///
+/// The source does not require a table. Lazy discovery retains its table in
the
+/// provider; eager and remote providers can supply tasks without one. The
reader
+/// is shared across partitions, including its loaded delete files and
settings.
+#[derive(Clone)]
pub struct IcebergDataSource {
- /// A table in the catalog.
- table: Table,
- /// Snapshot of the table to scan.
- snapshot_id: Option<i64>,
- /// Schema returned by this data source after projection.
schema: ArrowSchemaRef,
- /// Projection column names in the output schema.
- projection: Vec<String>,
- /// Filter to apply to the table scan
- predicate: Option<Predicate>,
- /// Optional limit on the number of rows to return
+ file_io: FileIO,
+ reader: ArrowReader,
fetch: Option<usize>,
+ file_scan_task_provider: Arc<dyn FileScanTaskProvider>,
+ metrics: ExecutionPlanMetricsSet,
+}
+
+impl Debug for IcebergDataSource {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("IcebergDataSource")
+ .field("schema", &self.schema)
+ .field("fetch", &self.fetch)
+ .field("file_scan_task_provider", &self.file_scan_task_provider)
+ .finish_non_exhaustive()
+ }
}
impl IcebergDataSource {
- /// Starts building a source that scans `table` and returns the columns of
- /// `schema`, all of them unless
[`IcebergDataSourceBuilder::with_projection`]
- /// selects some. Columns are read from Iceberg by name.
- pub fn builder(table: Table, schema: ArrowSchemaRef) ->
IcebergDataSourceBuilder {
+ /// Starts source construction with session reader settings and explicit
local
+ /// storage/runtime resources. `reader` must use the supplied `file_io`.
+ /// Batch size and page-index settings come from `config`; file concurrency
+ /// defaults to one because DataFusion runs partitions concurrently.
+ /// A later [`IcebergDataSourceBuilder::with_reader`] overrides these
defaults.
+ /// No discovery or current-runtime lookup is performed, even with eager
+ /// planning enabled: the caller supplies the task provider explicitly.
+ pub fn builder(
+ config: &SessionConfig,
+ schema: ArrowSchemaRef,
+ file_io: FileIO,
+ reader: ArrowReaderBuilder,
+ ) -> IcebergDataSourceBuilder {
IcebergDataSourceBuilder {
- table,
schema,
- projection: None,
- snapshot_id: None,
- predicate: None,
+ file_io,
+ reader: reader
+ .with_batch_size(config.batch_size())
+ .with_row_selection_enabled(
+ config.options().execution.parquet.enable_page_index,
+ )
+ .with_data_file_concurrency_limit(1)
+ .build(),
fetch: None,
+ file_scan_task_provider: None,
}
}
- pub fn table(&self) -> &Table {
- &self.table
- }
-
- pub fn snapshot_id(&self) -> Option<i64> {
- self.snapshot_id
- }
-
pub fn schema(&self) -> ArrowSchemaRef {
self.schema.clone()
}
- pub fn projection(&self) -> &[String] {
- &self.projection
+ /// Storage access used by the reader, retained for
transport/reconstruction.
+ pub fn file_io(&self) -> &FileIO {
+ &self.file_io
}
- pub fn predicate(&self) -> Option<&Predicate> {
- self.predicate.as_ref()
+ /// Process-local reader shared by all output partitions.
+ pub fn reader(&self) -> &ArrowReader {
+ &self.reader
}
pub fn fetch(&self) -> Option<usize> {
self.fetch
}
+
+ /// Supplies the files this source reads. Downcast to inspect a concrete
provider.
+ pub fn file_scan_task_provider(&self) -> &dyn FileScanTaskProvider {
+ self.file_scan_task_provider.as_ref()
+ }
+
+ /// Replaces task delivery while retaining the reader, schema and fetch,
and
+ /// resetting metrics. Tasks must produce this source's projected schema.
+ /// Returns an error if the provider advertises no output partitions.
+ pub fn with_file_scan_task_provider(
+ &self,
+ file_scan_task_provider: Arc<dyn FileScanTaskProvider>,
+ ) -> Result<Self> {
+ validate_provider(file_scan_task_provider.as_ref())?;
+ Ok(Self {
+ file_scan_task_provider,
+ metrics: Default::default(),
+ ..self.clone()
+ })
+ }
}
-/// Builds an [`IcebergDataSource`]. Created by [`IcebergDataSource::builder`].
+/// Assembles a source from its output schema, storage, reader and task
provider.
+///
+/// Construction is synchronous and performs no discovery, file I/O or runtime
+/// lookup. Start with [`IcebergDataSource::builder`], which applies session
reader
+/// settings, or override them with [`Self::with_reader`]. The execution
context
+/// passed to `open` does not replace the retained reader's settings. FileIO
must
+/// match the reader's storage, and tasks must produce the supplied output
schema.
///
-/// A table provider passes the table's schema and selects columns with
-/// [`Self::with_projection`]. To rebuild a source, such as in another process,
-/// pass its [`IcebergDataSource::schema`], which is already projected, and no
-/// projection.
-#[derive(Debug, Clone)]
+/// ```
+/// # use std::sync::Arc;
+/// # use datafusion::arrow::datatypes::SchemaRef;
+/// # use datafusion::common::Result;
+/// # use datafusion::prelude::SessionConfig;
+/// # use iceberg::{arrow::ArrowReaderBuilder, io::FileIO, scan::FileScanTask};
+/// # use iceberg_datafusion::read::{EagerFileScanTaskProvider,
IcebergDataSource};
+/// fn reconstruct(
+/// config: &SessionConfig,
+/// schema: SchemaRef,
+/// file_io: FileIO,
+/// reader: ArrowReaderBuilder,
+/// groups: Vec<Vec<FileScanTask>>,
+/// ) -> Result<IcebergDataSource> {
+/// let provider = EagerFileScanTaskProvider::try_new(groups)?;
+/// IcebergDataSource::builder(config, schema, file_io, reader)
+/// .with_file_scan_task_provider(Arc::new(provider))
+/// .build()
+/// }
+/// ```
+#[derive(Clone)]
pub struct IcebergDataSourceBuilder {
- table: Table,
schema: ArrowSchemaRef,
- projection: Option<Vec<usize>>,
- snapshot_id: Option<i64>,
- predicate: Option<Predicate>,
+ file_io: FileIO,
+ reader: ArrowReader,
fetch: Option<usize>,
+ file_scan_task_provider: Option<Arc<dyn FileScanTaskProvider>>,
}
impl IcebergDataSourceBuilder {
- /// Returns only the columns of the schema at these indices, or all of them
- /// if `None` (the default). Indices are into the schema passed to
- /// [`IcebergDataSource::builder`].
- pub fn with_projection(mut self, projection: Option<&Vec<usize>>) -> Self {
- self.projection = projection.cloned();
+ /// Uses an explicitly configured, shared reader instead of session
defaults.
+ /// Its FileIO must match the FileIO supplied at builder construction.
Retaining
+ /// a reader also retains its cached delete files across output partitions.
+ pub fn with_reader(mut self, reader: ArrowReader) -> Self {
+ self.reader = reader;
self
}
- /// Scans this snapshot, or the table's current one if `None` (the
default).
- pub fn with_snapshot_id(mut self, snapshot_id: Option<i64>) -> Self {
- self.snapshot_id = snapshot_id;
+ /// Supplies task delivery. Required before calling [`Self::build`].
+ pub fn with_file_scan_task_provider(
+ mut self,
+ provider: Arc<dyn FileScanTaskProvider>,
+ ) -> Self {
+ self.file_scan_task_provider = Some(provider);
self
}
- /// Filters the scan with `predicate`, or not at all if `None` (the
default).
- pub fn with_predicate(mut self, predicate: Option<Predicate>) -> Self {
- self.predicate = predicate;
- self
- }
-
- /// Filters the scan with the parts of `filters` that convert to an Iceberg
- /// predicate. The rest are dropped, so the scan may return rows that
- /// `filters` reject.
- pub fn with_filters(self, filters: &[Expr]) -> Self {
- self.with_predicate(convert_filters_to_predicate(filters))
- }
-
- /// Stops after `fetch` rows, or reads every row if `None` (the default).
+ /// Stops each partition after `fetch` rows, or reads every row for `None`.
pub fn with_fetch(mut self, fetch: Option<usize>) -> Self {
self.fetch = fetch;
self
}
- /// Builds the source, which reads the columns of its projected schema by
name.
- ///
- /// # Errors
- ///
- /// Returns an error if the projection is out of bounds for the schema.
+ /// Builds a source without discovering files. Returns an error if no
provider
+ /// was supplied or the provider advertises no output partitions.
pub fn build(self) -> Result<IcebergDataSource> {
- let schema = match &self.projection {
- None => self.schema,
- Some(projection) => Arc::new(self.schema.project(projection)?),
- };
- let projection = schema
- .fields()
- .iter()
- .map(|field| field.name().clone())
- .collect();
+ let provider = self.file_scan_task_provider.ok_or_else(|| {
+ exec_datafusion_err!("An Iceberg source requires a file task
provider")
+ })?;
Review Comment:
Rather than throwing a runtime error, I'd probably require it in the
`IcebergDataSourceBuilder`. Note that having required files be provided using a
builder pattern solves the public API breaking issue, but introduces a much
worst issue: breakage at runtime rather than compile time, which is still an
even worst way of breaking a project during an upgrade.
##########
crates/datafusion/tests/file_scan_task_provider.rs:
##########
@@ -0,0 +1,497 @@
+// 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 std::any::Any;
+use std::sync::Arc;
+
+use datafusion::arrow::datatypes::Schema;
+use datafusion::arrow::util::pretty::pretty_format_batches;
+use datafusion::common::Result;
+use datafusion::datasource::source::{DataSource, DataSourceExec};
+use datafusion::execution::TaskContext;
+use datafusion::physical_plan::{ExecutionPlan, collect};
+use datafusion::prelude::SessionConfig;
+use futures::TryStreamExt;
+use iceberg::arrow::ArrowReaderBuilder;
+use iceberg::io::FileIO;
+use iceberg::table::Table;
+use iceberg_datafusion::IcebergDataFusionConfig;
+use iceberg_datafusion::read::{
+ EagerFileScanTaskProvider, FileScanTaskProvider,
FileScanTaskProviderBuilder,
+ FileScanTaskProviderContext, IcebergDataSource, LazyFileScanTaskProvider,
+};
+use iceberg_datafusion::test_utils::IcebergTestHarness;
+
+#[tokio::test]
+async fn lazy_discovery_does_not_read_manifests_until_polled() -> Result<()> {
+ let harness = IcebergTestHarness::builder()
+ .with_config(SessionConfig::new().with_target_partitions(3))
+ .build()
+ .await?;
+ let plan = harness.plan("SELECT pickup_date FROM taxi").await?;
+ let source = iceberg_source(&plan);
+ let lazy = (source.file_scan_task_provider() as &dyn Any)
+ .downcast_ref::<LazyFileScanTaskProvider>()
+ .unwrap();
+ assert_eq!(lazy.partitioning().partition_count(), 1);
+ assert_eq!(lazy.projection(), &["pickup_date"]);
+
+ // Keep the loaded metadata but deliberately remove its S3 fixture storage.
+ // LocalFs cannot read these manifest paths. Opening the lazy stream must
+ // still succeed; only polling it should attempt that I/O and fail.
+ let inaccessible_table = Table::builder()
+ .identifier(lazy.table().identifier().clone())
+ .metadata(lazy.table().metadata_ref())
+ .file_io(FileIO::new_with_fs())
+ .runtime(iceberg::Runtime::current())
+ .build()
+ .map_err(iceberg_datafusion::to_datafusion_error)?;
+ let context = harness.context().task_ctx();
+ let (_, discovery) = FileScanTaskProviderBuilder::new(
+ Arc::clone(&context),
+ inaccessible_table,
+ lazy.schema(),
+ )
+ .build()
+ .await?;
+ let mut tasks = discovery.open(
+ 0,
+ FileScanTaskProviderContext {
+ task_context: &context,
+ },
+ )?;
+ assert!(tasks.try_next().await.is_err());
+ Ok(())
+}
+
+#[tokio::test]
+async fn lazy_builder_keeps_projected_schema_and_task_columns_in_order() ->
Result<()> {
+ let harness = IcebergTestHarness::builder()
+ .with_config(SessionConfig::new().with_target_partitions(1))
+ .build()
+ .await?;
+ let plan = harness
+ .plan("SELECT * FROM taxi WHERE pickup_date = DATE '2024-01-10'")
+ .await?;
+ let source = iceberg_source(&plan);
+ let lazy = (source.file_scan_task_provider() as &dyn Any)
+ .downcast_ref::<LazyFileScanTaskProvider>()
+ .unwrap();
+ let schema = lazy.schema();
+ // Reverse the fixture's relative order: date (field 13), then vendor
(field 1).
+ let projection = vec![
+ schema.index_of("pickup_date")?,
+ schema.index_of("vendor_id")?,
+ ];
+ let (schema, discovery) = FileScanTaskProviderBuilder::new(
+ harness.context().task_ctx(),
+ lazy.table().clone(),
+ schema,
+ )
+ .with_projection(Some(&projection))
+ .with_predicate(lazy.predicate().cloned())
+ .build()
+ .await?;
+ let columns = schema
+ .fields()
+ .iter()
+ .map(|field| field.name().clone())
+ .collect::<Vec<_>>();
+ insta::assert_debug_snapshot!(columns, @r#"
+ [
+ "pickup_date",
+ "vendor_id",
+ ]
+ "#);
+ let projected_lazy = (discovery.as_ref() as &dyn Any)
+ .downcast_ref::<LazyFileScanTaskProvider>()
+ .unwrap();
+ assert_eq!(projected_lazy.projection(), columns);
+ let context = harness.context().task_ctx();
+ let tasks = Arc::clone(&discovery)
+ .open(
+ 0,
+ FileScanTaskProviderContext {
+ task_context: &context,
+ },
+ )?
+ .try_collect::<Vec<_>>()
+ .await
+ .map_err(iceberg_datafusion::to_datafusion_error)?;
+ assert_eq!(tasks.len(), 1);
+ assert_eq!(tasks[0].project_field_ids(), &[13, 1]);
+
+ let projected = IcebergDataSource::builder(
+ &harness.context().copied_config(),
+ schema,
+ source.file_io().clone(),
+ lazy.table().reader_builder(),
+ )
+ .with_reader(source.reader().clone())
+ .with_file_scan_task_provider(discovery)
+ .with_fetch(Some(1))
+ .build()?;
+ let batches = projected.open(0, context)?.try_collect::<Vec<_>>().await?;
+ insta::assert_snapshot!(pretty_format_batches(&batches)?.to_string(), @"
+ +-------------+-----------+
+ | pickup_date | vendor_id |
+ +-------------+-----------+
+ | 2024-01-10 | 2 |
+ +-------------+-----------+
+ ");
+ Ok(())
+}
+
+#[tokio::test]
+async fn lazy_builder_rejects_projection_outside_the_supplied_schema() ->
Result<()> {
+ let harness = IcebergTestHarness::builder()
+ .with_config(SessionConfig::new().with_target_partitions(1))
+ .build()
+ .await?;
+ let plan = harness.plan("SELECT pickup_date FROM taxi").await?;
+ let source = iceberg_source(&plan);
+ let lazy = (source.file_scan_task_provider() as &dyn Any)
+ .downcast_ref::<LazyFileScanTaskProvider>()
+ .unwrap();
+ // The supplied schema has only one column, even though the table has
thirteen.
+ let error = FileScanTaskProviderBuilder::new(
+ harness.context().task_ctx(),
+ lazy.table().clone(),
+ lazy.schema(),
+ )
+ .with_projection(Some(&vec![1]))
+ .build()
+ .await
+ .unwrap_err();
+ insta::assert_snapshot!(error.to_string(), @"Arrow error: Schema error:
project index 1 out of bounds, max field 1");
+ Ok(())
+}
+
+#[tokio::test]
+async fn eager_table_planning_selects_files_before_execution() -> Result<()> {
+ let harness = IcebergTestHarness::builder()
+ .with_config(
+ SessionConfig::new()
+ .with_target_partitions(3)
+ .with_option_extension(IcebergDataFusionConfig::default())
+ .set_bool("iceberg.execution.eager_file_planning", true),
+ )
+ .build()
+ .await?;
+ let plan = harness
+ .plan(
+ "SELECT pickup_date, COUNT(*) AS trips FROM taxi \
+ WHERE pickup_date IN (DATE '2024-01-10', DATE '2024-01-11') \
+ GROUP BY pickup_date ORDER BY pickup_date",
+ )
+ .await?;
+ let eager = (iceberg_source(&plan).file_scan_task_provider() as &dyn Any)
+ .downcast_ref::<EagerFileScanTaskProvider>()
+ .unwrap();
+ // Only two selected files, so eager discovery caps the requested three
partitions.
+ assert_eq!(
+ eager.groups().iter().map(Vec::len).collect::<Vec<_>>(),
+ vec![1, 1]
+ );
+ let batches = collect(plan, harness.context().task_ctx()).await?;
+ insta::assert_snapshot!(pretty_format_batches(&batches)?.to_string(), @"
+ +-------------+-------+
+ | pickup_date | trips |
+ +-------------+-------+
+ | 2024-01-10 | 25000 |
+ | 2024-01-11 | 25000 |
+ +-------------+-------+
+ ");
+ Ok(())
+}
+
+#[tokio::test]
+async fn eager_planning_consumes_the_lazy_providers_discovery() -> Result<()> {
+ let harness = IcebergTestHarness::builder()
+ .with_config(SessionConfig::new().with_target_partitions(3))
+ .build()
+ .await?;
+ let plan = harness.plan("SELECT pickup_date FROM taxi").await?;
+ let lazy = (iceberg_source(&plan).file_scan_task_provider() as &dyn Any)
+ .downcast_ref::<LazyFileScanTaskProvider>()
+ .unwrap()
+ .clone();
+ let eager = lazy.into_eager(harness.context().task_ctx()).await?;
+ assert_eq!(
+ eager.groups().iter().map(Vec::len).collect::<Vec<_>>(),
+ vec![3, 2, 2]
+ );
+ assert_eq!(eager.tasks().count(), 7);
+ Ok(())
+}
+
+#[tokio::test]
+async fn reconstruction_needs_no_table_or_current_runtime() -> Result<()> {
+ let harness = IcebergTestHarness::builder()
+ .with_config(
+ SessionConfig::new()
+ .with_target_partitions(3)
+ .with_batch_size(1)
+ .with_option_extension(IcebergDataFusionConfig::default())
+ .set_bool("iceberg.execution.eager_file_planning", true),
+ )
+ .build()
+ .await?;
+ let plan = harness
+ .plan("SELECT pickup_date FROM taxi WHERE pickup_date = DATE
'2024-01-10'")
+ .await?;
+ let source = iceberg_source(&plan);
+ let eager = (source.file_scan_task_provider() as &dyn Any)
+ .downcast_ref::<EagerFileScanTaskProvider>()
+ .unwrap();
+ let file = eager.tasks().next().unwrap().clone();
+ // Explicit assignment: preserve an empty partition and a repeated file.
+ let groups = vec![vec![file.clone()], vec![], vec![file.clone(), file]];
+ let (schema, file_io, reader) = (
+ source.schema(),
+ source.file_io().clone(),
+ source.reader().clone(),
+ );
+ let reader_builder =
+ ArrowReaderBuilder::new(file_io.clone(), iceberg::Runtime::current());
+ // An explicit reader must override the constructor's session defaults.
+ let config = harness.context().copied_config().with_batch_size(7);
+ drop(plan);
+ drop(harness);
+
+ let source = std::thread::spawn(move || {
+ assert!(tokio::runtime::Handle::try_current().is_err());
+ IcebergDataSource::builder(&config, schema, file_io, reader_builder)
+ .with_reader(reader)
+
.with_file_scan_task_provider(Arc::new(EagerFileScanTaskProvider::try_new(
+ groups,
+ )?))
+ .with_fetch(Some(2))
+ .build()
+ })
Review Comment:
🙈 I know you have not reviewed this yet, so calming down and deleting the
comment I was writing.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]