dongjoon-hyun commented on code in PR #60475:
URL: https://github.com/apache/spark/pull/60475#discussion_r4570500778


##########
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") {

Review Comment:
   This test verifies that no plan node is serialized and that the result is 
correct, but it does not verify the key invariant of this PR: the eager cleanup 
of the join closes the very sorter that the generated `Sort` code created, 
i.e., both share the same `SortExecSorterHolder` instance after deserialization.
   
   If a future change breaks this sharing (e.g., making `sorterHolder` 
`@transient`, turning the `lazy val` into a `def`, or copying `SortExec` after 
codegen), the early release of SPARK-21492 would silently become a no-op. Since 
the sorter is still freed at task completion and the result stays correct, both 
this test and `JoinSuite` would still pass. Could we add an assertion for this, 
e.g., deserializing the stage RDD and checking the identity of the referenced 
holders, or checking that the sorter memory is released before the task ends?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala:
##########
@@ -229,4 +204,103 @@ object SortExec {
     spillSize += metrics.memoryBytesSpilled - spillSizeBefore
     metrics.incPeakExecutionMemory(sorter.getPeakMemoryUsage)
   }
+
+  /**
+   * The sorter holders of the [[SortExec]]s that run in the same task as 
`plan`: those in its
+   * subtree, but not beyond an [[Exchange]]. A join that releases its 
children's resources early
+   * from its generated code (see [[genCleanupSorters]]) references these 
instead of its child
+   * plans, so that the plans are not serialized into every task.
+   */
+  private[sql] def sorterHoldersInStage(plan: SparkPlan): 
Array[SortExecSorterHolder] = {
+    val holders = mutable.ArrayBuffer[SortExecSorterHolder]()
+    def visit(p: SparkPlan): Unit = p match {
+      case _: Exchange =>
+      case s: SortExec =>
+        holders += s.sorterHolder
+        visit(s.child)
+      case other => other.children.foreach(visit)
+    }
+    visit(plan)
+    holders.toArray
+  }
+
+  /**
+   * Generates the code that closes the sorters of the [[SortExec]]s below 
`join`, for a join that
+   * releases its children's resources early. This does in generated code what
+   * `join.cleanupResources()` does, without referencing the plan: only the 
sorter holders from
+   * [[sorterHoldersInStage]]. The other plan nodes that override 
[[SparkPlan.cleanupResources]]
+   * hold nothing to release in a task.
+   */
+  private[sql] def genCleanupSorters(ctx: CodegenContext, join: SparkPlan): 
String = {

Review Comment:
   This is a subtle behavior change. Previously, the generated code called 
`join.cleanupResources()`, which recursively reached `cleanupResources()` of 
every node below the join. Now only the `SortExec` sorters are released 
eagerly, while the interpreted path (`SortMergeJoinEvaluatorFactory` calls 
`cleanupResources()` of `left` and `right`) still reaches all of them, so the 
two paths behave differently.
   
   Since `cleanupResources()` is `protected[sql]`, a physical node outside 
Spark (e.g., from a plugin or an extension in an `org.apache.spark.sql` 
package) may override it to release native memory or buffers early. Under a 
codegen SMJ, such resources would now be held until the task completes, while 
they are still released early with `spark.sql.codegen.wholeStage=false`.
   
   The doc comment at L231-232 (`The other plan nodes that override 
cleanupResources hold nothing to release in a task`) is true for the built-in 
nodes today, but it is an assumption. Could you document it as such, or keep 
the parity with the interpreted path?



##########
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:
   `WholeStageCodegenSuite` mixes in `DisableAdaptiveExecutionSuite`, so the 
default AQE plan shape is not covered. With AQE, the child of `Sort` is 
`AQEShuffleReadExec` / `ShuffleQueryStageExec` instead of `Exchange`, and 
`sorterHoldersInStage` stops there only because `QueryStageExec` is a leaf 
node. It would be good to cover the AQE case as well, together with the 
ExistenceJoin codegen path (`eagerCleanup` in `codegenExistence`) and the 
combination of an interpreted SMJ with a codegen `Sort`.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala:
##########
@@ -229,4 +204,103 @@ object SortExec {
     spillSize += metrics.memoryBytesSpilled - spillSizeBefore
     metrics.incPeakExecutionMemory(sorter.getPeakMemoryUsage)
   }
+
+  /**
+   * The sorter holders of the [[SortExec]]s that run in the same task as 
`plan`: those in its
+   * subtree, but not beyond an [[Exchange]]. A join that releases its 
children's resources early
+   * from its generated code (see [[genCleanupSorters]]) references these 
instead of its child
+   * plans, so that the plans are not serialized into every task.
+   */
+  private[sql] def sorterHoldersInStage(plan: SparkPlan): 
Array[SortExecSorterHolder] = {
+    val holders = mutable.ArrayBuffer[SortExecSorterHolder]()
+    def visit(p: SparkPlan): Unit = p match {
+      case _: Exchange =>
+      case s: SortExec =>
+        holders += s.sorterHolder
+        visit(s.child)
+      case other => other.children.foreach(visit)
+    }
+    visit(plan)
+    holders.toArray
+  }
+
+  /**
+   * Generates the code that closes the sorters of the [[SortExec]]s below 
`join`, for a join that
+   * releases its children's resources early. This does in generated code what
+   * `join.cleanupResources()` does, without referencing the plan: only the 
sorter holders from
+   * [[sorterHoldersInStage]]. The other plan nodes that override 
[[SparkPlan.cleanupResources]]
+   * hold nothing to release in a task.
+   */
+  private[sql] def genCleanupSorters(ctx: CodegenContext, join: SparkPlan): 
String = {
+    val holders = ctx.addReferenceObj("sorterHolders", 
sorterHoldersInStage(join),
+      s"${classOf[SortExecSorterHolder].getName}[]")
+    s"${classOf[SortExec].getName}.cleanupSorters($holders);"

Review Comment:
   nit: When there is no `SortExec` below the join (e.g., when the inputs are 
already sorted), this still adds a reference to an empty array and generates a 
no-op `cleanupSorters` call. We could return an empty string in that case:
   ```scala
       val holders = sorterHoldersInStage(join)
       if (holders.isEmpty) {
         ""
       } else {
         val ref = ctx.addReferenceObj("sorterHolders", holders)
         s"${classOf[SortExec].getName}.cleanupSorters($ref);"
       }
   ```



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala:
##########
@@ -229,4 +204,103 @@ object SortExec {
     spillSize += metrics.memoryBytesSpilled - spillSizeBefore
     metrics.incPeakExecutionMemory(sorter.getPeakMemoryUsage)
   }
+
+  /**
+   * The sorter holders of the [[SortExec]]s that run in the same task as 
`plan`: those in its
+   * subtree, but not beyond an [[Exchange]]. A join that releases its 
children's resources early
+   * from its generated code (see [[genCleanupSorters]]) references these 
instead of its child
+   * plans, so that the plans are not serialized into every task.
+   */
+  private[sql] def sorterHoldersInStage(plan: SparkPlan): 
Array[SortExecSorterHolder] = {

Review Comment:
   This hard-codes a `SortExec`-only special case into the shared join codegen, 
which effectively introduces a second cleanup path separate from the 
`SparkPlan.cleanupResources()` contract. If a node overriding 
`cleanupResources()` is added later, it would work only in the interpreted path 
and be silently skipped in the codegen path.
   
   What do you think about a more general hook instead? For example, a node 
could expose a serializable cleanup handle (like `SortExecSorterHolder`), and 
`SparkPlan` could collect them up to the `Exchange` boundary. Then the join 
codegen would not need to know about `SortExec`.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala:
##########
@@ -229,4 +204,103 @@ object SortExec {
     spillSize += metrics.memoryBytesSpilled - spillSizeBefore
     metrics.incPeakExecutionMemory(sorter.getPeakMemoryUsage)
   }
+
+  /**
+   * The sorter holders of the [[SortExec]]s that run in the same task as 
`plan`: those in its
+   * subtree, but not beyond an [[Exchange]]. A join that releases its 
children's resources early
+   * from its generated code (see [[genCleanupSorters]]) references these 
instead of its child
+   * plans, so that the plans are not serialized into every task.
+   */
+  private[sql] def sorterHoldersInStage(plan: SparkPlan): 
Array[SortExecSorterHolder] = {
+    val holders = mutable.ArrayBuffer[SortExecSorterHolder]()
+    def visit(p: SparkPlan): Unit = p match {
+      case _: Exchange =>
+      case s: SortExec =>
+        holders += s.sorterHolder
+        visit(s.child)
+      case other => other.children.foreach(visit)
+    }
+    visit(plan)
+    holders.toArray
+  }
+
+  /**
+   * Generates the code that closes the sorters of the [[SortExec]]s below 
`join`, for a join that
+   * releases its children's resources early. This does in generated code what
+   * `join.cleanupResources()` does, without referencing the plan: only the 
sorter holders from
+   * [[sorterHoldersInStage]]. The other plan nodes that override 
[[SparkPlan.cleanupResources]]
+   * hold nothing to release in a task.
+   */
+  private[sql] def genCleanupSorters(ctx: CodegenContext, join: SparkPlan): 
String = {
+    val holders = ctx.addReferenceObj("sorterHolders", 
sorterHoldersInStage(join),
+      s"${classOf[SortExecSorterHolder].getName}[]")

Review Comment:
   nit: The explicit `className` is not needed. The default 
`CodeGenerator.typeName(obj.getClass)` already returns 
`...SortExecSorterHolder[]` for an array.
   ```suggestion
       val holders = ctx.addReferenceObj("sorterHolders", 
sorterHoldersInStage(join))
   ```



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala:
##########
@@ -229,4 +204,103 @@ object SortExec {
     spillSize += metrics.memoryBytesSpilled - spillSizeBefore
     metrics.incPeakExecutionMemory(sorter.getPeakMemoryUsage)
   }
+
+  /**
+   * The sorter holders of the [[SortExec]]s that run in the same task as 
`plan`: those in its
+   * subtree, but not beyond an [[Exchange]]. A join that releases its 
children's resources early
+   * from its generated code (see [[genCleanupSorters]]) references these 
instead of its child
+   * plans, so that the plans are not serialized into every task.
+   */
+  private[sql] def sorterHoldersInStage(plan: SparkPlan): 
Array[SortExecSorterHolder] = {
+    val holders = mutable.ArrayBuffer[SortExecSorterHolder]()
+    def visit(p: SparkPlan): Unit = p match {
+      case _: Exchange =>
+      case s: SortExec =>
+        holders += s.sorterHolder
+        visit(s.child)
+      case other => other.children.foreach(visit)
+    }
+    visit(plan)
+    holders.toArray
+  }
+
+  /**
+   * Generates the code that closes the sorters of the [[SortExec]]s below 
`join`, for a join that
+   * releases its children's resources early. This does in generated code what
+   * `join.cleanupResources()` does, without referencing the plan: only the 
sorter holders from
+   * [[sorterHoldersInStage]]. The other plan nodes that override 
[[SparkPlan.cleanupResources]]
+   * hold nothing to release in a task.
+   */
+  private[sql] def genCleanupSorters(ctx: CodegenContext, join: SparkPlan): 
String = {
+    val holders = ctx.addReferenceObj("sorterHolders", 
sorterHoldersInStage(join),
+      s"${classOf[SortExecSorterHolder].getName}[]")
+    s"${classOf[SortExec].getName}.cleanupSorters($holders);"
+  }
+
+  /** Closes the sorters of `holders`. Called from the code of 
[[genCleanupSorters]]. */
+  def cleanupSorters(holders: Array[SortExecSorterHolder]): Unit = {
+    holders.foreach(_.cleanupResources())
+  }
+}
+
+/**
+ * Creates the sorter of a [[SortExec]] and holds it until 
[[cleanupResources]]. It holds only what
+ * the sorter needs, not the plan, and is referenced by the generated code of 
the [[SortExec]] and
+ * of joins that release the sorter early (see 
[[SortExec.sorterHoldersInStage]]).
+ *
+ * WARNING: the sorter is per-task mutable state. Each task deserializes its 
own copy of the
+ * holder from the task binary, so it must not be shared across tasks or 
accessed from multiple
+ * threads concurrently.
+ */
+private[sql] class SortExecSorterHolder(
+    sortOrder: Seq[SortOrder],
+    output: Seq[Attribute],
+    enableRadixSort: Boolean,
+    testSpillFrequency: Int) extends Serializable {
+
+  @transient private var rowSorter: UnsafeExternalRowSorter = _
+
+  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(DataTypeUtils.fromAttributes(output), ordering,

Review Comment:
   nit: Previously, this used the cached `schema` of the node, but now 
`DataTypeUtils.fromAttributes(output)` builds a new `StructType` on every 
`createSorter()` call. The cost is small, but we could compute it once in the 
holder, e.g., `@transient private lazy val schema = 
DataTypeUtils.fromAttributes(output)`.



##########
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:
   Not introduced by this PR, but 
`FileFormatWriter.createConcurrentOutputWriterSpec` still passes `() => 
sortPlan.createSorter()`, which captures the whole `SortExec` and its child 
subtree into every write task when `spark.sql.maxConcurrentOutputFileWriters > 
0`. Now that we have the holder, `val holder = sortPlan.sorterHolder; () => 
holder.createSorter()` would ship only the holder. This could be a follow-up.



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