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


##########
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:
   **[1] `createSorter()` has no caller left, and it no longer works the way 
its scaladoc says.**
   
   Nothing in the repository calls `SortExec.createSorter()` any more. Outside 
a task it fails with an NPE, since the `UnsafeExternalRowSorter` constructor 
dereferences `TaskContext.get()` (`UnsafeExternalRowSorter.java:111-113`), so 
"on the driver side, e.g. for a test" works only with a hand-made 
`TaskContext`. In a task, where it does run, it creates the sorter on the 
deserialized node's own transient holder, which no join's `taskResourceCleaner` 
reaches. That is the use the `sorterHolder` scaladoc above rules out.
   
   Could we remove it? A caller outside Spark, e.g. a writer derived from the 
previous `FileFormatWriter` (`() => sortPlan.createSorter()`), would then get a 
compile error and move to `sorterHolder`, instead of silently depending on the 
node's transient holder. If it has to stay for source compatibility, the 
scaladoc could say that.



##########
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:
   **[2] `cleanupResources()` no longer releases anything, while its scaladoc 
says it closes the sorter.**
   
   In a task the node is a deserialized copy, and its transient `sorterHolder` 
is a fresh one, so this closes nothing, even when the generated code or 
`doExecute` filled the holder captured on the driver. Before this PR the same 
call in a task closed the sorter, which is how the sort merge joins used it. On 
the driver, the remaining caller is the stage cleanup of adaptive execution 
(`AdaptiveSparkPlanExec.scala:410`, through `QueryStageExec.scala:157`), where 
the holder has no sorter, so it does nothing there either.
   
   Could we drop this override? If it stays, the scaladoc could say that it 
releases nothing in a task and that code running in a task has to go through 
`taskResourceCleaner`. As written ("we overwrite cleanupResources to close 
UnsafeExternalRowSorter"), it suggests that a task-side 
`child.cleanupResources()`, as the joins did before this PR, still releases the 
sorter.



##########
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:
   **[3] nit: `inStage` can also collect the cleaners of another stage.**
   
   Only an `Exchange` or a leaf ends the walk, but an operator can also start a 
new stage inside its own `doExecute`. For example, `TakeOrderedAndProjectExec` 
is planned for a non-root `ORDER BY ... LIMIT` as well 
(`SparkStrategies.scala:131`), its `SinglePartition` output can satisfy the 
join's distribution without an exchange (e.g. when both sides are such 
subqueries), and it shuffles its child when the child has more than one 
partition (`limit.scala:365`). The cleaners of the sorts below it are then 
serialized into the join's tasks and released there, where they were never used.
   
   That is harmless with `SortExecSorterHolder`, which skips a null sorter, but 
the scaladoc ("the operators that run in the same task as `plan`") reads as 
exact. Could it say that the set can include operators of other stages, so a 
cleaner must be a no-op in a task that did not use it?



##########
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:
   **[4] nit: `cleanupAll` has one caller.**
   
   It is `cleaners.foreach(_.cleanupResources())`, and only 
`SortMergeJoinEvaluator.cleanupResources` calls it, since `genCleanupInStage` 
emits its own loop. Inlining it there would remove one indirection.



##########
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:
   **[5] The as-of join is checked only fully generated, with adaptive 
execution off.**
   
   This block is outside the loops over `codegenConfs` and `aqe`, and the suite 
mixes in `DisableAdaptiveExecutionSuite`, so the as-of join runs in one of the 
six combinations the sort merge joins run in. The PR description lists it with 
the cases covered with generated sorts under an interpreted join, without 
codegen, and with AQE on and off. It would not pass the check there: the 
interpreted `SortMergeAsOfJoinExec.doExecute` builds its scanner from 
`left.output`, `leftKeys` and other fields of the node inside the closure 
(`SortMergeAsOfJoinExec.scala:117-127`), so its task binary still carries the 
node and its subtree.
   
   That part predates this PR, so it need not be fixed here, but could the 
description, or a comment on this block, say that only the generated as-of join 
is covered?



##########
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:
   **[6] `full_outer` is not among the join types.**
   
   The full outer sort merge join is generated by default (`codegenFullOuter`, 
under `spark.sql.codegen.join.fullOuterSortMergeJoin.enabled`), and runs the 
`FullOuter` branch of `SortMergeJoinEvaluatorFactory` otherwise 
(`SortMergeJoinEvaluatorFactory.scala:183`), which now takes the children's 
output instead of the child plans. Neither path is checked here. Adding 
`"full_outer"` to `joinTypes` would cover both, since its output has four 
columns, so it runs interpreted in the `maxFields = 3` mode.



##########
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:
   **[7] nit: in this mode the semi and anti joins still run generated.**
   
   The output of a semi or anti join is its left side's output, here only `k1`, 
which does not exceed `maxFields = 1`, so the join stays in codegen, and the 
`output.length > 1` guard at L1238 skips the check that would show it. In fact, 
`maxFields` cannot make these joins interpreted while their left sort stays 
generated, since both have the same columns. The existence join does run 
interpreted here, as its output adds the `exists` column. Could the comment 
above say that this mode covers the inner, outer and existence joins only?



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