You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by gi...@apache.org on 2026/10/12 12:55:27 UTC
(datafusion-comet) branch gh-readonly-queue/main/pr-6814-019f3be9d106a8076e8ab22ba31466195bdf3e5b created (now 489632ab1e)
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a change to branch gh-readonly-queue/main/pr-6814-019f3be9d106a8076e8ab22ba31466195bdf3e5b
in repository https://gitbox.apache.org/repos/asf/datafusion-comet.git
at 489632ab1e fix: [spark34] preserve empty Iceberg partitions after dynamic pruning (#6814)
This branch includes the following new commits:
new 489632ab1e fix: [spark34] preserve empty Iceberg partitions after dynamic pruning (#6814)
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org
(datafusion-comet) 01/01: fix: [spark34] preserve empty Iceberg partitions after dynamic pruning (#6814)
Posted by gi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-6814-019f3be9d106a8076e8ab22ba31466195bdf3e5b
in repository https://gitbox.apache.org/repos/asf/datafusion-comet.git
commit 489632ab1ea3d4af3dfac0c9f34d5e9b45da3bd0
Author: LinSimon-901101 <bc...@gm.ntcu.edu.tw>
AuthorDate: Mon Oct 12 11:22:03 2026 +0000
fix: [spark34] preserve empty Iceberg partitions after dynamic pruning (#6814)
* fix: preserve empty Iceberg partitions after dynamic pruning
* test: simplify empty Iceberg scan credential regression
* test: cover single-split Iceberg joins after DPP
---
.../core/src/execution/operators/iceberg_scan.rs | 8 +-
.../serde/operator/CometIcebergNativeScan.scala | 17 +-
.../org/apache/comet/CometIcebergNativeSuite.scala | 280 ++++++++++++++++++++-
3 files changed, 297 insertions(+), 8 deletions(-)
diff --git a/native/core/src/execution/operators/iceberg_scan.rs b/native/core/src/execution/operators/iceberg_scan.rs
index ad69cac4f0..7b18c7e3be 100644
--- a/native/core/src/execution/operators/iceberg_scan.rs
+++ b/native/core/src/execution/operators/iceberg_scan.rs
@@ -35,7 +35,8 @@ use datafusion::physical_plan::metrics::{
BaselineMetrics, Count, ExecutionPlanMetricsSet, MetricBuilder, MetricsSet,
};
use datafusion::physical_plan::{
- DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning, PlanProperties,
+ DisplayAs, DisplayFormatType, EmptyRecordBatchStream, ExecutionPlan, Partitioning,
+ PlanProperties,
};
use futures::{Stream, StreamExt, TryStreamExt};
use iceberg::arrow::ScanMetrics;
@@ -178,6 +179,11 @@ impl IcebergScanExec {
context: Arc<TaskContext>,
) -> DFResult<SendableRecordBatchStream> {
let output_schema = Arc::clone(&self.output_schema);
+ // DPP can leave an empty execution partition so that global aggregates still run.
+ // No files need reading, so do not initialize storage or request catalog credentials.
+ if tasks.is_empty() {
+ return Ok(Box::pin(EmptyRecordBatchStream::new(output_schema)));
+ }
let file_io = load_file_io(
&self.catalog_properties,
&self.metadata_location,
diff --git a/spark/src/main/scala/org/apache/comet/serde/operator/CometIcebergNativeScan.scala b/spark/src/main/scala/org/apache/comet/serde/operator/CometIcebergNativeScan.scala
index 335f02ff03..22895e5145 100644
--- a/spark/src/main/scala/org/apache/comet/serde/operator/CometIcebergNativeScan.scala
+++ b/spark/src/main/scala/org/apache/comet/serde/operator/CometIcebergNativeScan.scala
@@ -1280,17 +1280,24 @@ object CometIcebergNativeScan extends CometOperatorSerde[CometBatchScanExec] wit
perPartitionBuilders += partitionBuilder.build()
}
case other if other.getClass.getName == "org.apache.spark.rdd.ParallelCollectionRDD" =>
- // Spark's BatchScanExec.inputRDD returns sparkContext.parallelize(empty, 1) when
- // DPP filtering removes all input partitions. That ParallelCollectionRDD is the only
- // non-DataSourceRDD shape its inputRDD produces, so reaching this branch means "DPP
- // pruned everything"; emit no per-partition data and let native execution return empty.
+ // Spark 3.4's BatchScanExec.inputRDD returns sparkContext.parallelize(empty, 1) when
+ // DPP removes every split of a scan that reports SinglePartition. Among supported
+ // versions, only Spark 3.4 infers SinglePartition from one execution partition,
+ // which may be a single split or a group of splits. Other fully pruned scans take
+ // the DataSourceRDD branch above: ungrouped scans have no partitions, while grouped
+ // scans may retain empty partitions. Preserve Spark's empty
+ // execution partition so global aggregates still run and scans in the same native block
+ // retain matching partition counts when no exchange separates them.
// Re-querying scan.toBatch.planInputPartitions() to verify is unreliable because
// Iceberg's Scan state after filter() doesn't always reflect post-DPP partitions on
// a re-call (V2 scan state is one-shot for the materialized inputRDD). Matched by class
// name because ParallelCollectionRDD is private[spark].
logDebug(
"BatchScanExec.inputRDD is ParallelCollectionRDD (DPP pruned all partitions); " +
- "skipping per-partition serialization")
+ "preserving empty execution partitions")
+ other.partitions.foreach { _ =>
+ perPartitionBuilders += OperatorOuterClass.IcebergScan.getDefaultInstance
+ }
case other =>
throw new IllegalStateException(
"Expected DataSourceRDD or ParallelCollectionRDD from BatchScanExec, " +
diff --git a/spark/src/test/scala/org/apache/comet/CometIcebergNativeSuite.scala b/spark/src/test/scala/org/apache/comet/CometIcebergNativeSuite.scala
index f271f7d6ec..02d2640d10 100644
--- a/spark/src/test/scala/org/apache/comet/CometIcebergNativeSuite.scala
+++ b/spark/src/test/scala/org/apache/comet/CometIcebergNativeSuite.scala
@@ -22,6 +22,7 @@ package org.apache.comet
import java.io.File
import java.net.URI
import java.nio.charset.StandardCharsets.UTF_8
+import java.util.UUID
import java.util.concurrent.atomic.AtomicLong
import scala.jdk.CollectionConverters._
@@ -41,11 +42,12 @@ import org.apache.spark.sql.execution.datasources.v2.BatchScanExec
import org.apache.spark.sql.execution.exchange.{ReusedExchangeExec, ShuffleExchangeExec, ShuffleExchangeLike}
import org.apache.spark.sql.functions.col
import org.apache.spark.sql.internal.SQLConf
-import org.apache.spark.sql.types.{ArrayType, StringType, StructType, TimestampType}
+import org.apache.spark.sql.types.{ArrayType, IntegerType, StringType, StructType, TimestampType}
import org.apache.comet.CometSparkSessionExtensions.{isSpark35Plus, isSpark40Plus, isSpark41Plus, isSpark42Plus}
+import org.apache.comet.cloud.s3.MinioLocationScopedCredentialProvider
import org.apache.comet.iceberg.{IcebergReflection, RESTCatalogHelper}
-import org.apache.comet.serde.OperatorOuterClass
+import org.apache.comet.serde.{OperatorOuterClass, QueryPlanSerde}
import org.apache.comet.testing.{FuzzDataGenerator, SchemaGenOptions}
/**
@@ -5150,6 +5152,280 @@ class CometIcebergNativeSuite
}
}
+ Seq(false, true).foreach { aqeEnabled =>
+ test(s"DPP - global aggregate after pruning a single split (AQE=$aqeEnabled)") {
+ assume(icebergAvailable, "Iceberg not available")
+ withTempIcebergDir { warehouseDir =>
+ val dimDir = new File(warehouseDir, "dim_parquet")
+ withSQLConf(
+ "spark.sql.catalog.aqe_cat" -> "org.apache.iceberg.spark.SparkCatalog",
+ "spark.sql.catalog.aqe_cat.type" -> "hadoop",
+ "spark.sql.catalog.aqe_cat.warehouse" -> warehouseDir.getAbsolutePath,
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqeEnabled.toString,
+ SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key -> "true",
+ CometConf.COMET_ENABLED.key -> "true",
+ CometConf.COMET_EXEC_ENABLED.key -> "true",
+ CometConf.COMET_ICEBERG_NATIVE_ENABLED.key -> "true") {
+ val factTable = "aqe_cat.db.single_split_dpp_fact"
+ spark.sql(s"""
+ CREATE TABLE $factTable (amount INT, store_id INT)
+ USING iceberg PARTITIONED BY (store_id)
+ """)
+ try {
+ spark
+ .range(100)
+ .selectExpr("CAST(id AS INT) AS amount", "5 AS store_id")
+ .coalesce(1)
+ .writeTo(factTable)
+ .append()
+
+ // The regression requires one original split: Spark 3.4 can then omit the
+ // exchange between the partial and final global aggregates.
+ val unprunedPlan = spark.table(factTable).queryExecution.executedPlan
+ assertSingleNativeScan(unprunedPlan)
+ val unprunedScan = collectIcebergNativeScans(unprunedPlan).head
+ assert(unprunedScan.numPartitions == 1, s"Expected one split:\n$unprunedPlan")
+ assert(
+ unprunedScan.perPartitionData
+ .map(OperatorOuterClass.IcebergScan.parseFrom(_).getFileScanTasksCount)
+ .sum == 1,
+ s"Expected one file scan task before pruning:\n$unprunedPlan")
+
+ spark
+ .range(1)
+ .selectExpr("99 AS store_id", "'X' AS country")
+ .write
+ .parquet(dimDir.getAbsolutePath)
+ withTempView("single_split_dim") {
+ spark.read
+ .parquet(dimDir.getAbsolutePath)
+ .createOrReplaceTempView("single_split_dim")
+ val query = s"""SELECT /*+ BROADCAST(d) */ COUNT(*), SUM(f.amount)
+ |FROM $factTable f JOIN single_split_dim d ON f.store_id = d.store_id
+ |WHERE d.country = 'X'""".stripMargin
+ val expected = Seq(Row(0L, null))
+ withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+ checkAnswer(spark.sql(query), expected)
+ }
+ val df = spark.sql(query)
+ checkCometAnswer(df, expected)
+
+ val plan = df.queryExecution.executedPlan
+ assertSingleNativeScan(plan)
+ val scan = collectIcebergNativeScans(plan).head
+ if (!isSpark35Plus) {
+ assert(
+ collect(plan) { case exchange: ShuffleExchangeLike => exchange }.isEmpty,
+ s"Expected the single-split aggregate to run without a shuffle:\n$plan")
+ assert(scan.numPartitions == 1, s"Expected one empty execution partition:\n$plan")
+ }
+ assert(
+ collectIcebergDPPSubqueries(plan).nonEmpty,
+ s"Expected executable DPP on the native scan:\n$plan")
+ assert(
+ scan.perPartitionData
+ .forall(OperatorOuterClass.IcebergScan.parseFrom(_).getFileScanTasksCount == 0),
+ s"Expected DPP to prune all file scan tasks:\n$plan")
+ assert(scan.metrics("num_splits").value == 0, "Pruned files must not be read")
+ }
+ } finally {
+ spark.sql(s"DROP TABLE $factTable")
+ }
+ }
+ }
+ }
+ }
+
+ for {
+ aqeEnabled <- Seq(false, true)
+ prunedSide <- Seq("a", "b")
+ } {
+ test(s"DPP - single-split sort-merge join (AQE=$aqeEnabled, pruned=$prunedSide)") {
+ assume(icebergAvailable, "Iceberg not available")
+ withTempIcebergDir { warehouseDir =>
+ val dimDir = new File(warehouseDir, "dim_parquet")
+ withSQLConf(
+ "spark.sql.catalog.aqe_cat" -> "org.apache.iceberg.spark.SparkCatalog",
+ "spark.sql.catalog.aqe_cat.type" -> "hadoop",
+ "spark.sql.catalog.aqe_cat.warehouse" -> warehouseDir.getAbsolutePath,
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqeEnabled.toString,
+ SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+ SQLConf.ADAPTIVE_AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+ SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key -> "true",
+ CometConf.COMET_ENABLED.key -> "true",
+ CometConf.COMET_EXEC_ENABLED.key -> "true",
+ CometConf.COMET_ICEBERG_NATIVE_ENABLED.key -> "true",
+ CometConf.COMET_EXEC_SORT_MERGE_JOIN_ENABLED.key -> "true",
+ CometConf.COMET_FORCE_SHJ.key -> "false") {
+ val factA = "aqe_cat.db.single_split_join_a"
+ val factB = "aqe_cat.db.single_split_join_b"
+ val tables = Seq(factA, factB)
+ def fileTaskCount(scan: CometIcebergNativeScanExec): Int =
+ scan.perPartitionData
+ .map(OperatorOuterClass.IcebergScan.parseFrom(_).getFileScanTasksCount)
+ .sum
+
+ try {
+ tables.foreach { table =>
+ spark.sql(s"""
+ CREATE TABLE $table (id INT, v INT, store_id INT)
+ USING iceberg PARTITIONED BY (store_id)
+ """)
+ spark
+ .range(100)
+ .selectExpr("CAST(id AS INT) AS id", "CAST(id AS INT) AS v", "5 AS store_id")
+ .coalesce(1)
+ .writeTo(table)
+ .append()
+
+ val unprunedPlan = spark.table(table).queryExecution.executedPlan
+ assertSingleNativeScan(unprunedPlan)
+ val scan = collectIcebergNativeScans(unprunedPlan).head
+ assert(scan.numPartitions == 1, s"Expected one split for $table:\n$unprunedPlan")
+ assert(
+ fileTaskCount(scan) == 1,
+ s"Expected one file task for $table:\n$unprunedPlan")
+ }
+
+ spark
+ .range(1)
+ .selectExpr("99 AS store_id", "'X' AS country")
+ .write
+ .parquet(dimDir.getAbsolutePath)
+ withTempView("single_split_join_dim") {
+ spark.read
+ .parquet(dimDir.getAbsolutePath)
+ .createOrReplaceTempView("single_split_join_dim")
+ val query = s"""SELECT /*+ BROADCAST(d), MERGE(a, b) */ COUNT(*), SUM(b.v)
+ |FROM $factA a JOIN $factB b ON a.id = b.id
+ |JOIN single_split_join_dim d ON $prunedSide.store_id = d.store_id
+ |WHERE d.country = 'X'""".stripMargin
+ val expected = Seq(Row(0L, null))
+ withSQLConf(CometConf.COMET_ENABLED.key -> "false") {
+ checkAnswer(spark.sql(query), expected)
+ }
+ val df = spark.sql(query)
+ val initialPlan = df.queryExecution.executedPlan
+ assert(
+ collectIcebergNativeScans(initialPlan).size == 2,
+ s"Expected two native Iceberg scans before execution:\n$initialPlan")
+ assert(
+ collectIcebergDPPSubqueries(initialPlan).size == 1,
+ s"Expected DPP on exactly one scan before execution:\n$initialPlan")
+ assert(
+ collect(initialPlan) { case join: CometSortMergeJoinExec => join }.size == 1,
+ s"Expected a native sort-merge join before execution:\n$initialPlan")
+ checkCometAnswer(df, expected)
+
+ val plan = df.queryExecution.executedPlan
+ val scans = collectIcebergNativeScans(plan)
+ if (isSpark35Plus && aqeEnabled && scans.isEmpty) {
+ // Newer Spark versions shuffle the join inputs, allowing AQE to replace
+ // the join and its scans with an empty relation after DPP prunes one input.
+ // This checks result compatibility; the SinglePartition regression assertions
+ // below target Spark 3.4, where both scans must remain in one native block.
+ assert(
+ collect(plan) { case empty: CometEmptyRelationExec => empty }.nonEmpty,
+ s"Expected AQE to replace the pruned join with an empty relation:\n$plan")
+ } else {
+ assert(scans.size == 2, s"Expected two native Iceberg scans:\n$plan")
+ val prunedScans = scans.filter(scan => collectIcebergDPPSubqueries(scan).nonEmpty)
+ assert(prunedScans.size == 1, s"Expected DPP on exactly one scan:\n$plan")
+ val prunedScan = prunedScans.head
+ assert(
+ fileTaskCount(prunedScan) == 0,
+ s"Expected all file tasks to be pruned:\n$plan")
+ assert(
+ prunedScan.metrics("num_splits").value == 0,
+ "Pruned files must not be read")
+ assert(
+ scans.filterNot(_ eq prunedScan).map(fileTaskCount) == Seq(1),
+ s"Expected the other scan to retain its file task:\n$plan")
+ }
+
+ if (!isSpark35Plus) {
+ val join = collectFirst(plan) { case j: CometSortMergeJoinExec => j }
+ .getOrElse(fail(s"Expected a native sort-merge join:\n$plan"))
+ assert(
+ collect(join) { case exchange: ShuffleExchangeLike => exchange }.isEmpty,
+ s"Expected no shuffle between the join and its scans:\n$plan")
+ val inputs = scala.collection.mutable.ArrayBuffer.empty[SparkPlan]
+ join.foreachUntilCometInput(join)(input => inputs += input)
+ val nativeScans = inputs.collect { case scan: CometIcebergNativeScanExec => scan }
+ assert(nativeScans.size == 2, s"Expected both scans in one native block:\n$plan")
+ assert(
+ nativeScans.forall(_.numPartitions == 1),
+ s"Expected both scans to retain one execution partition:\n$plan")
+ // Check execution input order, not just SQL aliases: pruning either input used
+ // to fail differently when its partition array was empty but the other was not.
+ val expectedTaskCounts = if (prunedSide == "a") Seq(0, 1) else Seq(1, 0)
+ assert(
+ nativeScans.map(fileTaskCount).toSeq == expectedTaskCounts,
+ s"Unexpected file tasks in native input order:\n$plan")
+ }
+ }
+ } finally {
+ tables.foreach(table => spark.sql(s"DROP TABLE IF EXISTS $table"))
+ }
+ }
+ }
+ }
+ }
+
+ test("DPP - empty Iceberg scan does not request S3 policy locations") {
+ // Exercise the empty executor scan emitted when DPP preserves Spark's last partition.
+ // A fresh catalog/bucket prevents a previously initialized FileIO from hiding the call.
+ val identity = UUID.randomUUID().toString
+ val common = OperatorOuterClass.IcebergScanCommon
+ .newBuilder()
+ .setMetadataLocation(s"s3://empty-scan-$identity/table/metadata/v1.metadata.json")
+ .setCatalogName(s"empty_scan_$identity")
+ .setDataFileConcurrencyLimit(1)
+ .putCatalogProperties(
+ "s3.comet.credential.provider.class",
+ classOf[MinioLocationScopedCredentialProvider].getName)
+ .addRequiredSchema(
+ OperatorOuterClass.SparkStructField
+ .newBuilder()
+ .setName("amount")
+ .setNullable(true)
+ .setDataType(QueryPlanSerde.serializeDataType(IntegerType).get))
+ .build()
+ val planBytes = OperatorOuterClass.Operator
+ .newBuilder()
+ .setIcebergScan(OperatorOuterClass.IcebergScan.newBuilder().setCommon(common))
+ .build()
+ .toByteArray
+
+ val result = spark.sparkContext
+ .parallelize(Seq(1), 1)
+ .mapPartitions { _ =>
+ MinioLocationScopedCredentialProvider.resetCounters()
+ val iterator = new CometExecIterator(
+ CometExec.newIterId,
+ Array.empty[Object],
+ 1,
+ planBytes,
+ CometMetricNode(Map.empty),
+ 1,
+ 0)
+ try {
+ var rows = 0L
+ while (iterator.hasNext) {
+ val batch = iterator.next()
+ rows += batch.numRows()
+ batch.close()
+ }
+ Iterator.single((rows, MinioLocationScopedCredentialProvider.locationCallCount()))
+ } finally {
+ iterator.close()
+ }
+ }
+ .collect()
+
+ assert(result.toSeq == Seq((0L, 0)), s"Expected no rows or policy requests: ${result.toSeq}")
+ }
+
test("AQE DPP - empty broadcast result prunes all partitions") {
assume(icebergAvailable, "Iceberg not available")
withTempIcebergDir { warehouseDir =>
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org