mbutrovich commented on code in PR #2671:
URL: https://github.com/apache/iceberg-rust/pull/2671#discussion_r3558635085
##########
crates/integrations/datafusion/src/physical_plan/scan.rs:
##########
@@ -146,13 +139,55 @@ impl ExecutionPlan for IcebergTableScan {
_partition: usize,
Review Comment:
`execute`'s `partition` argument is read at line 146
(`file_task_groups.get(_partition)`) and interpolated into the error message at
line 148 (`partition {_partition} does not exist`). The leading underscore
signals "unused" to readers and lint, and it leaks into user-facing error text.
Rename to `partition`. (`_context` at line 140 is still legitimately unused;
leave it.)
##########
crates/integrations/datafusion/src/physical_plan/scan.rs:
##########
@@ -146,13 +139,55 @@ impl ExecutionPlan for IcebergTableScan {
_partition: usize,
_context: Arc<TaskContext>,
) -> DFResult<SendableRecordBatchStream> {
- let fut = get_batch_stream(
- self.table.clone(),
- self.snapshot_id,
- self.projection.clone(),
- self.predicates.clone(),
- );
- let stream = futures::stream::once(fut).try_flatten();
+ let stream: Pin<Box<dyn Stream<Item = DFResult<RecordBatch>> + Send>>
= match &self
+ .file_task_groups
+ {
+ Some(file_task_groups) => {
+ let Some(file_task_group) =
file_task_groups.get(_partition).cloned() else {
+ return
Err(datafusion::common::DataFusionError::Internal(format!(
+ "IcebergTableScan partition {_partition} does not
exist; scan has {} partitions",
+ file_task_groups.len()
+ )));
+ };
+
+ let task_count = file_task_group.len();
+ let tasks: FileScanTaskStream = Box::pin(futures::stream::iter(
+ (0..task_count).map(move |idx|
Ok(file_task_group[idx].clone())),
+ ));
Review Comment:
`task_count` is used once; inline it as `(0..file_task_group.len())`.
Heads-up for anyone tempted to go further:
`file_task_group.iter().cloned().map(Ok)` does not compile here, because the
stream must be `'static` and `iter()` would borrow the local
`Arc<[FileScanTask]>`. The move-plus-index form is the allocation-free way to
clone lazily out of the `Arc`, so keep that shape; just remove the extra
binding.
##########
crates/integrations/datafusion/src/physical_plan/scan_planning.rs:
##########
@@ -0,0 +1,150 @@
+// 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::sync::Arc;
+
+use datafusion::arrow::datatypes::SchemaRef as ArrowSchemaRef;
+use datafusion::error::Result as DFResult;
+use datafusion::prelude::Expr;
+use futures::TryStreamExt;
+use iceberg::expr::Predicate;
+use iceberg::scan::{FileScanTask, TableScan};
+use iceberg::table::Table;
+
+use super::expr_to_predicate::convert_filters_to_predicate;
+use crate::to_datafusion_error;
+
+#[derive(Debug, Clone)]
+pub(crate) struct IcebergScanConfig {
+ /// Snapshot of the table to scan.
+ snapshot_id: Option<i64>,
+ /// Output schema after projection.
+ output_schema: ArrowSchemaRef,
+ /// Projection column names, None means all columns.
+ column_names: Option<Vec<String>>,
+ /// Filters to apply to the table scan.
+ predicates: Option<Predicate>,
+}
+
+impl IcebergScanConfig {
+ pub(crate) fn new(
+ schema: ArrowSchemaRef,
+ snapshot_id: Option<i64>,
+ projection: Option<&Vec<usize>>,
+ filters: &[Expr],
+ ) -> Self {
+ let output_schema = match projection {
+ None => schema.clone(),
+ Some(projection) => Arc::new(schema.project(projection).unwrap()),
+ };
+
+ Self {
+ snapshot_id,
+ output_schema,
+ column_names: get_column_names(schema, projection),
+ predicates: convert_filters_to_predicate(filters),
+ }
+ }
+
+ pub(crate) fn snapshot_id(&self) -> Option<i64> {
+ self.snapshot_id
+ }
+
+ pub(crate) fn output_schema(&self) -> ArrowSchemaRef {
+ self.output_schema.clone()
+ }
+
+ pub(crate) fn column_names(&self) -> Option<&[String]> {
+ self.column_names.as_deref()
+ }
+
+ pub(crate) fn predicates(&self) -> Option<&Predicate> {
+ self.predicates.as_ref()
+ }
+}
+
+pub(crate) async fn plan_file_task_groups(
+ table: &Table,
+ scan_config: &IcebergScanConfig,
+ target_partitions: usize,
+) -> DFResult<Vec<Vec<FileScanTask>>> {
+ // Do not cache planned FileScanTasks in the provider in v1. They are
query-specific
+ // because projection, predicate binding, snapshot schema, and delete
planning can differ
+ // between scans. Catalog-backed providers also need fresh metadata on
each scan.
+ // TODO: Revisit provider-level caching for static tables with a precise
cache key.
+ let tasks: Vec<FileScanTask> = build_table_scan(table, scan_config)?
+ .plan_files()
+ .await
+ .map_err(to_datafusion_error)?
+ .try_collect::<Vec<_>>()
+ .await
+ .map_err(to_datafusion_error)?;
+
+ Ok(group_file_scan_tasks_round_robin(tasks, target_partitions))
+}
+
+fn get_column_names(
+ schema: ArrowSchemaRef,
+ projection: Option<&Vec<usize>>,
+) -> Option<Vec<String>> {
+ projection.map(|v| {
+ v.iter()
+ .map(|p| schema.field(*p).name().clone())
+ .collect::<Vec<String>>()
+ })
+}
+
+/// Groups file scan tasks into `target_partitions` groups using a naive
+/// round-robin assignment. `target_partitions` is clamped to a minimum of 1.
+// TODO: Replace this naive round-robin grouping with size-based grouping once
the
+// first parallel scan path is stable. Keep this v1 simple and deterministic.
+fn group_file_scan_tasks_round_robin(
+ tasks: Vec<FileScanTask>,
+ target_partitions: usize,
+) -> Vec<Vec<FileScanTask>> {
+ if tasks.is_empty() {
+ return vec![vec![]];
+ }
+
+ let target_partitions = target_partitions.max(1);
+
+ let mut groups: Vec<Vec<FileScanTask>> = vec![Vec::new();
target_partitions];
+ for (i, task) in tasks.into_iter().enumerate() {
+ groups[i % target_partitions].push(task);
+ }
+
+ groups.retain(|group| !group.is_empty());
+ groups
Review Comment:
When `target_partitions > tasks.len()` (which the tests deliberately hit
with `data_file_count + 1`), this allocates extra empty vecs and then walks the
whole vec to remove them. The result is always `min(target_partitions,
tasks.len())` non-empty groups, so clamp up front and the `retain` disappears:
```rust
// tasks is non-empty here (early return above handles the empty case)
let target_partitions = target_partitions.max(1).min(tasks.len());
let mut groups: Vec<Vec<FileScanTask>> = vec![Vec::new(); target_partitions];
for (i, task) in tasks.into_iter().enumerate() {
groups[i % target_partitions].push(task);
}
groups
```
##########
crates/integrations/datafusion/src/table/mod.rs:
##########
Review Comment:
Both `IcebergTableProvider::scan` (`:158`, used at `:178`) and
`IcebergStaticTableProvider::scan` (`:343`, used at `:352`) pass `_state` into
`create_scan_plan`, which reads it via `enable_eager_scan_planning(state)`.
Rename both to `state`. Note: `_state` at `:365` (`insert_into` is genuinely
unused; leave it.)
--
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]