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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala:
##########
@@ -61,50 +65,23 @@ 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 = _
+  /**
+   * Creates the sorter of this node and keeps it for [[cleanupResources]]. 
The generated code
+   * references this holder instead of the node, so that the node and its 
child subtree are not
+   * serialized into every task. The node keeps the same holder through 
serialization, so the
+   * sorter the generated code creates is the one that [[cleanupResources]] of 
this node (e.g.
+   * reached through the interpreted `SortMergeJoinExec`) closes, as long as 
both are
+   * deserialized from the same task binary.
+   */
+  private[sql] lazy val sorterHolder =
+    new SortExecSorterHolder(sortOrder, output, enableRadixSort, 
testSpillFrequency)
 
   /**
    * 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.
+   * UnsafeExternalRowSorter. The generated code calls 
[[SortExecSorterHolder.createSorter]]
+   * directly.
    */
-  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
-      }
-    }
-
-    val pageSize = SparkEnv.get.memoryManager.pageSizeBytes
-    rowSorter = UnsafeExternalRowSorter.create(
-      schema, ordering, prefixComparator, prefixComputer, pageSize, 
canUseRadixSort)
-
-    if (testSpillFrequency > 0) {
-      rowSorter.setTestSpillFrequency(testSpillFrequency)
-    }
-    rowSorter
-  }
+  def createSorter(): UnsafeExternalRowSorter = sorterHolder.createSorter()

Review Comment:
   Done: `SortExec.doExecute`, `SortMergeJoinExec.doExecute` (the evaluator 
factory now takes the children's output and the cleaners instead of the child 
plans) and the concurrent output writer capture the holder instead of the node. 
The serialization test covers the interpreted sort and join.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -639,6 +641,80 @@ class WholeStageCodegenSuite extends SharedSparkSession
     checkAnswer(twoJoinsDF, Seq(Row(6), Row(7), Row(8), Row(9)))
   }
 
+  test("SPARK-61666: Sort and sort merge join codegen do not serialize plan 
nodes") {
+    // The RDD a codegen stage adds on top of its input RDDs, with the 
references of its
+    // generated code, is serialized into every task binary. A plan node 
written with it would drag
+    // its whole child subtree along, so the stage must not reference one.
+    def serializedPlanNodes(stage: WholeStageCodegenExec): Seq[String] = {
+      val rdd = stage.execute()
+      // The input RDDs are cached by the plans below, so these are the ones 
`rdd` reads.
+      val inputs = stage.child.asInstanceOf[CodegenSupport].inputRDDs()
+      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 stage: the input RDDs belong to other 
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
+    }
+    // The codegen stages that run a sort or a sort merge join themselves.
+    def checkStages(df: => DataFrame, expectedNodes: Set[String]): Unit = {
+      def inStage(plan: SparkPlan): Seq[SparkPlan] = plan match {
+        case _: InputAdapter => Nil
+        case other => other +: other.children.flatMap(inStage)
+      }
+      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
+          val stages = result.queryExecution.executedPlan.collect {
+            case stage: WholeStageCodegenExec
+                if inStage(stage.child).exists(p => 
expectedNodes.contains(p.nodeName)) =>
+              stage -> 
inStage(stage.child).map(_.nodeName).filter(expectedNodes.contains)
+          }
+          assert(stages.flatMap(_._2).toSet == expectedNodes)
+          stages.foreach { case (stage, _) =>
+            val planNodes = serializedPlanNodes(stage)
+            assert(planNodes.isEmpty, s"$planNodes referenced 
by\n${stage.treeString}")
+          }
+          checkAnswer(result, expected)
+        }
+      }
+    }
+
+    withSQLConf(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1") {
+      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"))
+      checkStages(df1.orderBy($"v1".desc), Set("Sort"))
+      Seq("inner", "left_outer", "right_outer", "left_semi", 
"left_anti").foreach { joinType =>

Review Comment:
   Covered by the new `JoinSuite` test (generated sorts under an interpreted 
join via `maxFields`); it fails when the join and the sorts do not share the 
holders.



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