ulysses-you commented on code in PR #60675:
URL: https://github.com/apache/spark/pull/60675#discussion_r4628419558


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinExec.scala:
##########
@@ -61,14 +61,39 @@ case class SortMergeJoinExec(
     // For left and right outer joins, the output is ordered by the streamed 
input's join keys.
     case LeftOuter => getKeyOrdering(leftKeys, left.outputOrdering)
     case RightOuter => getKeyOrdering(rightKeys, right.outputOrdering)
-    // There are null rows in both streams, so there is no order.
-    case FullOuter => Nil
+    case FullOuter => fullOuterOutputOrdering
     case LeftExistence(_) => getKeyOrdering(leftKeys, left.outputOrdering)
     case x =>
       throw new IllegalArgumentException(
         s"${getClass.getSimpleName} should not take $x as the JoinType")
   }
 
+  /**
+   * For a single key or non-nullable composite keys, a FULL OUTER join merges 
in ascending
+   * order. Coalescing each key pair preserves that order when the absent 
side's key evaluates
+   * to NULL on the padded output row.
+   *
+   * A single nullable key is safe: NULL keys precede all non-NULL keys. With 
multiple keys, the
+   * scanners emit a row containing any NULL before comparing its leading 
components, e.g.
+   * (2, NULL) before (1, 0), so every input key must be non-nullable in that 
case.
+   */
+  private lazy val fullOuterOutputOrdering: Seq[SortOrder] = {
+    val supportsKeyNullability = leftKeys.length == 1 ||
+      (leftKeys.forall(!_.nullable) && rightKeys.forall(!_.nullable))
+
+    if (leftKeys.isEmpty ||

Review Comment:
   nit: this branch is dead. With empty keys `supportsKeyNullability` is 
vacuously true, both padding checks are vacuous, and `coalescedKeys(Nil)` 
already returns `Seq(Nil, Nil)`, so the result is `Nil` without it. 
`SortMergeJoinExec` is only built from `ExtractEquiJoinKeys`. Please drop it, 
or document why it is kept.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/joins/FullOuterJoinOrderingSuite.scala:
##########
@@ -0,0 +1,424 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.execution.joins
+
+import org.apache.spark.sql.{DataFrame, QueryTest, Row}
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.plans.FullOuter
+import org.apache.spark.sql.execution.{LocalTableScanExec, SortExec, 
SparkPlan, WholeStageCodegenExec}
+import org.apache.spark.sql.execution.adaptive.{AdaptiveSparkPlanHelper, 
AQEShuffleReadExec}
+import org.apache.spark.sql.execution.aggregate.SortAggregateExec
+import org.apache.spark.sql.execution.exchange.ShuffleExchangeExec
+import org.apache.spark.sql.execution.window.WindowExec
+import org.apache.spark.sql.functions.{coalesce, col}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{IntegerType, StructField, StructType}
+
+class FullOuterJoinOrderingSuite
+  extends QueryTest with SharedSparkSession with AdaptiveSparkPlanHelper {
+
+  override protected def sparkConf = super.sparkConf
+    .set(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key, "-1")
+    .set(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key, "false")
+    .set(SQLConf.PREFER_SORTMERGEJOIN.key, "true")
+    .set(SQLConf.SHUFFLE_PARTITIONS.key, "5")
+    .set(SQLConf.SHUFFLE_SPREAD_NULL_JOIN_KEYS_ENABLED.key, "false")
+    .set(SQLConf.ENABLE_FULL_OUTER_SORT_MERGE_JOIN_CODEGEN.key, "true")
+    .set(SQLConf.ADAPTIVE_MAX_SHUFFLE_HASH_JOIN_LOCAL_MAP_THRESHOLD.key, "0")
+
+  testWithWholeStageCodegenOnAndOff("single nullable keys retain merged 
ordering") { codegen =>
+    withSingleKeys(
+        Seq(Row(null), Row(1), Row(3), Row(3)),
+        Seq(Row(null), Row(2), Row(3), Row(4))) {
+      val df = sql("SELECT /*+ MERGE(a, b) */ k FROM a FULL OUTER JOIN b USING 
(k)")
+      checkOrdered(df, Seq(Row(null), Row(null), Row(1), Row(2), Row(3), 
Row(3), Row(4)), "k")
+      val plan = df.queryExecution.executedPlan
+      val generatedJoins = collect(plan) {
+        case w: WholeStageCodegenExec if 
w.exists(_.isInstanceOf[SortMergeJoinExec]) => w
+      }
+      assert(generatedJoins.nonEmpty == codegen.toBoolean, plan)
+      assert(fullOuterJoin(df).leftKeys.head.nullable)
+    }
+  }
+
+  testWithWholeStageCodegenOnAndOff("disjoint keys and exhausted inputs retain 
ordering") { _ =>
+    withSQLConf(SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      Seq(
+        (Seq(Row(1), Row(2), Row(3)), Seq(Row(4), Row(5)), (1 to 
5).map(Row(_))),
+        (Seq.empty[Row], Seq(Row(2), Row(1)), Seq(Row(1), Row(2))),
+        (Seq(Row(2), Row(1)), Seq.empty[Row], Seq(Row(1), Row(2)))).foreach {
+        case (left, right, expected) =>
+          withSingleKeys(left, right) {
+            val df = sql("SELECT /*+ MERGE(a, b) */ k FROM a FULL OUTER JOIN b 
USING (k)")
+            fullOuterJoin(df)
+            checkOrdered(df, expected, "k")
+          }
+      }
+    }
+  }
+
+  testWithWholeStageCodegenOnAndOff("residual predicates keep equal-key groups 
together") { _ =>
+    withTempView("a", "b") {
+      frame(Seq(Row(1, 0), Row(3, 10), Row(3, 20), Row(5, 0)),
+        "k" -> false, "v" -> false).createOrReplaceTempView("a")
+      frame(Seq(Row(2, 0), Row(3, 15), Row(3, 5), Row(4, 0)),
+        "k" -> false, "v" -> false).createOrReplaceTempView("b")
+      val df = sql(
+        """SELECT /*+ MERGE(a, b) */ coalesce(a.k, b.k) AS k, a.v, b.v
+          |FROM a FULL OUTER JOIN b ON a.k = b.k AND a.v < b.v""".stripMargin)
+      assert(fullOuterJoin(df).condition.nonEmpty)
+      checkOrdered(df, Seq(
+        Row(1, 0, null), Row(2, null, 0), Row(3, 10, 15), Row(3, 20, null),
+        Row(3, null, 5), Row(4, null, 0), Row(5, 0, null)), "k")
+    }
+  }
+
+  testWithWholeStageCodegenOnAndOff("non-null composite keys support mixed 
COALESCE orders") { _ =>
+    withTempView("a", "b") {
+      frame(Seq(Row(1, 2), Row(2, 0), Row(2, 0), Row(5, 1)),
+        "k1" -> false, "k2" -> false).createOrReplaceTempView("a")
+      frame(Seq(Row(1, 1), Row(2, 0), Row(4, 3)),
+        "k1" -> false, "k2" -> false).createOrReplaceTempView("b")
+      val df = sql(
+        """SELECT /*+ MERGE(a, b) */
+          |coalesce(a.k1, b.k1) AS x, coalesce(b.k2, a.k2) AS y
+          |FROM a FULL OUTER JOIN b ON a.k1 = b.k1 AND a.k2 = 
b.k2""".stripMargin)
+      val join = fullOuterJoin(df)
+      assert((join.leftKeys ++ join.rightKeys).forall(!_.nullable))
+      checkOrdered(df, Seq(Row(1, 1), Row(1, 2), Row(2, 0), Row(2, 0), Row(4, 
3), Row(5, 1)),
+        "x", "y")
+      val sorted = df.sortWithinPartitions("x", "y")
+      assert(numSorts(sorted.queryExecution.executedPlan) == 2)
+    }
+  }
+
+  testWithWholeStageCodegenOnAndOff("nullable composite keys keep their 
consumer sort") { _ =>
+    withSQLConf(SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      val nullable = frame(Seq(Row(2, null)), "k1" -> false, "k2" -> true)
+      val nonNullable = frame(Seq(Row(1, 0)), "k1" -> false, "k2" -> false)
+      Seq((nullable, nonNullable), (nonNullable, nullable)).foreach { case 
(left, right) =>
+        val df = left.as("l").hint("merge").join(right.as("r"),
+          col("l.k1") === col("r.k1") && col("l.k2") === col("r.k2"), 
"full_outer")
+          .select(coalesce(col("l.k1"), col("r.k1")).as("k1"),
+            coalesce(col("l.k2"), col("r.k2")).as("k2"))
+        assert(fullOuterJoin(df).outputOrdering.isEmpty)
+        assert(df.collect().toSeq == Seq(Row(2, null), Row(1, 0)))

Review Comment:
   nit: this pins the scanner's internal emission order, not the contract. The 
case only guarantees `outputOrdering.isEmpty` (asserted just above); the exact 
order comes from the eager any-NULL branch in 
`SortMergeFullOuterJoinScanner.advanceNext`. A future change to that emission 
order would fail this test for an unrelated reason. Suggest asserting the row 
multiset instead.
   



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