snmvaughan commented on code in PR #7662:
URL: https://github.com/apache/datafusion-comet/pull/7662#discussion_r4644767544


##########
spark/src/main/scala/org/apache/spark/sql/comet/operators.scala:
##########
@@ -741,17 +741,53 @@ abstract class CometExec extends CometPlan {
  * Declares the distribution of the Spark operator that a Comet operator 
replaces. Without it
  * AQE's OptimizeSkewInRebalancePartitions can split a skewed partition under 
an operator that
  * needs its input clustered, because ValidateRequirements has nothing to 
reject, and one key then
- * yields several rows. Mix it into operators that replace a clustering 
aggregate, window or join.
+ * yields several rows. Mix it into operators that replace a clustering 
aggregate or window. A
+ * join mixes in [[CometDelegatesJoinChildDistribution]] instead.
  */
 trait CometDelegatesRequiredChildDistribution extends CometExec {
   override def requiredChildDistribution: Seq[Distribution] =
     originalPlan.requiredChildDistribution
 }
 
+/**
+ * [[CometDelegatesRequiredChildDistribution]] for a join. A 
storage-partitioned join, whose sides
+ * are key-grouped scans that Spark joins with no exchange, declares no 
requirement. No shuffle
+ * sits below it for AQE to split. EnsureRequirements only accepts such a join 
when it is Spark's
+ * own join operator, and in Spark 4.1 only over Spark's own scans. So when 
AQE plans a DPP
+ * subquery's converted plan again, it would put an exchange under each side 
that it has no
+ * logical link for (#7441). The sides are the join's current children, which 
are Comet operators,
+ * because conversion works bottom-up and AQE can later swap in query stages.
+ */
+trait CometDelegatesJoinChildDistribution extends 
CometDelegatesRequiredChildDistribution {
+  override def requiredChildDistribution: Seq[Distribution] =
+    if (children.forall(CometExec.isStoragePartitioned)) {
+      children.map(_ => UnspecifiedDistribution)
+    } else {
+      super.requiredChildDistribution
+    }
+}
+
 object CometExec {
   final class InvalidSparkFallbackException(message: String)
       extends IllegalArgumentException(message)
 
+  /**
+   * Whether `plan` reads only key-grouped scans, with no shuffle above them. 
This is how Spark
+   * plans each side of a storage-partitioned join. A scan counts only when 
the scan it replaces
+   * or wraps was planned key-grouped, so a table read without grouping does 
not.
+   */
+  private[comet] def isStoragePartitioned(plan: SparkPlan): Boolean =
+    !plan.exists(_.isInstanceOf[ShuffleExchangeLike]) &&
+      plan.collectLeaves().forall {
+        // Spark's own scans. Comet's non-native V2 scan, CometBatchScanExec, 
is a leaf under a
+        // CometScanWrapper that this does not unwrap, so a join over it keeps 
its requirement.

Review Comment:
   You're right, thank you. `CometBatchScanExec` is only built for CSV, Text 
and Iceberg, and `CometExecRule` handles each of them before the 
`CometScanWrapper` case, so a declined Iceberg conversion stays a bare 
`CometBatchScanExec` that this case already matches. I used your wording for 
the comment and removed the paragraph from the description. Done in 7835efea9.
   



##########
spark/src/test/scala/org/apache/comet/CometIcebergNativeSuite.scala:
##########
@@ -7033,6 +7033,133 @@ class CometIcebergNativeSuite
     }
   }
 
+  // A storage-partitioned join is a sort-merge join that Spark plans without 
a shuffle, because
+  // both scans report a KeyGroupedPartitioning. On the build side of a DPP 
broadcast, AQE plans
+  // the converted join again, and EnsureRequirements has to find the join's 
required distribution
+  // already met rather than put an exchange under each side, which AQE has no 
logical link for
+  // (#7441).
+  test("AQE DPP - storage-partitioned join on the DPP build side (#7441)") {
+    assume(icebergAvailable, "Iceberg not available")
+    withTempIcebergDir { warehouseDir =>
+      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 -> "true",
+        SQLConf.DYNAMIC_PARTITION_PRUNING_REUSE_BROADCAST_ONLY.key -> "true",
+        SQLConf.V2_BUCKETING_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_PUSH_PART_VALUES_ENABLED.key -> "true",
+        "spark.sql.iceberg.planning.preserve-data-grouping" -> "true",
+        CometConf.COMET_ENABLED.key -> "true",
+        CometConf.COMET_EXEC_ENABLED.key -> "true",
+        CometConf.COMET_ICEBERG_NATIVE_ENABLED.key -> "true") {
+
+        spark.sql("""
+          CREATE TABLE aqe_cat.db.spj_dpp_fact (amount INT, store_id INT)
+          USING iceberg PARTITIONED BY (store_id)
+        """)
+        spark.sql("""
+          CREATE TABLE aqe_cat.db.spj_dpp_dim_a (id INT, country STRING)
+          USING iceberg PARTITIONED BY (id)
+        """)
+        spark.sql("""
+          CREATE TABLE aqe_cat.db.spj_dpp_dim_b (id INT, name STRING)
+          USING iceberg PARTITIONED BY (id)
+        """)
+        spark.sql(
+          "INSERT INTO aqe_cat.db.spj_dpp_fact SELECT CAST(id AS INT), CAST(id 
% 10 AS INT) " +
+            "FROM range(0, 100)")
+        spark.sql(
+          "INSERT INTO aqe_cat.db.spj_dpp_dim_a SELECT CAST(id AS INT), " +
+            "IF(id < 3, 'X', 'Y') FROM range(0, 10)")
+        spark.sql(
+          "INSERT INTO aqe_cat.db.spj_dpp_dim_b SELECT CAST(id AS INT), 
concat('n', id) " +
+            "FROM range(0, 10)")
+
+        // The merge join of the two dimensions is the build side of the 
broadcast that prunes the
+        // fact scan. It needs no shuffle because both of its scans are 
key-grouped on id.
+        val query =
+          """SELECT /*+ BROADCAST(d) */ f.store_id, f.amount, d.name
+            |FROM aqe_cat.db.spj_dpp_fact f JOIN (
+            |  SELECT /*+ MERGE(a, b) */ a.id, b.name

Review Comment:
   Done in 7835efea9. The two queries and the two hints are now generated with 
a `for`, the tables are created once per case and dropped in a `finally`, and 
every case asserts the join operator the hint should produce 
(`CometSortMergeJoinExec` for `MERGE`, `CometHashJoinExec` for `SHUFFLE_HASH`), 
that the fact scan carries a DPP filter, and that neither the plan nor the DPP 
subquery's plan has an exchange, which the aggregate query now gets too. Thank 
you for running the `SHUFFLE_HASH` variant against a reverted `operators.scala`.
   



##########
spark/src/main/scala/org/apache/spark/sql/comet/CometIcebergNativeScanExec.scala:
##########
@@ -136,16 +136,23 @@ case class CometIcebergNativeScanExec(
   // tasks here would run a placeholder subquery. At execution, 
CometNativeExec sizes the native
   // RDD from perPartitionData instead.
   //
-  // Spark 3.4's BatchScanExec reports SinglePartition for one input 
partition, which it counts
-  // before any DPP filtering, and Spark plans no exchange above it on that 
basis. The scan reports
-  // the same. Otherwise EnsureRequirements, which AQE runs again over a DPP 
subquery's converted
-  // plan, inserts an exchange inside a native block that is already 
serialized (#7422).
-  // serializePartitions keeps that one partition when DPP prunes it, as Spark 
does.
+  // Spark 3.4's BatchScanExec reports SinglePartition for one input 
partition, and every supported
+  // version reports a key-grouped partitioning (KeyGroupedPartitioning, 
called KeyedPartitioning
+  // from Spark 4.2) for a storage-partitioned scan. Spark takes both from the 
partitions it plans,
+  // before any DPP filtering, and plans the operators above the scan on that 
basis, with no
+  // exchange for a join or aggregate that the partitioning already satisfies. 
The scan reports the
+  // same, so reading it resolves no DPP subquery. Otherwise 
EnsureRequirements, which AQE runs
+  // again over a DPP subquery's converted plan, inserts exchanges inside a 
native block that is
+  // already serialized (#7422, #7441). serializePartitions keeps one 
partition for each of Spark's
+  // partitions when DPP prunes some, as Spark does.
   override lazy val outputPartitioning: Partitioning =
-    if (originalPlan != null && originalPlan.outputPartitioning == 
SinglePartition) {
-      SinglePartition
-    } else {
+    if (originalPlan == null) {
       UnknownPartitioning(0)
+    } else {
+      originalPlan.outputPartitioning match {
+        case _: UnknownPartitioning => UnknownPartitioning(0)
+        case reported => reported
+      }

Review Comment:
   Done in 6dab540e2, thank you. I checked 
`DataSourceV2ScanExecBase.outputPartitioning` on Spark 3.5.9, 4.0.4, 4.1.3 and 
4.2.0, and its fallback is `super.outputPartitioning` in each, so the match was 
dead code. The `originalPlan == null` guard stays, because a canonicalized copy 
has no original plan.
   



-- 
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]

Reply via email to