viirya commented on code in PR #60475:
URL: https://github.com/apache/spark/pull/60475#discussion_r4575378204


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala:
##########
@@ -61,58 +62,38 @@ case class SortExec(
     "peakMemory" -> SQLMetrics.createSizeMetric(sparkContext, "peak memory"),
     "spillSize" -> SQLMetrics.createSizeMetric(sparkContext, "spill size"))
 
-  // WARNING: This is a shared mutable var on the SortExec instance. Do not 
access it from
-  // multiple threads concurrently - Spark operators do not guarantee 
thread-safety and one
-  // task's sorter could overwrite another's, causing a race condition.
-  private[sql] var rowSorter: UnsafeExternalRowSorter = _
-
   /**
-   * This method gets invoked only once for each SortExec instance to 
initialize an
-   * UnsafeExternalRowSorter, both `plan.execute` and code generation are 
using it.
-   * In the code generation code path, we need to call this function outside 
the class so we
-   * should make it public.
+   * Creates the sorter of this node in a task and keeps it until it is 
released. Everything that
+   * runs in a task captures this holder rather than the node: the generated 
code, the closure of
+   * [[doExecute]], operators above that release the sorter early (through
+   * [[taskResourceCleaner]]) and the concurrent output writers of 
`FileFormatWriter`. So the node
+   * and its child subtree are not serialized into every task for the sorter, 
and in a task they
+   * all share the copy of the holder deserialized from the task binary.
+   *
+   * It is transient, so that a node that is still serialized into a task by 
another operator
+   * does not carry it. A deserialized node therefore has a fresh holder that 
nothing else uses:
+   * code that runs in a task must not create or release the sorter through 
the node.
    */
-  def createSorter(): UnsafeExternalRowSorter = {
-    val ordering = RowOrdering.create(sortOrder, output)
-
-    // The comparator for comparing prefix
-    val boundSortExpression = BindReferences.bindReference(sortOrder.head, 
output)
-    val prefixComparator = 
SortPrefixUtils.getPrefixComparator(boundSortExpression)
-
-    val canUseRadixSort = enableRadixSort && sortOrder.length == 1 &&
-      SortPrefixUtils.canSortFullyWithPrefix(boundSortExpression)
-
-    // The generator for prefix
-    val prefixExpr = SortPrefix(boundSortExpression)
-    val prefixProjection = UnsafeProjection.create(Seq(prefixExpr))
-    val prefixComputer = new UnsafeExternalRowSorter.PrefixComputer {
-      private val result = new UnsafeExternalRowSorter.PrefixComputer.Prefix
-      override def computePrefix(row: InternalRow):
-          UnsafeExternalRowSorter.PrefixComputer.Prefix = {
-        val prefix = prefixProjection.apply(row)
-        result.isNull = prefix.isNullAt(0)
-        result.value = if (result.isNull) prefixExpr.nullValue else 
prefix.getLong(0)
-        result
-      }
-    }
+  @transient private[sql] lazy val sorterHolder =
+    new SortExecSorterHolder(sortOrder, output, enableRadixSort, 
testSpillFrequency)
 
-    val pageSize = SparkEnv.get.memoryManager.pageSizeBytes
-    rowSorter = UnsafeExternalRowSorter.create(
-      schema, ordering, prefixComparator, prefixComputer, pageSize, 
canUseRadixSort)
+  /**
+   * Creates a sorter for this node on the driver side, e.g. for a test. Code 
that runs in a task
+   * must use [[sorterHolder]] captured on the driver instead, see there.
+   */
+  def createSorter(): UnsafeExternalRowSorter = sorterHolder.createSorter()

Review Comment:
   Removed. Nothing in Spark calls it any more, and as you say a caller outside 
Spark is better off with a compile error that points it to `sorterHolder` than 
with a method that silently creates a sorter on the deserialized node's own 
holder.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala:
##########
@@ -191,15 +172,11 @@ case class SortExec(
   }
 
   /**
-   * In SortExec, we overwrite cleanupResources to close 
UnsafeExternalRowSorter.
-   * There's possible for rowSorter to be null here, for example, in the 
scenario of empty iterator
-   * in the current task, the downstream physical node (like 
SortMergeJoinExec) will trigger
-   * cleanupResources before rowSorter is initialized in createSorter.
+   * In SortExec, we overwrite cleanupResources to close 
UnsafeExternalRowSorter. In a task, the
+   * operators above (like SortMergeJoinExec) close it through 
[[taskResourceCleaner]] instead.
    */
   override protected[sql] def cleanupResources(): Unit = {

Review Comment:
   Dropped the override. In a task it reached only the deserialized node's 
fresh holder, and on the driver the holder never has a sorter, so it released 
nothing on either side.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/TaskResourceCleaner.scala:
##########
@@ -0,0 +1,81 @@
+/*
+ * 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
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.codegen.CodegenContext
+import org.apache.spark.sql.execution.exchange.Exchange
+
+/**
+ * Releases the resources that a physical operator holds in a task, without 
referencing the
+ * operator. See [[SparkPlan.taskResourceCleaner]].
+ *
+ * The cleaner is per-task mutable state: it is created on the driver, before 
the task binary is
+ * serialized, and every task deserializes its own copy. Everything in a task 
that creates or
+ * releases the resources must reach them through that same copy, so it must 
capture the cleaner
+ * itself rather than the operator: a deserialized operator does not carry its 
cleaner.
+ */
+private[sql] trait TaskResourceCleaner extends Serializable {
+  def cleanupResources(): Unit
+}
+
+private[sql] object TaskResourceCleaner {
+
+  /**
+   * The cleaners of the operators that run in the same task as `plan`: those 
in its subtree, but
+   * not beyond an [[Exchange]] (or a leaf, such as a query stage). An 
operator that releases the
+   * resources of its children early in a task, such as a sort merge join, 
releases these.
+   */
+  def inStage(plan: SparkPlan): Array[TaskResourceCleaner] = {
+    val cleaners = mutable.ArrayBuffer[TaskResourceCleaner]()
+    def visit(p: SparkPlan): Unit = p match {
+      case _: Exchange =>

Review Comment:
   Good catch. Updated the `inStage` scaladoc to say that the set can include 
operators of other stages, below an operator that starts a new stage in its own 
`doExecute` such as `TakeOrderedAndProjectExec`, and the `TaskResourceCleaner` 
scaladoc now states the contract that `cleanupResources()` must do nothing in a 
task that did not use the cleaner.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/TaskResourceCleaner.scala:
##########
@@ -0,0 +1,81 @@
+/*
+ * 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
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.codegen.CodegenContext
+import org.apache.spark.sql.execution.exchange.Exchange
+
+/**
+ * Releases the resources that a physical operator holds in a task, without 
referencing the
+ * operator. See [[SparkPlan.taskResourceCleaner]].
+ *
+ * The cleaner is per-task mutable state: it is created on the driver, before 
the task binary is
+ * serialized, and every task deserializes its own copy. Everything in a task 
that creates or
+ * releases the resources must reach them through that same copy, so it must 
capture the cleaner
+ * itself rather than the operator: a deserialized operator does not carry its 
cleaner.
+ */
+private[sql] trait TaskResourceCleaner extends Serializable {
+  def cleanupResources(): Unit
+}
+
+private[sql] object TaskResourceCleaner {
+
+  /**
+   * The cleaners of the operators that run in the same task as `plan`: those 
in its subtree, but
+   * not beyond an [[Exchange]] (or a leaf, such as a query stage). An 
operator that releases the
+   * resources of its children early in a task, such as a sort merge join, 
releases these.
+   */
+  def inStage(plan: SparkPlan): Array[TaskResourceCleaner] = {
+    val cleaners = mutable.ArrayBuffer[TaskResourceCleaner]()
+    def visit(p: SparkPlan): Unit = p match {
+      case _: Exchange =>
+      case other =>
+        cleaners ++= other.taskResourceCleaner
+        other.children.foreach(visit)
+    }
+    plan.children.foreach(visit)
+    cleaners.toArray
+  }
+
+  /** Releases the resources of `cleaners`. */
+  def cleanupAll(cleaners: Array[TaskResourceCleaner]): Unit = {

Review Comment:
   Inlined.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -639,6 +641,112 @@ class WholeStageCodegenSuite extends SharedSparkSession
     checkAnswer(twoJoinsDF, Seq(Row(6), Row(7), Row(8), Row(9)))
   }
 
+  test("SPARK-61666: Sort and sort merge joins do not serialize plan nodes 
into tasks") {
+    // The RDD that a codegen stage, or an operator outside codegen, adds on 
top of its input RDDs
+    // is serialized into every task binary, with the references of the 
generated code. A plan
+    // node written with it would drag its whole child subtree along, so it 
must not reference one.
+    def serializedPlanNodes(rdd: RDD[_], inputs: Seq[RDD[_]]): Seq[String] = {
+      val planNodes = mutable.ArrayBuffer[String]()
+      val out = new ObjectOutputStream(new ByteArrayOutputStream()) {
+        enableReplaceObject(true)
+        override def replaceObject(obj: AnyRef): AnyRef = obj match {
+          // Cut the lineage below: the input RDDs belong to other operators 
or stages.
+          case r: RDD[_] if inputs.exists(_ eq r) => "input RDD"
+          case p: SparkPlan =>
+            planNodes += p.nodeName
+            p
+          case _ => obj
+        }
+      }
+      out.writeObject(rdd)
+      out.close()
+      planNodes.toSeq
+    }
+    def inStage(plan: SparkPlan): Seq[SparkPlan] = plan match {
+      case _: InputAdapter => Nil
+      case other => other +: other.children.flatMap(inStage)
+    }
+    // Checks the codegen stages and the operators outside codegen that run a 
sort or a sort merge
+    // join. `expectedNodes` are the node names that must run, in codegen or 
not.
+    def checkPlans(df: => DataFrame, expectedNodes: Set[String]): Unit = {
+      val expected = withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> 
"false") {
+        df.collect().toSeq
+      }
+      Seq(false, true).foreach { usePartitionEvaluator =>
+        withSQLConf(SQLConf.USE_PARTITION_EVALUATOR.key -> 
usePartitionEvaluator.toString) {
+          val result = df
+          checkAnswer(result, expected)
+          // The RDDs are cached by the plans, so these are the ones the query 
ran.
+          val plan = result.queryExecution.executedPlan
+          // All the nodes of the plan, including those in adaptive query 
stages.
+          def allNodes(p: SparkPlan): Seq[SparkPlan] = p +: (p match {
+            case a: AdaptiveSparkPlanExec => allNodes(a.executedPlan)
+            case q: QueryStageExec => allNodes(q.plan)
+            case other => other.children.flatMap(allNodes)
+          })
+          val nodes = allNodes(plan)
+          val stages = nodes.collect { case s: WholeStageCodegenExec => s }
+          val generated = stages.flatMap(s => inStage(s.child))
+          val targets = stages.filter(s => inStage(s.child).exists(
+              p => expectedNodes.contains(p.nodeName))).map { s =>
+            (s.treeString, s.execute(), 
s.child.asInstanceOf[CodegenSupport].inputRDDs())
+          } ++ nodes.collect {
+            case p if expectedNodes.contains(p.nodeName) && 
!generated.exists(_ eq p) =>
+              (p.treeString, p.execute(), p.children.map(_.execute()))
+          }
+          assert(nodes.map(_.nodeName).toSet.intersect(expectedNodes) == 
expectedNodes,
+            plan.treeString)
+          targets.foreach { case (treeString, rdd, inputs) =>
+            val planNodes = serializedPlanNodes(rdd, inputs)
+            assert(planNodes.isEmpty, s"$planNodes referenced by\n$treeString")
+          }
+        }
+      }
+    }
+
+    val df1 = spark.range(0, 100, 1, 2).select(($"id" % 10).as("k1"), 
$"id".as("v1"))
+    val df2 = spark.range(0, 30, 1, 2).select(($"id" % 7).as("k2"), 
$"id".as("v2"))
+    withTempView("t1", "t2") {
+      df1.createOrReplaceTempView("t1")
+      df2.createOrReplaceTempView("t2")
+      // Fully generated; generated sorts under an interpreted join (the join 
output has more fields
+      // than `maxFields`); and no codegen at all.
+      Seq(
+        Seq.empty[(String, String)],
+        Seq(SQLConf.WHOLESTAGE_MAX_NUM_FIELDS.key -> "3"),
+        Seq(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "false")).foreach { 
codegenConfs =>
+        Seq(false, true).foreach { aqe =>
+          withSQLConf(codegenConfs ++ Seq(
+              SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe.toString,
+              SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1"): _*) {
+            checkPlans(df1.orderBy($"v1".desc), Set("Sort"))
+            val joinTypes = Seq("inner", "left_outer", "right_outer", 
"left_semi", "left_anti")
+            joinTypes.foreach { joinType =>
+              checkPlans(
+                df1.join(df2.hint("SHUFFLE_MERGE"), $"k1" === $"k2", joinType),
+                Set("Sort", "SortMergeJoin"))
+            }
+            // An existence join.
+            checkPlans(
+              spark.sql("SELECT * FROM t1 WHERE EXISTS (SELECT 1 FROM t2 WHERE 
k2 = k1) OR v1 < 3"),
+              Set("Sort", "SortMergeJoin"))
+          }
+        }
+      }
+    }
+
+    withSQLConf(SQLConf.SORT_MERGE_AS_OF_JOIN_ENABLED.key -> "true") {

Review Comment:
   The as-of join block now runs with AQE on and off, and its comment says that 
only the generated as-of join is covered, since the interpreted one still 
captures the join node in its closure to build its scanner. I also fixed the PR 
description accordingly.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -639,6 +641,112 @@ class WholeStageCodegenSuite extends SharedSparkSession
     checkAnswer(twoJoinsDF, Seq(Row(6), Row(7), Row(8), Row(9)))
   }
 
+  test("SPARK-61666: Sort and sort merge joins do not serialize plan nodes 
into tasks") {
+    // The RDD that a codegen stage, or an operator outside codegen, adds on 
top of its input RDDs
+    // is serialized into every task binary, with the references of the 
generated code. A plan
+    // node written with it would drag its whole child subtree along, so it 
must not reference one.
+    def serializedPlanNodes(rdd: RDD[_], inputs: Seq[RDD[_]]): Seq[String] = {
+      val planNodes = mutable.ArrayBuffer[String]()
+      val out = new ObjectOutputStream(new ByteArrayOutputStream()) {
+        enableReplaceObject(true)
+        override def replaceObject(obj: AnyRef): AnyRef = obj match {
+          // Cut the lineage below: the input RDDs belong to other operators 
or stages.
+          case r: RDD[_] if inputs.exists(_ eq r) => "input RDD"
+          case p: SparkPlan =>
+            planNodes += p.nodeName
+            p
+          case _ => obj
+        }
+      }
+      out.writeObject(rdd)
+      out.close()
+      planNodes.toSeq
+    }
+    def inStage(plan: SparkPlan): Seq[SparkPlan] = plan match {
+      case _: InputAdapter => Nil
+      case other => other +: other.children.flatMap(inStage)
+    }
+    // Checks the codegen stages and the operators outside codegen that run a 
sort or a sort merge
+    // join. `expectedNodes` are the node names that must run, in codegen or 
not.
+    def checkPlans(df: => DataFrame, expectedNodes: Set[String]): Unit = {
+      val expected = withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> 
"false") {
+        df.collect().toSeq
+      }
+      Seq(false, true).foreach { usePartitionEvaluator =>
+        withSQLConf(SQLConf.USE_PARTITION_EVALUATOR.key -> 
usePartitionEvaluator.toString) {
+          val result = df
+          checkAnswer(result, expected)
+          // The RDDs are cached by the plans, so these are the ones the query 
ran.
+          val plan = result.queryExecution.executedPlan
+          // All the nodes of the plan, including those in adaptive query 
stages.
+          def allNodes(p: SparkPlan): Seq[SparkPlan] = p +: (p match {
+            case a: AdaptiveSparkPlanExec => allNodes(a.executedPlan)
+            case q: QueryStageExec => allNodes(q.plan)
+            case other => other.children.flatMap(allNodes)
+          })
+          val nodes = allNodes(plan)
+          val stages = nodes.collect { case s: WholeStageCodegenExec => s }
+          val generated = stages.flatMap(s => inStage(s.child))
+          val targets = stages.filter(s => inStage(s.child).exists(
+              p => expectedNodes.contains(p.nodeName))).map { s =>
+            (s.treeString, s.execute(), 
s.child.asInstanceOf[CodegenSupport].inputRDDs())
+          } ++ nodes.collect {
+            case p if expectedNodes.contains(p.nodeName) && 
!generated.exists(_ eq p) =>
+              (p.treeString, p.execute(), p.children.map(_.execute()))
+          }
+          assert(nodes.map(_.nodeName).toSet.intersect(expectedNodes) == 
expectedNodes,
+            plan.treeString)
+          targets.foreach { case (treeString, rdd, inputs) =>
+            val planNodes = serializedPlanNodes(rdd, inputs)
+            assert(planNodes.isEmpty, s"$planNodes referenced by\n$treeString")
+          }
+        }
+      }
+    }
+
+    val df1 = spark.range(0, 100, 1, 2).select(($"id" % 10).as("k1"), 
$"id".as("v1"))
+    val df2 = spark.range(0, 30, 1, 2).select(($"id" % 7).as("k2"), 
$"id".as("v2"))
+    withTempView("t1", "t2") {
+      df1.createOrReplaceTempView("t1")
+      df2.createOrReplaceTempView("t2")
+      // Fully generated; generated sorts under an interpreted join (the join 
output has more fields
+      // than `maxFields`); and no codegen at all.
+      Seq(
+        Seq.empty[(String, String)],
+        Seq(SQLConf.WHOLESTAGE_MAX_NUM_FIELDS.key -> "3"),
+        Seq(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> "false")).foreach { 
codegenConfs =>
+        Seq(false, true).foreach { aqe =>
+          withSQLConf(codegenConfs ++ Seq(
+              SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> aqe.toString,
+              SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1"): _*) {
+            checkPlans(df1.orderBy($"v1".desc), Set("Sort"))
+            val joinTypes = Seq("inner", "left_outer", "right_outer", 
"left_semi", "left_anti")

Review Comment:
   Added `full_outer`; it runs generated in the default mode and interpreted 
under `maxFields = 3`.



##########
sql/core/src/test/scala/org/apache/spark/sql/JoinSuite.scala:
##########
@@ -1189,6 +1190,75 @@ class JoinSuite extends SharedSparkSession with 
AdaptiveSparkPlanHelper
     }
   }
 
+  test("SPARK-61666: sort merge joins release the sorters of their children 
early") {
+    // A join that stops reading one side before its end releases that side's 
sorter once it has
+    // produced its last row, instead of holding its memory until the task 
completes. Read the
+    // join to its end in a task, and check that the task holds no execution 
memory afterwards.
+    def memoryAfterJoin(df: DataFrame): Seq[Long] = {
+      df.queryExecution.toRdd.mapPartitions { iter =>
+        iter.foreach(_ => ())
+        
Iterator(TaskContext.get().taskMemoryManager().getMemoryConsumptionForThisTask)
+      }.collect().toSeq
+    }
+    def isGenerated(df: DataFrame, nodeName: String): Boolean = {
+      collect(df.queryExecution.executedPlan) {
+        case s: WholeStageCodegenExec => s.collect { case p if p.nodeName == 
nodeName => p }
+      }.flatten.nonEmpty
+    }
+
+    // The join reads `small` to its end, but not `big`.
+    val small = spark.range(0, 100).select($"id".as("k1"))
+    val big = spark.range(0, 1000).select($"id".as("k2"))
+    withTempView("small", "big") {
+      small.createOrReplaceTempView("small")
+      big.createOrReplaceTempView("big")
+      // Fully generated; generated sorts under an interpreted join (the join 
output has more
+      // fields than `maxFields`); and no codegen at all.
+      Seq(
+        (Seq.empty[(String, String)], true, true),
+        (Seq(SQLConf.WHOLESTAGE_MAX_NUM_FIELDS.key -> "1"), true, false),

Review Comment:
   Right. The comments in both tests now say that the `maxFields` mode leaves 
the semi and anti joins generated, since their output is their left side's.



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