fvaleye commented on code in PR #1620: URL: https://github.com/apache/iceberg-rust/pull/1620#discussion_r2469734510
########## crates/integrations/datafusion/src/physical_plan/repartition.rs: ########## @@ -0,0 +1,966 @@ +// 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::collections::HashSet; +use std::num::NonZeroUsize; +use std::sync::Arc; + +use datafusion::error::{DataFusionError, Result as DFResult}; +use datafusion::physical_expr::PhysicalExpr; +use datafusion::physical_plan::expressions::Column; +use datafusion::physical_plan::repartition::RepartitionExec; +use datafusion::physical_plan::{ExecutionPlan, Partitioning}; +use iceberg::spec::{TableMetadata, TableMetadataRef, Transform}; +use tracing; + +use crate::physical_plan::project::PARTITION_VALUES_COLUMN; + +/// Creates an Iceberg-aware repartition execution plan that optimizes data distribution +/// for parallel processing while respecting Iceberg table partitioning semantics. +/// +/// Automatically determines the optimal partitioning strategy based on the table's +/// partition specification. +/// +/// ## Partitioning Strategies +/// +/// - **Unpartitioned tables** – Uses round-robin distribution to balance load across workers. +/// - **Hash partitioning** – Applied for tables with identity or bucket transforms, ensuring +/// co-location of related data for efficient file clustering. This is used when the `_partition` +/// column is present AND the partition spec has hash-friendly transforms (Identity/Bucket), +/// or when source columns with these transforms are available. +/// - **Round-robin partitioning** – Used for temporal transforms (Year, Month, Day, Hour), +/// Truncate, or other transforms that don't provide good hash distribution. +/// - **Mixed transforms** – Combines multiple transform types, using hash partitioning only +/// when Identity or Bucket transforms are present, otherwise falling back to round-robin. +/// +/// ## Performance Notes +/// +/// - Only repartitions when the input scheme or partition count differs from the target. +/// - Requires an explicit target partition count for deterministic behavior. +/// - Preserves column order (partitions first, then buckets) for consistent layout. +/// +/// # Arguments +/// +/// * `input` – The input execution plan providing data to be repartitioned. For partitioned tables, +/// the input should include the `_partition` column (added via `project_with_partition`). +/// * `table_metadata` – Iceberg table metadata containing partition spec. +/// * `target_partitions` – Target number of partitions for parallel processing (must be > 0). +/// +/// # Returns +/// +/// An execution plan that applies the optimal partitioning strategy, or the original input plan if no repartitioning is needed. +/// +/// # Example +/// +/// ```ignore +/// let repartitioned_plan = repartition( +/// input_plan, +/// table.metadata_ref(), +/// 4, // Explicit partition count +/// )?; +/// ``` +#[allow(dead_code)] +pub(crate) fn repartition( + input: Arc<dyn ExecutionPlan>, + table_metadata: TableMetadataRef, + target_partitions: NonZeroUsize, +) -> DFResult<Arc<dyn ExecutionPlan>> { + let partitioning_strategy = + determine_partitioning_strategy(&input, &table_metadata, target_partitions)?; + + if !needs_repartitioning(&input, &partitioning_strategy) { + return Ok(input); + } + + Ok(Arc::new(RepartitionExec::try_new( + input, + partitioning_strategy, + )?)) +} + +/// Returns whether repartitioning is actually needed by comparing input and desired partitioning +fn needs_repartitioning(input: &Arc<dyn ExecutionPlan>, desired: &Partitioning) -> bool { + let input_partitioning = input.properties().output_partitioning(); + match (input_partitioning, desired) { + (Partitioning::RoundRobinBatch(a), Partitioning::RoundRobinBatch(b)) => a != b, + (Partitioning::Hash(a_exprs, a_n), Partitioning::Hash(b_exprs, b_n)) => { + a_n != b_n || !same_columns(a_exprs, b_exprs) + } + _ => true, + } +} + +/// Helper function to check if two sets of column expressions are the same +fn same_columns(a_exprs: &[Arc<dyn PhysicalExpr>], b_exprs: &[Arc<dyn PhysicalExpr>]) -> bool { + if a_exprs.len() != b_exprs.len() { + return false; + } + a_exprs.iter().zip(b_exprs.iter()).all(|(a, b)| { + if let (Some(a_col), Some(b_col)) = ( + a.as_any().downcast_ref::<Column>(), + b.as_any().downcast_ref::<Column>(), + ) { + a_col.name() == b_col.name() && a_col.index() == b_col.index() + } else { + std::ptr::eq(a.as_ref(), b.as_ref()) + } + }) +} + +/// Determine the optimal partitioning strategy based on table metadata. +/// +/// Analyzes the table's partition specification to select the most appropriate +/// DataFusion partitioning strategy for insert operations. +/// +/// ## Partitioning Strategy +/// +/// - **Hash partitioning using `_partition` column**: Used when the input includes a +/// projected `_partition` column AND the partition spec contains Identity or Bucket transforms. +/// Ensures data is distributed based on actual partition values with good distribution. +/// +/// - **Hash partitioning using source columns**: Applied when identity or bucket transforms +/// provide good distribution: +/// 1. Identity partition columns (e.g., `PARTITIONED BY (user_id, category)`) +/// 2. Bucket columns from partition spec (e.g., `bucket(16, user_id)`) +/// +/// Ensures co-location within partitions and buckets for optimal file clustering. +/// +/// - **Round-robin partitioning**: Used for unpartitioned tables, or when partition transforms +/// don't provide good hash distribution (e.g., Year, Month, Day, Hour, Truncate transforms). +/// Ensures even load distribution across partitions. +/// +/// ## Column Priority +/// +/// Columns are combined in the following order, with duplicates removed: +/// 1. `_partition` column (highest priority, if present) +/// 2. Identity partition columns from partition spec +/// 3. Bucket columns from partition spec +/// +/// ## Fallback +/// +/// If no suitable hash columns are found, falls back to round-robin batch partitioning +/// to ensure even load distribution across partitions. +fn determine_partitioning_strategy( + input: &Arc<dyn ExecutionPlan>, + table_metadata: &TableMetadata, + target_partitions: NonZeroUsize, +) -> DFResult<Partitioning> { + let partition_spec = table_metadata.default_partition_spec(); + let table_schema = table_metadata.current_schema(); + let input_schema = input.schema(); + let target_partition_count = target_partitions.get(); + + // Check if partition spec has transforms suitable for hash partitioning + let has_hash_friendly_transforms = partition_spec + .fields() + .iter() + .any(|pf| matches!(pf.transform, Transform::Identity | Transform::Bucket(_))); + + let partition_col_result = input_schema.index_of(PARTITION_VALUES_COLUMN); + let is_partitioned_table = !partition_spec.is_unpartitioned(); + + match (is_partitioned_table, partition_col_result) { + // Case 1: Partitioned table with _partition column present + (true, Ok(partition_col_idx)) => { + let partition_field = input_schema.field(partition_col_idx); + if partition_field.name() != PARTITION_VALUES_COLUMN { + return Err(DataFusionError::Plan(format!( + "Expected {} column at index {}, but found '{}'", + PARTITION_VALUES_COLUMN, + partition_col_idx, + partition_field.name() + ))); + } + + let partition_expr = Arc::new(Column::new(PARTITION_VALUES_COLUMN, partition_col_idx)) + as Arc<dyn PhysicalExpr>; + + return if has_hash_friendly_transforms { + Ok(Partitioning::Hash( + vec![partition_expr], + target_partition_count, + )) + } else { + Ok(Partitioning::RoundRobinBatch(target_partition_count)) + }; + } + + // Case 2: Partitioned table missing _partition column (warning) + (true, Err(_)) => { + tracing::warn!( + "Partitioned table input missing {} column. \ + Consider adding partition projection before repartitioning.", + PARTITION_VALUES_COLUMN + ); + } + + // Case 3: Unpartitioned table with _partition column + (false, Ok(_)) => { + tracing::warn!( + "Input contains {} column but table is unpartitioned. \ + This may indicate unnecessary projection.", + PARTITION_VALUES_COLUMN + ); + } + + // Case 4: Unpartitioned table without _partition column + (false, Err(_)) => { + // Nothing to do - fall through to source column analysis + } + } + + let hash_column_names: Vec<&str> = partition_spec Review Comment: Since the physical plan is generated by `IcebergTableProvider`, which always calls `project_with_partition()` for partitioned tables... we can guarantee that the `_partition` column will be present... so it is unnecessary if we stick to the DataFusion plan creation! Let me rework this. -- 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]
