You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "vinodkc (via GitHub)" <gi...@apache.org> on 2023/07/06 22:31:39 UTC

[GitHub] [spark] vinodkc opened a new pull request, #41884: [SPARK-44325][SQL]Use PartitionEvaluator API for SortMergeJoinExec

vinodkc opened a new pull request, #41884:
URL: https://github.com/apache/spark/pull/41884

   <!--
   Thanks for sending a pull request!  Here are some tips for you:
     1. If this is your first time, please read our contributor guidelines: https://spark.apache.org/contributing.html
     2. Ensure you have added or run the appropriate tests for your PR: https://spark.apache.org/developer-tools.html
     3. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP][SPARK-XXXX] Your PR title ...'.
     4. Be sure to keep the PR description updated to reflect all changes.
     5. Please write your PR title to summarize what this PR proposes.
     6. If possible, provide a concise example to reproduce the issue for a faster review.
     7. If you want to add a new configuration, please read the guideline first for naming configurations in
        'core/src/main/scala/org/apache/spark/internal/config/ConfigEntry.scala'.
     8. If you want to add or modify an error type or message, please read the guideline first in
        'core/src/main/resources/error/README.md'.
   -->
   
   ### What changes were proposed in this pull request?
   <!--
   Please clarify what changes you are proposing. The purpose of this section is to outline the changes and how this PR fixes the issue. 
   If possible, please consider writing useful notes for better and faster reviews in your PR. See the examples below.
     1. If you refactor some codes with changing classes, showing the class hierarchy will help reviewers.
     2. If you fix some SQL features, you can provide some references of other DBMSes.
     3. If there is design documentation, please add the link.
     4. If there is a discussion in the mailing list, please add the link.
   -->
   SQL operator `SortMergeJoinExec` updated to use the `PartitionEvaluator` API to do execution.
   
   ### Why are the changes needed?
   <!--
   Please clarify why the changes are needed. For instance,
     1. If you propose a new API, clarify the use case for a new API.
     2. If you fix a bug, you can clarify why it is a bug.
   -->
   To avoid the use of lambda during distributed execution.
   Ref: SPARK-43061 for more details.
   
   ### Does this PR introduce _any_ user-facing change?
   <!--
   Note that it means *any* user-facing change including all aspects such as the documentation fix.
   If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description and/or an example to show the behavior difference if possible.
   If possible, please also clarify if this is a user-facing change compared to the released Spark versions or within the unreleased branches such as master.
   If no, write 'No'.
   -->
   No
   
   ### How was this patch tested?
   <!--
   If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
   If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
   If tests were not added, please describe why they were not added and/or why it was difficult to add.
   If benchmark tests were added, please run the benchmarks in GitHub Actions for the consistent environment, and the instructions could accord to: https://spark.apache.org/developer-tools.html#github-workflow-benchmarks.
   -->
   Updated 1 test case, once all the SQL operators are migrated, the flag `spark.sql.execution.useTaskEvaluator` will be enabled by default to avoid running the tests with and without this TaskEvaluator
   


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] yaooqinn closed pull request #41884: [SPARK-44325][SQL] Use PartitionEvaluator API in SortMergeJoinExec

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn closed pull request #41884: [SPARK-44325][SQL] Use PartitionEvaluator API in SortMergeJoinExec
URL: https://github.com/apache/spark/pull/41884


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] vinodkc commented on a diff in pull request #41884: [SPARK-44325][SQL] Use PartitionEvaluator API in SortMergeJoinExec

Posted by "vinodkc (via GitHub)" <gi...@apache.org>.
vinodkc commented on code in PR #41884:
URL: https://github.com/apache/spark/pull/41884#discussion_r1276595994


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinExec.scala:
##########
@@ -128,249 +122,27 @@ case class SortMergeJoinExec(
     val spillSize = longMetric("spillSize")
     val spillThreshold = getSpillThreshold
     val inMemoryThreshold = getInMemoryThreshold
-    left.execute().zipPartitions(right.execute()) { (leftIter, rightIter) =>
-      val boundCondition: (InternalRow) => Boolean = {
-        condition.map { cond =>
-          Predicate.create(cond, left.output ++ right.output).eval _
-        }.getOrElse {
-          (r: InternalRow) => true
-        }
-      }
-
-      // An ordering that can be used to compare keys from both sides.
-      val keyOrdering = RowOrdering.createNaturalAscendingOrdering(leftKeys.map(_.dataType))
-      val resultProj: InternalRow => InternalRow = UnsafeProjection.create(output, output)
-
-      joinType match {
-        case _: InnerLike =>
-          new RowIterator {
-            private[this] var currentLeftRow: InternalRow = _
-            private[this] var currentRightMatches: ExternalAppendOnlyUnsafeRowArray = _
-            private[this] var rightMatchesIterator: Iterator[UnsafeRow] = null
-            private[this] val smjScanner = new SortMergeJoinScanner(
-              createLeftKeyGenerator(),
-              createRightKeyGenerator(),
-              keyOrdering,
-              RowIterator.fromScala(leftIter),
-              RowIterator.fromScala(rightIter),
-              inMemoryThreshold,
-              spillThreshold,
-              spillSize,
-              cleanupResources
-            )
-            private[this] val joinRow = new JoinedRow
-
-            if (smjScanner.findNextInnerJoinRows()) {
-              currentRightMatches = smjScanner.getBufferedMatches
-              currentLeftRow = smjScanner.getStreamedRow
-              rightMatchesIterator = currentRightMatches.generateIterator()
-            }
-
-            override def advanceNext(): Boolean = {
-              while (rightMatchesIterator != null) {
-                if (!rightMatchesIterator.hasNext) {
-                  if (smjScanner.findNextInnerJoinRows()) {
-                    currentRightMatches = smjScanner.getBufferedMatches
-                    currentLeftRow = smjScanner.getStreamedRow
-                    rightMatchesIterator = currentRightMatches.generateIterator()
-                  } else {
-                    currentRightMatches = null
-                    currentLeftRow = null
-                    rightMatchesIterator = null
-                    return false
-                  }
-                }
-                joinRow(currentLeftRow, rightMatchesIterator.next())
-                if (boundCondition(joinRow)) {
-                  numOutputRows += 1
-                  return true
-                }
-              }
-              false
-            }
-
-            override def getRow: InternalRow = resultProj(joinRow)
-          }.toScala
-
-        case LeftOuter =>
-          val smjScanner = new SortMergeJoinScanner(
-            streamedKeyGenerator = createLeftKeyGenerator(),
-            bufferedKeyGenerator = createRightKeyGenerator(),
-            keyOrdering,
-            streamedIter = RowIterator.fromScala(leftIter),
-            bufferedIter = RowIterator.fromScala(rightIter),
-            inMemoryThreshold,
-            spillThreshold,
-            spillSize,
-            cleanupResources
-          )
-          val rightNullRow = new GenericInternalRow(right.output.length)
-          new LeftOuterIterator(
-            smjScanner, rightNullRow, boundCondition, resultProj, numOutputRows).toScala
-
-        case RightOuter =>
-          val smjScanner = new SortMergeJoinScanner(
-            streamedKeyGenerator = createRightKeyGenerator(),
-            bufferedKeyGenerator = createLeftKeyGenerator(),
-            keyOrdering,
-            streamedIter = RowIterator.fromScala(rightIter),
-            bufferedIter = RowIterator.fromScala(leftIter),
-            inMemoryThreshold,
-            spillThreshold,
-            spillSize,
-            cleanupResources
-          )
-          val leftNullRow = new GenericInternalRow(left.output.length)
-          new RightOuterIterator(
-            smjScanner, leftNullRow, boundCondition, resultProj, numOutputRows).toScala
-
-        case FullOuter =>
-          val leftNullRow = new GenericInternalRow(left.output.length)
-          val rightNullRow = new GenericInternalRow(right.output.length)
-          val smjScanner = new SortMergeFullOuterJoinScanner(
-            leftKeyGenerator = createLeftKeyGenerator(),
-            rightKeyGenerator = createRightKeyGenerator(),
-            keyOrdering,
-            leftIter = RowIterator.fromScala(leftIter),
-            rightIter = RowIterator.fromScala(rightIter),
-            boundCondition,
-            leftNullRow,
-            rightNullRow)
-
-          new FullOuterIterator(
-            smjScanner,
-            resultProj,
-            numOutputRows).toScala
-
-        case LeftSemi =>
-          new RowIterator {
-            private[this] var currentLeftRow: InternalRow = _
-            private[this] val smjScanner = new SortMergeJoinScanner(
-              createLeftKeyGenerator(),
-              createRightKeyGenerator(),
-              keyOrdering,
-              RowIterator.fromScala(leftIter),
-              RowIterator.fromScala(rightIter),
-              inMemoryThreshold,
-              spillThreshold,
-              spillSize,
-              cleanupResources,
-              onlyBufferFirstMatchedRow
-            )
-            private[this] val joinRow = new JoinedRow
-
-            override def advanceNext(): Boolean = {
-              while (smjScanner.findNextInnerJoinRows()) {
-                val currentRightMatches = smjScanner.getBufferedMatches
-                currentLeftRow = smjScanner.getStreamedRow
-                if (currentRightMatches != null && currentRightMatches.length > 0) {
-                  val rightMatchesIterator = currentRightMatches.generateIterator()
-                  while (rightMatchesIterator.hasNext) {
-                    joinRow(currentLeftRow, rightMatchesIterator.next())
-                    if (boundCondition(joinRow)) {
-                      numOutputRows += 1
-                      return true
-                    }
-                  }
-                }
-              }
-              false
-            }
-
-            override def getRow: InternalRow = currentLeftRow
-          }.toScala
-
-        case LeftAnti =>
-          new RowIterator {
-            private[this] var currentLeftRow: InternalRow = _
-            private[this] val smjScanner = new SortMergeJoinScanner(
-              createLeftKeyGenerator(),
-              createRightKeyGenerator(),
-              keyOrdering,
-              RowIterator.fromScala(leftIter),
-              RowIterator.fromScala(rightIter),
-              inMemoryThreshold,
-              spillThreshold,
-              spillSize,
-              cleanupResources,
-              onlyBufferFirstMatchedRow
-            )
-            private[this] val joinRow = new JoinedRow
-
-            override def advanceNext(): Boolean = {
-              while (smjScanner.findNextOuterJoinRows()) {
-                currentLeftRow = smjScanner.getStreamedRow
-                val currentRightMatches = smjScanner.getBufferedMatches
-                if (currentRightMatches == null || currentRightMatches.length == 0) {
-                  numOutputRows += 1
-                  return true
-                }
-                var found = false
-                val rightMatchesIterator = currentRightMatches.generateIterator()
-                while (!found && rightMatchesIterator.hasNext) {
-                  joinRow(currentLeftRow, rightMatchesIterator.next())
-                  if (boundCondition(joinRow)) {
-                    found = true
-                  }
-                }
-                if (!found) {
-                  numOutputRows += 1
-                  return true
-                }
-              }
-              false
-            }
-
-            override def getRow: InternalRow = currentLeftRow
-          }.toScala
-
-        case j: ExistenceJoin =>
-          new RowIterator {
-            private[this] var currentLeftRow: InternalRow = _
-            private[this] val result: InternalRow = new GenericInternalRow(Array[Any](null))
-            private[this] val smjScanner = new SortMergeJoinScanner(
-              createLeftKeyGenerator(),
-              createRightKeyGenerator(),
-              keyOrdering,
-              RowIterator.fromScala(leftIter),
-              RowIterator.fromScala(rightIter),
-              inMemoryThreshold,
-              spillThreshold,
-              spillSize,
-              cleanupResources,
-              onlyBufferFirstMatchedRow
-            )
-            private[this] val joinRow = new JoinedRow
-
-            override def advanceNext(): Boolean = {
-              while (smjScanner.findNextOuterJoinRows()) {
-                currentLeftRow = smjScanner.getStreamedRow
-                val currentRightMatches = smjScanner.getBufferedMatches
-                var found = false
-                if (currentRightMatches != null && currentRightMatches.length > 0) {
-                  val rightMatchesIterator = currentRightMatches.generateIterator()
-                  while (!found && rightMatchesIterator.hasNext) {
-                    joinRow(currentLeftRow, rightMatchesIterator.next())
-                    if (boundCondition(joinRow)) {
-                      found = true
-                    }
-                  }
-                }
-                result.setBoolean(0, found)
-                numOutputRows += 1
-                return true
-              }
-              false
-            }
-
-            override def getRow: InternalRow = resultProj(joinRow(currentLeftRow, result))
-          }.toScala
-
-        case x =>
-          throw new IllegalArgumentException(
-            s"SortMergeJoin should not take $x as the JoinType")
+    val evaluatorFactory = new SortMergeJoinEvaluatorFactory(
+      leftKeys,
+      rightKeys,
+      joinType,
+      condition,
+      left,
+      right,
+      output,
+      inMemoryThreshold,
+      spillThreshold,
+      numOutputRows,
+      spillSize,
+      onlyBufferFirstMatchedRow
+    )
+    if (conf.usePartitionEvaluator) {
+      left.execute().zipPartitionsWithEvaluator(right.execute(), evaluatorFactory)
+    } else {
+      left.execute().zipPartitions(right.execute()) { (leftIter, rightIter) =>
+        val evaluator = evaluatorFactory.createEvaluator()
+        evaluator.eval(0, leftIter, rightIter)

Review Comment:
   `zipPartitionsWithIndex` method is currently absent, hence 0 index is passed to evaluator.eval(0, ...)
   
   Once `spark.sql.execution.useTaskEvaluator` is set to true by default, this block will not be executed.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] beliefer commented on a diff in pull request #41884: [SPARK-44325][SQL] Use PartitionEvaluator API in SortMergeJoinExec

Posted by "beliefer (via GitHub)" <gi...@apache.org>.
beliefer commented on code in PR #41884:
URL: https://github.com/apache/spark/pull/41884#discussion_r1258202239


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,306 @@
+/*
+ * 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.{PartitionEvaluator, PartitionEvaluatorFactory}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, Predicate, Projection, RowOrdering, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.plans.{ExistenceJoin, FullOuter, InnerLike, JoinType, LeftAnti, LeftOuter, LeftSemi, RightOuter}
+import org.apache.spark.sql.execution.{ExternalAppendOnlyUnsafeRowArray, RowIterator, SparkPlan}
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+class SortMergeJoinEvaluatorFactory(
+    leftKeys: Seq[Expression],
+    rightKeys: Seq[Expression],
+    joinType: JoinType,
+    condition: Option[Expression],
+    left: SparkPlan,
+    right: SparkPlan,
+    output: Seq[Attribute],
+    inMemoryThreshold: Int,
+    spillThreshold: Int,
+    numOutputRows: SQLMetric,
+    spillSize: SQLMetric,
+    onlyBufferFirstMatchedRow: Boolean)
+    extends PartitionEvaluatorFactory[InternalRow, InternalRow] {
+  override def createEvaluator(): PartitionEvaluator[InternalRow, InternalRow] =
+    new SortMergeJoinEvaluator
+
+  private class SortMergeJoinEvaluator extends PartitionEvaluator[InternalRow, InternalRow] {
+
+    private def cleanupResources(): Unit = {
+      IndexedSeq(left, right).foreach(_.cleanupResources())
+    }
+    private def createLeftKeyGenerator(): Projection =
+      UnsafeProjection.create(leftKeys, left.output)
+
+    private def createRightKeyGenerator(): Projection =
+      UnsafeProjection.create(rightKeys, right.output)
+
+    override def eval(
+        partitionIndex: Int,
+        inputs: Iterator[InternalRow]*): Iterator[InternalRow] = {
+      assert(inputs.length == 2)
+      val leftIter = inputs(0)
+      val rightIter = inputs(1)
+
+      val boundCondition: InternalRow => Boolean = {
+        condition
+          .map { cond =>
+            Predicate.create(cond, left.output ++ right.output).eval _
+          }
+          .getOrElse { (r: InternalRow) =>
+            true
+          }

Review Comment:
   ```suggestion
           condition.map { cond =>
             Predicate.create(cond, left.output ++ right.output).eval _
           }.getOrElse {
             (r: InternalRow) => true
           }
   ```



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] cloud-fan commented on a diff in pull request #41884: [SPARK-44325][SQL] Use PartitionEvaluator API in SortMergeJoinExec

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #41884:
URL: https://github.com/apache/spark/pull/41884#discussion_r1256379618


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,299 @@
+/*
+ * 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.{PartitionEvaluator, PartitionEvaluatorFactory}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, Predicate, Projection, RowOrdering, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.plans.{ExistenceJoin, FullOuter, InnerLike, JoinType, LeftAnti, LeftOuter, LeftSemi, RightOuter}
+import org.apache.spark.sql.execution.{ExternalAppendOnlyUnsafeRowArray, RowIterator}
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+class SortMergeJoinEvaluatorFactory(
+    leftKeys: Seq[Expression],
+    rightKeys: Seq[Expression],
+    joinType: JoinType,
+    condition: Option[Expression],
+    leftOutput: Seq[Attribute],
+    rightOutput: Seq[Attribute],
+    output: Seq[Attribute],
+    createLeftKeyGenerator: () => Projection,

Review Comment:
   is it possible to pass the necessary arguments that can create the key generators? we'd better avoid serializing a lambda.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] vinodkc commented on a diff in pull request #41884: [SPARK-44325][SQL] Use PartitionEvaluator API in SortMergeJoinExec

Posted by "vinodkc (via GitHub)" <gi...@apache.org>.
vinodkc commented on code in PR #41884:
URL: https://github.com/apache/spark/pull/41884#discussion_r1257318242


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,299 @@
+/*
+ * 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.{PartitionEvaluator, PartitionEvaluatorFactory}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, Predicate, Projection, RowOrdering, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.plans.{ExistenceJoin, FullOuter, InnerLike, JoinType, LeftAnti, LeftOuter, LeftSemi, RightOuter}
+import org.apache.spark.sql.execution.{ExternalAppendOnlyUnsafeRowArray, RowIterator}
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+class SortMergeJoinEvaluatorFactory(
+    leftKeys: Seq[Expression],
+    rightKeys: Seq[Expression],
+    joinType: JoinType,
+    condition: Option[Expression],
+    leftOutput: Seq[Attribute],
+    rightOutput: Seq[Attribute],
+    output: Seq[Attribute],
+    createLeftKeyGenerator: () => Projection,

Review Comment:
   Done



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,303 @@
+/*
+ * 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.{PartitionEvaluator, PartitionEvaluatorFactory}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, Predicate, Projection, RowOrdering, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.plans.{ExistenceJoin, FullOuter, InnerLike, JoinType, LeftAnti, LeftOuter, LeftSemi, RightOuter}
+import org.apache.spark.sql.execution.{ExternalAppendOnlyUnsafeRowArray, RowIterator}
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+class SortMergeJoinEvaluatorFactory(
+    leftKeys: Seq[Expression],
+    rightKeys: Seq[Expression],
+    joinType: JoinType,
+    condition: Option[Expression],
+    leftOutput: Seq[Attribute],
+    rightOutput: Seq[Attribute],
+    output: Seq[Attribute],
+    inMemoryThreshold: Int,
+    spillThreshold: Int,
+    numOutputRows: SQLMetric,
+    spillSize: SQLMetric,
+    cleanupResources: () => Unit,

Review Comment:
   Done



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] viirya commented on a diff in pull request #41884: [SPARK-44325][SQL] Use PartitionEvaluator API in SortMergeJoinExec

Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #41884:
URL: https://github.com/apache/spark/pull/41884#discussion_r1257422559


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,307 @@
+/*
+ * 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.{PartitionEvaluator, PartitionEvaluatorFactory}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, Predicate, Projection, RowOrdering, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.plans.{ExistenceJoin, FullOuter, InnerLike, JoinType, LeftAnti, LeftOuter, LeftSemi, RightOuter}
+import org.apache.spark.sql.execution.{ExternalAppendOnlyUnsafeRowArray, RowIterator, SparkPlan}
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+class SortMergeJoinEvaluatorFactory(
+    leftKeys: Seq[Expression],
+    rightKeys: Seq[Expression],
+    joinType: JoinType,
+    condition: Option[Expression],
+    left: SparkPlan,
+    right: SparkPlan,
+    output: Seq[Attribute],
+    inMemoryThreshold: Int,
+    spillThreshold: Int,
+    numOutputRows: SQLMetric,
+    spillSize: SQLMetric,
+    onlyBufferFirstMatchedRow: Boolean)
+    extends PartitionEvaluatorFactory[InternalRow, InternalRow] {
+  override def createEvaluator(): PartitionEvaluator[InternalRow, InternalRow] =
+    new SortMergeJoinEvaluator
+
+  private class SortMergeJoinEvaluator extends PartitionEvaluator[InternalRow, InternalRow] {
+
+    private lazy val children: Seq[SparkPlan] = IndexedSeq(left, right)
+    private def cleanupResources(): Unit = {
+      children.foreach(_.cleanupResources())
+    }

Review Comment:
   lazy val `children` is only used here. Maybe just inline 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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] beliefer commented on a diff in pull request #41884: [SPARK-44325][SQL] Use PartitionEvaluator API in SortMergeJoinExec

Posted by "beliefer (via GitHub)" <gi...@apache.org>.
beliefer commented on code in PR #41884:
URL: https://github.com/apache/spark/pull/41884#discussion_r1257090837


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,303 @@
+/*
+ * 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.{PartitionEvaluator, PartitionEvaluatorFactory}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, Predicate, Projection, RowOrdering, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.plans.{ExistenceJoin, FullOuter, InnerLike, JoinType, LeftAnti, LeftOuter, LeftSemi, RightOuter}
+import org.apache.spark.sql.execution.{ExternalAppendOnlyUnsafeRowArray, RowIterator}
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+class SortMergeJoinEvaluatorFactory(
+    leftKeys: Seq[Expression],
+    rightKeys: Seq[Expression],
+    joinType: JoinType,
+    condition: Option[Expression],
+    leftOutput: Seq[Attribute],
+    rightOutput: Seq[Attribute],
+    output: Seq[Attribute],
+    inMemoryThreshold: Int,
+    spillThreshold: Int,
+    numOutputRows: SQLMetric,
+    spillSize: SQLMetric,
+    cleanupResources: () => Unit,

Review Comment:
   lambda still exists here.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] cloud-fan commented on pull request #41884: [SPARK-44325][SQL] Use PartitionEvaluator API in SortMergeJoinExec

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on PR #41884:
URL: https://github.com/apache/spark/pull/41884#issuecomment-1629939029

   @viirya I think the benefit is that, we make it more clear what gets serialized and sent to the executor side.


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] cloud-fan commented on a diff in pull request #41884: [SPARK-44325][SQL] Use PartitionEvaluator API in SortMergeJoinExec

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #41884:
URL: https://github.com/apache/spark/pull/41884#discussion_r1277106244


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinExec.scala:
##########
@@ -128,249 +122,27 @@ case class SortMergeJoinExec(
     val spillSize = longMetric("spillSize")
     val spillThreshold = getSpillThreshold
     val inMemoryThreshold = getInMemoryThreshold
-    left.execute().zipPartitions(right.execute()) { (leftIter, rightIter) =>
-      val boundCondition: (InternalRow) => Boolean = {
-        condition.map { cond =>
-          Predicate.create(cond, left.output ++ right.output).eval _
-        }.getOrElse {
-          (r: InternalRow) => true
-        }
-      }
-
-      // An ordering that can be used to compare keys from both sides.
-      val keyOrdering = RowOrdering.createNaturalAscendingOrdering(leftKeys.map(_.dataType))
-      val resultProj: InternalRow => InternalRow = UnsafeProjection.create(output, output)
-
-      joinType match {
-        case _: InnerLike =>
-          new RowIterator {
-            private[this] var currentLeftRow: InternalRow = _
-            private[this] var currentRightMatches: ExternalAppendOnlyUnsafeRowArray = _
-            private[this] var rightMatchesIterator: Iterator[UnsafeRow] = null
-            private[this] val smjScanner = new SortMergeJoinScanner(
-              createLeftKeyGenerator(),
-              createRightKeyGenerator(),
-              keyOrdering,
-              RowIterator.fromScala(leftIter),
-              RowIterator.fromScala(rightIter),
-              inMemoryThreshold,
-              spillThreshold,
-              spillSize,
-              cleanupResources
-            )
-            private[this] val joinRow = new JoinedRow
-
-            if (smjScanner.findNextInnerJoinRows()) {
-              currentRightMatches = smjScanner.getBufferedMatches
-              currentLeftRow = smjScanner.getStreamedRow
-              rightMatchesIterator = currentRightMatches.generateIterator()
-            }
-
-            override def advanceNext(): Boolean = {
-              while (rightMatchesIterator != null) {
-                if (!rightMatchesIterator.hasNext) {
-                  if (smjScanner.findNextInnerJoinRows()) {
-                    currentRightMatches = smjScanner.getBufferedMatches
-                    currentLeftRow = smjScanner.getStreamedRow
-                    rightMatchesIterator = currentRightMatches.generateIterator()
-                  } else {
-                    currentRightMatches = null
-                    currentLeftRow = null
-                    rightMatchesIterator = null
-                    return false
-                  }
-                }
-                joinRow(currentLeftRow, rightMatchesIterator.next())
-                if (boundCondition(joinRow)) {
-                  numOutputRows += 1
-                  return true
-                }
-              }
-              false
-            }
-
-            override def getRow: InternalRow = resultProj(joinRow)
-          }.toScala
-
-        case LeftOuter =>
-          val smjScanner = new SortMergeJoinScanner(
-            streamedKeyGenerator = createLeftKeyGenerator(),
-            bufferedKeyGenerator = createRightKeyGenerator(),
-            keyOrdering,
-            streamedIter = RowIterator.fromScala(leftIter),
-            bufferedIter = RowIterator.fromScala(rightIter),
-            inMemoryThreshold,
-            spillThreshold,
-            spillSize,
-            cleanupResources
-          )
-          val rightNullRow = new GenericInternalRow(right.output.length)
-          new LeftOuterIterator(
-            smjScanner, rightNullRow, boundCondition, resultProj, numOutputRows).toScala
-
-        case RightOuter =>
-          val smjScanner = new SortMergeJoinScanner(
-            streamedKeyGenerator = createRightKeyGenerator(),
-            bufferedKeyGenerator = createLeftKeyGenerator(),
-            keyOrdering,
-            streamedIter = RowIterator.fromScala(rightIter),
-            bufferedIter = RowIterator.fromScala(leftIter),
-            inMemoryThreshold,
-            spillThreshold,
-            spillSize,
-            cleanupResources
-          )
-          val leftNullRow = new GenericInternalRow(left.output.length)
-          new RightOuterIterator(
-            smjScanner, leftNullRow, boundCondition, resultProj, numOutputRows).toScala
-
-        case FullOuter =>
-          val leftNullRow = new GenericInternalRow(left.output.length)
-          val rightNullRow = new GenericInternalRow(right.output.length)
-          val smjScanner = new SortMergeFullOuterJoinScanner(
-            leftKeyGenerator = createLeftKeyGenerator(),
-            rightKeyGenerator = createRightKeyGenerator(),
-            keyOrdering,
-            leftIter = RowIterator.fromScala(leftIter),
-            rightIter = RowIterator.fromScala(rightIter),
-            boundCondition,
-            leftNullRow,
-            rightNullRow)
-
-          new FullOuterIterator(
-            smjScanner,
-            resultProj,
-            numOutputRows).toScala
-
-        case LeftSemi =>
-          new RowIterator {
-            private[this] var currentLeftRow: InternalRow = _
-            private[this] val smjScanner = new SortMergeJoinScanner(
-              createLeftKeyGenerator(),
-              createRightKeyGenerator(),
-              keyOrdering,
-              RowIterator.fromScala(leftIter),
-              RowIterator.fromScala(rightIter),
-              inMemoryThreshold,
-              spillThreshold,
-              spillSize,
-              cleanupResources,
-              onlyBufferFirstMatchedRow
-            )
-            private[this] val joinRow = new JoinedRow
-
-            override def advanceNext(): Boolean = {
-              while (smjScanner.findNextInnerJoinRows()) {
-                val currentRightMatches = smjScanner.getBufferedMatches
-                currentLeftRow = smjScanner.getStreamedRow
-                if (currentRightMatches != null && currentRightMatches.length > 0) {
-                  val rightMatchesIterator = currentRightMatches.generateIterator()
-                  while (rightMatchesIterator.hasNext) {
-                    joinRow(currentLeftRow, rightMatchesIterator.next())
-                    if (boundCondition(joinRow)) {
-                      numOutputRows += 1
-                      return true
-                    }
-                  }
-                }
-              }
-              false
-            }
-
-            override def getRow: InternalRow = currentLeftRow
-          }.toScala
-
-        case LeftAnti =>
-          new RowIterator {
-            private[this] var currentLeftRow: InternalRow = _
-            private[this] val smjScanner = new SortMergeJoinScanner(
-              createLeftKeyGenerator(),
-              createRightKeyGenerator(),
-              keyOrdering,
-              RowIterator.fromScala(leftIter),
-              RowIterator.fromScala(rightIter),
-              inMemoryThreshold,
-              spillThreshold,
-              spillSize,
-              cleanupResources,
-              onlyBufferFirstMatchedRow
-            )
-            private[this] val joinRow = new JoinedRow
-
-            override def advanceNext(): Boolean = {
-              while (smjScanner.findNextOuterJoinRows()) {
-                currentLeftRow = smjScanner.getStreamedRow
-                val currentRightMatches = smjScanner.getBufferedMatches
-                if (currentRightMatches == null || currentRightMatches.length == 0) {
-                  numOutputRows += 1
-                  return true
-                }
-                var found = false
-                val rightMatchesIterator = currentRightMatches.generateIterator()
-                while (!found && rightMatchesIterator.hasNext) {
-                  joinRow(currentLeftRow, rightMatchesIterator.next())
-                  if (boundCondition(joinRow)) {
-                    found = true
-                  }
-                }
-                if (!found) {
-                  numOutputRows += 1
-                  return true
-                }
-              }
-              false
-            }
-
-            override def getRow: InternalRow = currentLeftRow
-          }.toScala
-
-        case j: ExistenceJoin =>
-          new RowIterator {
-            private[this] var currentLeftRow: InternalRow = _
-            private[this] val result: InternalRow = new GenericInternalRow(Array[Any](null))
-            private[this] val smjScanner = new SortMergeJoinScanner(
-              createLeftKeyGenerator(),
-              createRightKeyGenerator(),
-              keyOrdering,
-              RowIterator.fromScala(leftIter),
-              RowIterator.fromScala(rightIter),
-              inMemoryThreshold,
-              spillThreshold,
-              spillSize,
-              cleanupResources,
-              onlyBufferFirstMatchedRow
-            )
-            private[this] val joinRow = new JoinedRow
-
-            override def advanceNext(): Boolean = {
-              while (smjScanner.findNextOuterJoinRows()) {
-                currentLeftRow = smjScanner.getStreamedRow
-                val currentRightMatches = smjScanner.getBufferedMatches
-                var found = false
-                if (currentRightMatches != null && currentRightMatches.length > 0) {
-                  val rightMatchesIterator = currentRightMatches.generateIterator()
-                  while (!found && rightMatchesIterator.hasNext) {
-                    joinRow(currentLeftRow, rightMatchesIterator.next())
-                    if (boundCondition(joinRow)) {
-                      found = true
-                    }
-                  }
-                }
-                result.setBoolean(0, found)
-                numOutputRows += 1
-                return true
-              }
-              false
-            }
-
-            override def getRow: InternalRow = resultProj(joinRow(currentLeftRow, result))
-          }.toScala
-
-        case x =>
-          throw new IllegalArgumentException(
-            s"SortMergeJoin should not take $x as the JoinType")
+    val evaluatorFactory = new SortMergeJoinEvaluatorFactory(
+      leftKeys,
+      rightKeys,
+      joinType,
+      condition,
+      left,
+      right,
+      output,
+      inMemoryThreshold,
+      spillThreshold,
+      numOutputRows,
+      spillSize,
+      onlyBufferFirstMatchedRow
+    )
+    if (conf.usePartitionEvaluator) {
+      left.execute().zipPartitionsWithEvaluator(right.execute(), evaluatorFactory)
+    } else {
+      left.execute().zipPartitions(right.execute()) { (leftIter, rightIter) =>
+        val evaluator = evaluatorFactory.createEvaluator()
+        evaluator.eval(0, leftIter, rightIter)

Review Comment:
   can we use `TaskContext.getPartitionId`?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] yaooqinn commented on pull request #41884: [SPARK-44325][SQL] Use PartitionEvaluator API in SortMergeJoinExec

Posted by "yaooqinn (via GitHub)" <gi...@apache.org>.
yaooqinn commented on PR #41884:
URL: https://github.com/apache/spark/pull/41884#issuecomment-1631780007

   thanks @vinodkc and @cloud-fan @viirya @beliefer. merged to master


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] vinodkc commented on a diff in pull request #41884: [SPARK-44325][SQL] Use PartitionEvaluator API in SortMergeJoinExec

Posted by "vinodkc (via GitHub)" <gi...@apache.org>.
vinodkc commented on code in PR #41884:
URL: https://github.com/apache/spark/pull/41884#discussion_r1257606803


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,307 @@
+/*
+ * 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.{PartitionEvaluator, PartitionEvaluatorFactory}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, Predicate, Projection, RowOrdering, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.plans.{ExistenceJoin, FullOuter, InnerLike, JoinType, LeftAnti, LeftOuter, LeftSemi, RightOuter}
+import org.apache.spark.sql.execution.{ExternalAppendOnlyUnsafeRowArray, RowIterator, SparkPlan}
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+class SortMergeJoinEvaluatorFactory(
+    leftKeys: Seq[Expression],
+    rightKeys: Seq[Expression],
+    joinType: JoinType,
+    condition: Option[Expression],
+    left: SparkPlan,
+    right: SparkPlan,
+    output: Seq[Attribute],
+    inMemoryThreshold: Int,
+    spillThreshold: Int,
+    numOutputRows: SQLMetric,
+    spillSize: SQLMetric,
+    onlyBufferFirstMatchedRow: Boolean)
+    extends PartitionEvaluatorFactory[InternalRow, InternalRow] {
+  override def createEvaluator(): PartitionEvaluator[InternalRow, InternalRow] =
+    new SortMergeJoinEvaluator
+
+  private class SortMergeJoinEvaluator extends PartitionEvaluator[InternalRow, InternalRow] {
+
+    private lazy val children: Seq[SparkPlan] = IndexedSeq(left, right)
+    private def cleanupResources(): Unit = {
+      children.foreach(_.cleanupResources())
+    }

Review Comment:
   Done



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] vinodkc commented on a diff in pull request #41884: [SPARK-44325][SQL] Use PartitionEvaluator API in SortMergeJoinExec

Posted by "vinodkc (via GitHub)" <gi...@apache.org>.
vinodkc commented on code in PR #41884:
URL: https://github.com/apache/spark/pull/41884#discussion_r1258432194


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,306 @@
+/*
+ * 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.{PartitionEvaluator, PartitionEvaluatorFactory}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, Predicate, Projection, RowOrdering, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.plans.{ExistenceJoin, FullOuter, InnerLike, JoinType, LeftAnti, LeftOuter, LeftSemi, RightOuter}
+import org.apache.spark.sql.execution.{ExternalAppendOnlyUnsafeRowArray, RowIterator, SparkPlan}
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+class SortMergeJoinEvaluatorFactory(
+    leftKeys: Seq[Expression],
+    rightKeys: Seq[Expression],
+    joinType: JoinType,
+    condition: Option[Expression],
+    left: SparkPlan,
+    right: SparkPlan,
+    output: Seq[Attribute],
+    inMemoryThreshold: Int,
+    spillThreshold: Int,
+    numOutputRows: SQLMetric,
+    spillSize: SQLMetric,
+    onlyBufferFirstMatchedRow: Boolean)
+    extends PartitionEvaluatorFactory[InternalRow, InternalRow] {
+  override def createEvaluator(): PartitionEvaluator[InternalRow, InternalRow] =
+    new SortMergeJoinEvaluator
+
+  private class SortMergeJoinEvaluator extends PartitionEvaluator[InternalRow, InternalRow] {
+
+    private def cleanupResources(): Unit = {
+      IndexedSeq(left, right).foreach(_.cleanupResources())
+    }
+    private def createLeftKeyGenerator(): Projection =
+      UnsafeProjection.create(leftKeys, left.output)
+
+    private def createRightKeyGenerator(): Projection =
+      UnsafeProjection.create(rightKeys, right.output)
+
+    override def eval(
+        partitionIndex: Int,
+        inputs: Iterator[InternalRow]*): Iterator[InternalRow] = {
+      assert(inputs.length == 2)
+      val leftIter = inputs(0)
+      val rightIter = inputs(1)
+
+      val boundCondition: InternalRow => Boolean = {
+        condition
+          .map { cond =>
+            Predicate.create(cond, left.output ++ right.output).eval _
+          }
+          .getOrElse { (r: InternalRow) =>
+            true
+          }

Review Comment:
   Done



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] vinodkc commented on pull request #41884: [SPARK-44325][SQL] Use PartitionEvaluator API in SortMergeJoinExec

Posted by "vinodkc (via GitHub)" <gi...@apache.org>.
vinodkc commented on PR #41884:
URL: https://github.com/apache/spark/pull/41884#issuecomment-1625519632

   CC @cloud-fan @viirya @dongjoon-hyun @yaooqinn @beliefer @HyukjinKwon 


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] beliefer commented on pull request #41884: [SPARK-44325][SQL] Use PartitionEvaluator API in SortMergeJoinExec

Posted by "beliefer (via GitHub)" <gi...@apache.org>.
beliefer commented on PR #41884:
URL: https://github.com/apache/spark/pull/41884#issuecomment-1630315499

   LGTM+1


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] cloud-fan commented on a diff in pull request #41884: [SPARK-44325][SQL] Use PartitionEvaluator API in SortMergeJoinExec

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #41884:
URL: https://github.com/apache/spark/pull/41884#discussion_r1277106792


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/SortMergeJoinExec.scala:
##########
@@ -128,249 +122,27 @@ case class SortMergeJoinExec(
     val spillSize = longMetric("spillSize")
     val spillThreshold = getSpillThreshold
     val inMemoryThreshold = getInMemoryThreshold
-    left.execute().zipPartitions(right.execute()) { (leftIter, rightIter) =>
-      val boundCondition: (InternalRow) => Boolean = {
-        condition.map { cond =>
-          Predicate.create(cond, left.output ++ right.output).eval _
-        }.getOrElse {
-          (r: InternalRow) => true
-        }
-      }
-
-      // An ordering that can be used to compare keys from both sides.
-      val keyOrdering = RowOrdering.createNaturalAscendingOrdering(leftKeys.map(_.dataType))
-      val resultProj: InternalRow => InternalRow = UnsafeProjection.create(output, output)
-
-      joinType match {
-        case _: InnerLike =>
-          new RowIterator {
-            private[this] var currentLeftRow: InternalRow = _
-            private[this] var currentRightMatches: ExternalAppendOnlyUnsafeRowArray = _
-            private[this] var rightMatchesIterator: Iterator[UnsafeRow] = null
-            private[this] val smjScanner = new SortMergeJoinScanner(
-              createLeftKeyGenerator(),
-              createRightKeyGenerator(),
-              keyOrdering,
-              RowIterator.fromScala(leftIter),
-              RowIterator.fromScala(rightIter),
-              inMemoryThreshold,
-              spillThreshold,
-              spillSize,
-              cleanupResources
-            )
-            private[this] val joinRow = new JoinedRow
-
-            if (smjScanner.findNextInnerJoinRows()) {
-              currentRightMatches = smjScanner.getBufferedMatches
-              currentLeftRow = smjScanner.getStreamedRow
-              rightMatchesIterator = currentRightMatches.generateIterator()
-            }
-
-            override def advanceNext(): Boolean = {
-              while (rightMatchesIterator != null) {
-                if (!rightMatchesIterator.hasNext) {
-                  if (smjScanner.findNextInnerJoinRows()) {
-                    currentRightMatches = smjScanner.getBufferedMatches
-                    currentLeftRow = smjScanner.getStreamedRow
-                    rightMatchesIterator = currentRightMatches.generateIterator()
-                  } else {
-                    currentRightMatches = null
-                    currentLeftRow = null
-                    rightMatchesIterator = null
-                    return false
-                  }
-                }
-                joinRow(currentLeftRow, rightMatchesIterator.next())
-                if (boundCondition(joinRow)) {
-                  numOutputRows += 1
-                  return true
-                }
-              }
-              false
-            }
-
-            override def getRow: InternalRow = resultProj(joinRow)
-          }.toScala
-
-        case LeftOuter =>
-          val smjScanner = new SortMergeJoinScanner(
-            streamedKeyGenerator = createLeftKeyGenerator(),
-            bufferedKeyGenerator = createRightKeyGenerator(),
-            keyOrdering,
-            streamedIter = RowIterator.fromScala(leftIter),
-            bufferedIter = RowIterator.fromScala(rightIter),
-            inMemoryThreshold,
-            spillThreshold,
-            spillSize,
-            cleanupResources
-          )
-          val rightNullRow = new GenericInternalRow(right.output.length)
-          new LeftOuterIterator(
-            smjScanner, rightNullRow, boundCondition, resultProj, numOutputRows).toScala
-
-        case RightOuter =>
-          val smjScanner = new SortMergeJoinScanner(
-            streamedKeyGenerator = createRightKeyGenerator(),
-            bufferedKeyGenerator = createLeftKeyGenerator(),
-            keyOrdering,
-            streamedIter = RowIterator.fromScala(rightIter),
-            bufferedIter = RowIterator.fromScala(leftIter),
-            inMemoryThreshold,
-            spillThreshold,
-            spillSize,
-            cleanupResources
-          )
-          val leftNullRow = new GenericInternalRow(left.output.length)
-          new RightOuterIterator(
-            smjScanner, leftNullRow, boundCondition, resultProj, numOutputRows).toScala
-
-        case FullOuter =>
-          val leftNullRow = new GenericInternalRow(left.output.length)
-          val rightNullRow = new GenericInternalRow(right.output.length)
-          val smjScanner = new SortMergeFullOuterJoinScanner(
-            leftKeyGenerator = createLeftKeyGenerator(),
-            rightKeyGenerator = createRightKeyGenerator(),
-            keyOrdering,
-            leftIter = RowIterator.fromScala(leftIter),
-            rightIter = RowIterator.fromScala(rightIter),
-            boundCondition,
-            leftNullRow,
-            rightNullRow)
-
-          new FullOuterIterator(
-            smjScanner,
-            resultProj,
-            numOutputRows).toScala
-
-        case LeftSemi =>
-          new RowIterator {
-            private[this] var currentLeftRow: InternalRow = _
-            private[this] val smjScanner = new SortMergeJoinScanner(
-              createLeftKeyGenerator(),
-              createRightKeyGenerator(),
-              keyOrdering,
-              RowIterator.fromScala(leftIter),
-              RowIterator.fromScala(rightIter),
-              inMemoryThreshold,
-              spillThreshold,
-              spillSize,
-              cleanupResources,
-              onlyBufferFirstMatchedRow
-            )
-            private[this] val joinRow = new JoinedRow
-
-            override def advanceNext(): Boolean = {
-              while (smjScanner.findNextInnerJoinRows()) {
-                val currentRightMatches = smjScanner.getBufferedMatches
-                currentLeftRow = smjScanner.getStreamedRow
-                if (currentRightMatches != null && currentRightMatches.length > 0) {
-                  val rightMatchesIterator = currentRightMatches.generateIterator()
-                  while (rightMatchesIterator.hasNext) {
-                    joinRow(currentLeftRow, rightMatchesIterator.next())
-                    if (boundCondition(joinRow)) {
-                      numOutputRows += 1
-                      return true
-                    }
-                  }
-                }
-              }
-              false
-            }
-
-            override def getRow: InternalRow = currentLeftRow
-          }.toScala
-
-        case LeftAnti =>
-          new RowIterator {
-            private[this] var currentLeftRow: InternalRow = _
-            private[this] val smjScanner = new SortMergeJoinScanner(
-              createLeftKeyGenerator(),
-              createRightKeyGenerator(),
-              keyOrdering,
-              RowIterator.fromScala(leftIter),
-              RowIterator.fromScala(rightIter),
-              inMemoryThreshold,
-              spillThreshold,
-              spillSize,
-              cleanupResources,
-              onlyBufferFirstMatchedRow
-            )
-            private[this] val joinRow = new JoinedRow
-
-            override def advanceNext(): Boolean = {
-              while (smjScanner.findNextOuterJoinRows()) {
-                currentLeftRow = smjScanner.getStreamedRow
-                val currentRightMatches = smjScanner.getBufferedMatches
-                if (currentRightMatches == null || currentRightMatches.length == 0) {
-                  numOutputRows += 1
-                  return true
-                }
-                var found = false
-                val rightMatchesIterator = currentRightMatches.generateIterator()
-                while (!found && rightMatchesIterator.hasNext) {
-                  joinRow(currentLeftRow, rightMatchesIterator.next())
-                  if (boundCondition(joinRow)) {
-                    found = true
-                  }
-                }
-                if (!found) {
-                  numOutputRows += 1
-                  return true
-                }
-              }
-              false
-            }
-
-            override def getRow: InternalRow = currentLeftRow
-          }.toScala
-
-        case j: ExistenceJoin =>
-          new RowIterator {
-            private[this] var currentLeftRow: InternalRow = _
-            private[this] val result: InternalRow = new GenericInternalRow(Array[Any](null))
-            private[this] val smjScanner = new SortMergeJoinScanner(
-              createLeftKeyGenerator(),
-              createRightKeyGenerator(),
-              keyOrdering,
-              RowIterator.fromScala(leftIter),
-              RowIterator.fromScala(rightIter),
-              inMemoryThreshold,
-              spillThreshold,
-              spillSize,
-              cleanupResources,
-              onlyBufferFirstMatchedRow
-            )
-            private[this] val joinRow = new JoinedRow
-
-            override def advanceNext(): Boolean = {
-              while (smjScanner.findNextOuterJoinRows()) {
-                currentLeftRow = smjScanner.getStreamedRow
-                val currentRightMatches = smjScanner.getBufferedMatches
-                var found = false
-                if (currentRightMatches != null && currentRightMatches.length > 0) {
-                  val rightMatchesIterator = currentRightMatches.generateIterator()
-                  while (!found && rightMatchesIterator.hasNext) {
-                    joinRow(currentLeftRow, rightMatchesIterator.next())
-                    if (boundCondition(joinRow)) {
-                      found = true
-                    }
-                  }
-                }
-                result.setBoolean(0, found)
-                numOutputRows += 1
-                return true
-              }
-              false
-            }
-
-            override def getRow: InternalRow = resultProj(joinRow(currentLeftRow, result))
-          }.toScala
-
-        case x =>
-          throw new IllegalArgumentException(
-            s"SortMergeJoin should not take $x as the JoinType")
+    val evaluatorFactory = new SortMergeJoinEvaluatorFactory(
+      leftKeys,
+      rightKeys,
+      joinType,
+      condition,
+      left,
+      right,
+      output,
+      inMemoryThreshold,
+      spillThreshold,
+      numOutputRows,
+      spillSize,
+      onlyBufferFirstMatchedRow
+    )
+    if (conf.usePartitionEvaluator) {
+      left.execute().zipPartitionsWithEvaluator(right.execute(), evaluatorFactory)
+    } else {
+      left.execute().zipPartitions(right.execute()) { (leftIter, rightIter) =>
+        val evaluator = evaluatorFactory.createEvaluator()
+        evaluator.eval(0, leftIter, rightIter)

Review Comment:
   nvm, it's different from index. Maybe we should just leave a note here about why we always use `0`.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org