spark-test commented on code in PR #60475:
URL: https://github.com/apache/spark/pull/60475#discussion_r4571579684


##########
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:
   **Non-blocking (P2):** Only generated code reaches the sorter through the 
holder. Every other task-side caller still reaches it through the node, via 
this delegate or `cleanupResources()`, and so captures the plan:
   
   - `SortExec.doExecute` calls `createSorter()` inside its 
`mapPartitionsInternal` closure.
   - `SortMergeJoinExec.doExecute` hands `SortMergeJoinEvaluatorFactory` both 
child plans, which it uses only for `cleanupResources()` and their `output`.
   - `FileFormatWriter`'s concurrent-writer spec captures `() => 
sortPlan.createSorter()` when `spark.sql.maxConcurrentOutputFileWriters` is set.
   
   These paths run under default settings. `CollapseCodegenStages` keeps any 
operator whose schema exceeds `spark.sql.codegen.maxFields` (100) out of 
codegen, so a global `orderBy` over 120 columns runs this sort interpreted, and 
a sort merge join of two 60-column tables runs the join interpreted over 
generated sorts. Stages that fall back after a compile failure, or because a 
method exceeds `spark.sql.codegen.hugeMethodLimit`, land on them too. Their 
task binaries still carry the plan through the exchange below, which is the 
cost this PR removes for generated code, so the wide-schema sorts and joins 
with the largest plans miss the saving. Capturing the holder instead of the 
node works on each of these paths, and nothing in the code marks them as 
deferred. Results are unaffected.
   
   See **Shared repair plan 1** in the review body.



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

Review Comment:
   **Non-blocking (P2):** This holder is a non-transient lazy val, and the 
driver forces it before any task binary is written: in `doProduce`, in 
`sorterHoldersInStage`, and, with adaptive execution, in `cleanupResources()`, 
which the stage cleanup in `AdaptiveSparkPlanExec` reaches for every 
materialized stage, whether or not the sort was generated. On the base branch 
the node's only sorter field was null on the driver, so a serialized `SortExec` 
carried no sorter state. Now every task binary that still serializes a 
`SortExec` also writes its holder and the output list built for it, and nothing 
is removed to offset them. `FilterExec.output`, for example, rebuilds that list 
and adds a new non-nullable attribute for the join key.
   
   Plan subtrees are still serialized by keyed `HashAggregateExec` codegen 
(until SPARK-61661), by `ShuffledHashJoinExec` codegen and by interpreted 
operators, and they reach upstream `SortExec`s through 
`ShuffleExchangeExec.child` or `ShuffleQueryStageExec.plan`. For example, when 
both sides are too large to broadcast, `df1.join(df2, 
"k").groupBy("v").count()` gets larger task binaries than on the base branch in 
two stages: the join plus partial aggregate stage, and the final aggregate 
stage after the exchange on `v`, which runs no sort at all. From the code, the 
growth is one holder and one output list per reachable `SortExec`, plus a new 
attribute for each computed or nullability-adjusted sort-input column. It is 
estimated at about 1% of the binary for narrow schemas and has not been 
measured. Results are unaffected.
   
   See **Shared repair plan 1** in the review body.



##########
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:
   **Non-blocking (P2):** These cases run only fully generated stages, but the 
PR also relies on a second route to the holder. When a sort merge join's output 
exceeds `spark.sql.codegen.maxFields` while each side stays within it, for 
example a join of two 60-column tables, the join runs interpreted over 
generated sorts. `SortMergeJoinEvaluatorFactory.cleanupResources` then calls 
`cleanupResources()` on its children, which reaches the `SortExec` node's 
deserialized `sorterHolder`, and that has to be the object the generated Sort 
code filled. The `sorterHolder` scaladoc relies on this, and it holds only 
while the field is a non-transient lazy val written into the same task binary. 
A generated join over a sort that fell back to interpreted execution depends on 
the same field.
   
   If the holder became `@transient`, a natural step to keep it out of 
plan-carrying binaries, fully generated joins would keep working, because both 
of their references point at the holder object itself. But each deserialized 
node would get a fresh holder, so early release in this mode would silently 
close nothing, and the sorter of a side the join stops reading early would hold 
its memory until the task ends. Neither these cases nor JoinSuite's SPARK-21492 
test, which disables all codegen, would notice, since answers do not change and 
the task-completion listener frees the memory. Covering this plan needs a check 
that observes the released memory itself; checking answers or the absence of 
plan nodes in this mode would not catch the regression.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60475#discussion_r4570500778), 
[2](https://github.com/apache/spark/pull/60475#discussion_r4570500791), 
[3](https://github.com/apache/spark/pull/60475#pullrequestreview-5900343981).
   
   **Verification:**
   - **Behavior:** In a task running a fully generated sort merge join (inner, 
left and right outer, semi and anti) or a generated as-of join, over inputs 
where the join finishes before reading one side to its end, the sorts below the 
join hold no execution memory once the join has produced its last row, while 
the task is still running.
   - **Behavior:** The same holds for an interpreted sort merge join over 
generated sorts, for example a join whose output exceeds 
spark.sql.codegen.maxFields while each side stays within it.
   - **Regression:** Each check fails when the join releases holders other than 
the ones its sorts filled, for example when sorterHolder is turned into a def, 
because the sorters then keep their memory until the task ends.



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