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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ShuffledHashJoinExec.scala:
##########
@@ -98,33 +98,27 @@ case class ShuffledHashJoinExec private (
   }
 
   /**
-   * This is called by generated Java class, should be public.
+   * Creates the builder of the build-side [[HashedRelation]]. It holds only 
what building the
+   * relation needs, so the generated code can reference it instead of this 
plan node, which would
+   * serialize the child subtrees into every task.
    */
-  def buildHashedRelation(iter: Iterator[InternalRow]): HashedRelation = {
-    val buildDataSize = longMetric("buildDataSize")
-    val buildTime = longMetric("buildTime")
-    val start = System.nanoTime()
-    val context = TaskContext.get()
-    val relation = HashedRelation(
-      iter,
+  private def createRelationBuilder(): ShuffledHashJoinRelationBuilder = {
+    new ShuffledHashJoinRelationBuilder(
       buildBoundKeys,

Review Comment:
   **[1] A `ScalarSubquery` in the build keys still serializes a plan subtree 
into every task.** `buildBoundKeys` keeps the physical 
`execution.ScalarSubquery` as is, and its `plan` field (a `SubqueryExec` with 
its child, subquery.scala:68-70) is not transient. So for a key like `t1.a = 
t2.b + (SELECT max(c) FROM t3)`, the builder still carries the subquery plan, 
down to the `t3` scan, into every task binary. The stream-side keys and the 
condition do not have this, because `ScalarSubquery.doGenCode` inlines the 
result as a literal. This is not a regression, since the whole node was 
serialized before, but the goal of this PR does not hold in this case, and the 
new test does not cover it. Could `createRelationBuilder` pass the keys with 
`transform { case s: ScalarSubquery => s.toLiteral }`, or could a follow-up 
handle it?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ShuffledHashJoinExec.scala:
##########
@@ -98,33 +98,27 @@ case class ShuffledHashJoinExec private (
   }
 
   /**
-   * This is called by generated Java class, should be public.
+   * Creates the builder of the build-side [[HashedRelation]]. It holds only 
what building the
+   * relation needs, so the generated code can reference it instead of this 
plan node, which would
+   * serialize the child subtrees into every task.
    */
-  def buildHashedRelation(iter: Iterator[InternalRow]): HashedRelation = {
-    val buildDataSize = longMetric("buildDataSize")
-    val buildTime = longMetric("buildTime")
-    val start = System.nanoTime()
-    val context = TaskContext.get()
-    val relation = HashedRelation(
-      iter,
+  private def createRelationBuilder(): ShuffledHashJoinRelationBuilder = {
+    new ShuffledHashJoinRelationBuilder(
       buildBoundKeys,
-      taskMemoryManager = context.taskMemoryManager(),
       // build-side or full outer join needs support for NULL key in 
HashedRelation.
       allowsNullKey = joinType == FullOuter ||
         (joinType == LeftOuter && buildSide == BuildLeft) ||
         (joinType == RightOuter && buildSide == BuildRight),
       ignoresDuplicatedKey = ignoreDuplicatedKey)
-    buildTime += NANOSECONDS.toMillis(System.nanoTime() - start)
-    buildDataSize += relation.estimatedSize
-    // This relation is usually used until the end of task.
-    context.addTaskCompletionListener[Unit](_ => relation.close())
-    relation
   }
 
   protected override def doExecute(): RDD[InternalRow] = {
     val numOutputRows = longMetric("numOutputRows")
+    val buildTime = longMetric("buildTime")
+    val buildDataSize = longMetric("buildDataSize")
+    val relationBuilder = createRelationBuilder()

Review Comment:
   **[2] Minor: in `doExecute`, the builder adds a serialized copy of the bound 
keys.** The `zipPartitions` closure still calls `buildSideOrFullOuterJoin`, 
`join`, `joinType` and `buildSide`, so it still captures `this`, and the node 
is serialized with the closure as before. Before this PR, `buildBoundKeys` (a 
`@transient lazy val`, HashJoin.scala:132) and `ignoreDuplicatedKey` (L94) were 
left out and computed again on the executors. Now the closure also captures 
`relationBuilder`, so the bound keys go into the task binary next to the node. 
The cost is small, but this path gains nothing from the builder. Could the 
closure call `createRelationBuilder()` itself, so that these are computed on 
the executors as before?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -563,6 +566,72 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61668: ShuffledHashJoin codegen references do not serialize plan 
nodes") {
+    // What a codegen stage adds to the task binary (its closure, with the 
references of the
+    // generated code) is serialized into every task. A plan node in it would 
drag its whole child
+    // subtrees along, through the exchanges below the join.
+    def serializedPlanNodes(stage: WholeStageCodegenExec): Seq[String] = {
+      // Serialize the RDD that the stage adds on top of its input RDDs, as 
the task binary does:
+      // its closure or evaluator factory with the generated code references. 
The input RDDs are
+      // not followed, since they belong to the operators below this stage.
+      val rdd = stage.execute()
+      val planNodes = mutable.ArrayBuffer[String]()
+      val out = new ObjectOutputStream(new ByteArrayOutputStream()) {
+        enableReplaceObject(true)
+        override def replaceObject(obj: AnyRef): AnyRef = obj match {
+          case p: SparkPlan => planNodes += p.nodeName; p
+          case r: RDD[_] if r ne rdd => null

Review Comment:
   **[3] Minor: the helper also drops the RDD that the stage builds itself.** 
`case r: RDD[_] if r ne rdd => null` drops every RDD except the top one. With 
`usePartitionEvaluator=false` and two inputs, `WholeStageCodegenExec.doExecute` 
builds `zipPartitions(...) {...}.mapPartitionsWithIndex {...}` 
(WholeStageCodegenExec.scala:1072-1079), so the stage's own 
`ZippedPartitionsRDD2` and its closure are dropped too, not only the input RDDs 
that L575-576 name. That closure captures nothing today, so nothing is missed 
now, but a reference added there later would still pass this test. #60475 
replaces only `inputRDDs()`. Could this helper do the same?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -563,6 +566,72 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61668: ShuffledHashJoin codegen references do not serialize plan 
nodes") {
+    // What a codegen stage adds to the task binary (its closure, with the 
references of the
+    // generated code) is serialized into every task. A plan node in it would 
drag its whole child
+    // subtrees along, through the exchanges below the join.
+    def serializedPlanNodes(stage: WholeStageCodegenExec): Seq[String] = {
+      // Serialize the RDD that the stage adds on top of its input RDDs, as 
the task binary does:
+      // its closure or evaluator factory with the generated code references. 
The input RDDs are
+      // not followed, since they belong to the operators below this stage.
+      val rdd = stage.execute()
+      val planNodes = mutable.ArrayBuffer[String]()
+      val out = new ObjectOutputStream(new ByteArrayOutputStream()) {
+        enableReplaceObject(true)
+        override def replaceObject(obj: AnyRef): AnyRef = obj match {
+          case p: SparkPlan => planNodes += p.nodeName; p
+          case r: RDD[_] if r ne rdd => null
+          case o => o
+        }
+      }
+      out.writeObject(rdd)
+      out.close()
+      planNodes.toSeq
+    }
+
+    val df1 = spark.range(0, 20, 1, 2).select(($"id" % 7).as("k1"), 
$"id".as("v1"))
+    val df2 = spark.range(0, 15, 1, 2).select(($"id" % 5).as("k2"), 
$"id".as("v2"))
+    val cond = $"k1" === $"k2" && $"v1" =!= $"v2"
+    // (join type, hint the left side, expected build side). The hinted side 
is the build side.
+    val cases = Seq(

Review Comment:
   **[5] Minor: a few join types that also go through `prepareRelation` are not 
in the cases.** ExistenceJoin (`codegenExistence`), LeftSingle (through 
`codegenOuter`) and the stream-side `right_outer` with `BuildLeft` are missing. 
A plan reference added back on one of those paths would not fail this test. 
Could the list add the `right_outer` case, and the other two if a hint can 
force them into a shuffled hash join?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ShuffledHashJoinExec.scala:
##########
@@ -679,3 +678,45 @@ object ShuffledHashJoinExec {
       isSkewJoin)
   }
 }
+
+/**
+ * Builds the [[HashedRelation]] of the build side of a 
[[ShuffledHashJoinExec]] in each task.
+ *
+ * The generated code of the join references this builder, and the references 
of the generated
+ * code are serialized into every task binary. So it holds only what building 
the relation needs,
+ * not the plan node, whose child subtrees (through the exchanges below the 
join) would otherwise
+ * be serialized and deserialized by every task.
+ *
+ * @param buildBoundKeys the build-side join keys, bound to the build-side 
output.
+ * @param allowsNullKey whether the relation must support null keys 
(build-side outer and full
+ *                      outer joins).
+ * @param ignoresDuplicatedKey whether the relation keeps only the first row 
of each key.
+ */
+private[joins] class ShuffledHashJoinRelationBuilder(
+    buildBoundKeys: Seq[Expression],
+    allowsNullKey: Boolean,
+    ignoresDuplicatedKey: Boolean) extends Serializable {
+
+  /**
+   * Builds the relation from the build-side rows of the current task, and 
closes it when the task
+   * completes. Called by the generated code, so it must be public.
+   */
+  def build(

Review Comment:
   **[10] Nit: the two metrics could be fields of the builder.** 
`createRelationBuilder()` runs on the driver, so it can pass 
`longMetric("buildTime")` and `longMetric("buildDataSize")` to the constructor. 
Within one serialization stream the same accumulator stays one object, so 
`doExecute` would still update the same metrics. Then the generated code is 
just `$relationBuilder.build(inputs[1])`, without the two `metricTerm` 
references at L371-372. Could `build` take only the iterator?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -563,6 +566,72 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61668: ShuffledHashJoin codegen references do not serialize plan 
nodes") {
+    // What a codegen stage adds to the task binary (its closure, with the 
references of the
+    // generated code) is serialized into every task. A plan node in it would 
drag its whole child
+    // subtrees along, through the exchanges below the join.
+    def serializedPlanNodes(stage: WholeStageCodegenExec): Seq[String] = {

Review Comment:
   **[9] Minor: #60468 and #60475 add almost the same helper to this suite.** 
Both also add `serializedPlanNodes` with the same `java.io` and 
`scala.collection.mutable` imports, but the three helpers differ in what they 
cut: this one and #60468 drop every RDD but the top one, while #60475 replaces 
only `inputRDDs()` with `"input RDD"`. Merged one after another, the PRs would 
conflict on the imports and leave three helpers that behave a little 
differently. Could one suite-level private helper be shared, for example added 
by the first PR that merges and reused by the other two?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -563,6 +566,72 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61668: ShuffledHashJoin codegen references do not serialize plan 
nodes") {
+    // What a codegen stage adds to the task binary (its closure, with the 
references of the
+    // generated code) is serialized into every task. A plan node in it would 
drag its whole child
+    // subtrees along, through the exchanges below the join.
+    def serializedPlanNodes(stage: WholeStageCodegenExec): Seq[String] = {
+      // Serialize the RDD that the stage adds on top of its input RDDs, as 
the task binary does:
+      // its closure or evaluator factory with the generated code references. 
The input RDDs are
+      // not followed, since they belong to the operators below this stage.
+      val rdd = stage.execute()
+      val planNodes = mutable.ArrayBuffer[String]()
+      val out = new ObjectOutputStream(new ByteArrayOutputStream()) {
+        enableReplaceObject(true)
+        override def replaceObject(obj: AnyRef): AnyRef = obj match {
+          case p: SparkPlan => planNodes += p.nodeName; p
+          case r: RDD[_] if r ne rdd => null
+          case o => o
+        }
+      }
+      out.writeObject(rdd)
+      out.close()
+      planNodes.toSeq
+    }
+
+    val df1 = spark.range(0, 20, 1, 2).select(($"id" % 7).as("k1"), 
$"id".as("v1"))
+    val df2 = spark.range(0, 15, 1, 2).select(($"id" % 5).as("k2"), 
$"id".as("v2"))
+    val cond = $"k1" === $"k2" && $"v1" =!= $"v2"
+    // (join type, hint the left side, expected build side). The hinted side 
is the build side.
+    val cases = Seq(
+      ("inner", false, BuildRight),
+      ("inner", true, BuildLeft),
+      // Stream-side outer join.
+      ("left_outer", false, BuildRight),
+      // Build-side outer joins.
+      ("left_outer", true, BuildLeft),
+      ("right_outer", false, BuildRight),
+      ("full_outer", false, BuildRight),
+      ("full_outer", true, BuildLeft),
+      ("left_semi", false, BuildRight),
+      ("left_anti", false, BuildRight))
+    for {
+      (joinType, hintLeft, buildSide) <- cases
+      usePartitionEvaluator <- Seq(false, true)
+    } {
+      def join(): DataFrame = if (hintLeft) {
+        df1.hint("SHUFFLE_HASH").join(df2, cond, joinType)
+      } else {
+        df1.join(df2.hint("SHUFFLE_HASH"), cond, joinType)
+      }
+      val expected = withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> 
"false") {

Review Comment:
   **[4] Minor: the expected rows go through the same builder.** With 
`WHOLESTAGE_CODEGEN_ENABLED=false`, `doExecute` also builds the relation with 
`ShuffledHashJoinRelationBuilder`. So a mistake that both paths share (for 
example a wrong `allowsNullKey` or `ignoresDuplicatedKey`) gives the same wrong 
rows on both sides, and `checkAnswer` still passes. Also, `cond` refers to the 
build-side `v2`, so `ignoreDuplicatedKey` is false in every case, and the 
`ignoresDuplicatedKey = true` path of the semi and anti joins never runs here. 
Could the test compare with fixed expected rows, or add a semi/anti case whose 
condition uses only stream-side columns?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -563,6 +566,72 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61668: ShuffledHashJoin codegen references do not serialize plan 
nodes") {
+    // What a codegen stage adds to the task binary (its closure, with the 
references of the
+    // generated code) is serialized into every task. A plan node in it would 
drag its whole child
+    // subtrees along, through the exchanges below the join.
+    def serializedPlanNodes(stage: WholeStageCodegenExec): Seq[String] = {
+      // Serialize the RDD that the stage adds on top of its input RDDs, as 
the task binary does:
+      // its closure or evaluator factory with the generated code references. 
The input RDDs are
+      // not followed, since they belong to the operators below this stage.
+      val rdd = stage.execute()
+      val planNodes = mutable.ArrayBuffer[String]()
+      val out = new ObjectOutputStream(new ByteArrayOutputStream()) {
+        enableReplaceObject(true)
+        override def replaceObject(obj: AnyRef): AnyRef = obj match {
+          case p: SparkPlan => planNodes += p.nodeName; p
+          case r: RDD[_] if r ne rdd => null
+          case o => o
+        }
+      }
+      out.writeObject(rdd)
+      out.close()
+      planNodes.toSeq
+    }
+
+    val df1 = spark.range(0, 20, 1, 2).select(($"id" % 7).as("k1"), 
$"id".as("v1"))
+    val df2 = spark.range(0, 15, 1, 2).select(($"id" % 5).as("k2"), 
$"id".as("v2"))
+    val cond = $"k1" === $"k2" && $"v1" =!= $"v2"
+    // (join type, hint the left side, expected build side). The hinted side 
is the build side.
+    val cases = Seq(
+      ("inner", false, BuildRight),
+      ("inner", true, BuildLeft),
+      // Stream-side outer join.
+      ("left_outer", false, BuildRight),
+      // Build-side outer joins.
+      ("left_outer", true, BuildLeft),
+      ("right_outer", false, BuildRight),
+      ("full_outer", false, BuildRight),
+      ("full_outer", true, BuildLeft),
+      ("left_semi", false, BuildRight),
+      ("left_anti", false, BuildRight))
+    for {
+      (joinType, hintLeft, buildSide) <- cases
+      usePartitionEvaluator <- Seq(false, true)

Review Comment:
   **[6] Nit: the expected rows are computed twice for each case.** 
`usePartitionEvaluator` is the inner generator, and `expected` does not depend 
on it, so the interpreted query runs 18 times instead of 9. The messages at 
L624, L627 and L629 also do not say which `usePartitionEvaluator` value failed. 
Could `expected` move out of the inner loop, and the messages include 
`usePartitionEvaluator=$usePartitionEvaluator`?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ShuffledHashJoinExec.scala:
##########
@@ -371,12 +365,17 @@ case class ShuffledHashJoinExec private (
   override def needCopyResult: Boolean = true
 
   protected override def prepareRelation(ctx: CodegenContext): 
HashedRelationInfo = {
-    val thisPlan = ctx.addReferenceObj("plan", this)
+    // The generated code calls into a relation builder rather than into this 
plan node: a
+    // reference to the node would serialize its child subtrees into every 
task binary.
+    val relationBuilder = ctx.addReferenceObj("relationBuilder", 
createRelationBuilder())

Review Comment:
   **[8] Design: could one generic check cover all the operators?** This PR, 
#60468 and #60475 each fix one operator and add one test for it. Together they 
remove the remaining `ctx.addReferenceObj("plan", this)` calls on master 
(`SortExec`, `HashAggregateExec`, `SortMergeJoinExec`, `SortMergeAsOfJoinExec` 
and this one). But nothing stops a new operator or a refactoring from adding 
such a reference again, unless it also adds its own test. Could 
`WholeStageCodegenExec` check under `Utils.isTesting` that `ctx.references` 
holds no `SparkPlan`, in a follow-up after the three PRs? That would cover 
every operator with one check instead of three tests and three helpers.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -563,6 +566,72 @@ class WholeStageCodegenSuite extends SharedSparkSession
     }
   }
 
+  test("SPARK-61668: ShuffledHashJoin codegen references do not serialize plan 
nodes") {
+    // What a codegen stage adds to the task binary (its closure, with the 
references of the
+    // generated code) is serialized into every task. A plan node in it would 
drag its whole child
+    // subtrees along, through the exchanges below the join.
+    def serializedPlanNodes(stage: WholeStageCodegenExec): Seq[String] = {
+      // Serialize the RDD that the stage adds on top of its input RDDs, as 
the task binary does:
+      // its closure or evaluator factory with the generated code references. 
The input RDDs are
+      // not followed, since they belong to the operators below this stage.
+      val rdd = stage.execute()
+      val planNodes = mutable.ArrayBuffer[String]()
+      val out = new ObjectOutputStream(new ByteArrayOutputStream()) {

Review Comment:
   **[7] Nit: the serialized bytes are buffered but never read.** If a 
regression comes back, the whole plan subtree is kept in the 
`ByteArrayOutputStream`, and `out.close()` is skipped when `writeObject` 
throws. SparkPlanSuite.scala:85 already uses `OutputStream.nullOutputStream()` 
with `try`/`finally`. Could this follow it?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ShuffledHashJoinExec.scala:
##########
@@ -679,3 +678,45 @@ object ShuffledHashJoinExec {
       isSkewJoin)
   }
 }
+
+/**
+ * Builds the [[HashedRelation]] of the build side of a 
[[ShuffledHashJoinExec]] in each task.
+ *
+ * The generated code of the join references this builder, and the references 
of the generated
+ * code are serialized into every task binary. So it holds only what building 
the relation needs,
+ * not the plan node, whose child subtrees (through the exchanges below the 
join) would otherwise
+ * be serialized and deserialized by every task.
+ *
+ * @param buildBoundKeys the build-side join keys, bound to the build-side 
output.
+ * @param allowsNullKey whether the relation must support null keys 
(build-side outer and full
+ *                      outer joins).
+ * @param ignoresDuplicatedKey whether the relation keeps only the first row 
of each key.
+ */
+private[joins] class ShuffledHashJoinRelationBuilder(
+    buildBoundKeys: Seq[Expression],
+    allowsNullKey: Boolean,
+    ignoresDuplicatedKey: Boolean) extends Serializable {
+
+  /**
+   * Builds the relation from the build-side rows of the current task, and 
closes it when the task
+   * completes. Called by the generated code, so it must be public.

Review Comment:
   **[11] Nit: the same reason is written in three places.** The scaladoc at 
L100-104, the comment at L368-369 and the class scaladoc at L682-688 all 
explain that a reference to the node would serialize its child subtrees. Also, 
`build` is called by `doExecute` at L121 too, so "Called by the generated code" 
is only half of it. Could the reason stay only in the class scaladoc, and L702 
mention both callers?



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