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


##########
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:
   Good catch, confirmed: with `k1 = k2 + (SELECT max(id) - 8 FROM range(10))` 
the builder carried `Subquery`, its aggregate stages and the `Range` below 
them. The codegen path now passes the keys through 
`ScalarSubquery.replaceWithLiterals`, like the generated code of the scalar 
subquery itself; `produce` runs after `waitForSubqueries`, so the result is 
ready. Added this case to the test; it fails without the change.



##########
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:
   Agreed. `doExecute` now creates the builder inside the closure, so 
`buildBoundKeys` and `ignoreDuplicatedKey` are computed in the task as before 
and nothing is added to the closure.



##########
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:
   Right, with two inputs and the evaluator off, the stage's own 
`ZippedPartitionsRDD2` was cut too. The helper now cuts only the stage's 
`inputRDDs()`, same as #60475.



##########
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:
   The expected rows now come from the same query without the shuffled hash 
join (`SHUFFLE_MERGE` hint, or without forcing SHJ for the existence and single 
joins), and the test asserts that plan has no `ShuffledHashJoinExec`. Added 
left semi and left anti cases with a key-only condition, asserting 
`ignoreDuplicatedKey` is true there and false in the other semi/anti cases.



##########
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:
   Added the stream-side `right_outer` with `BuildLeft`, and an existence join 
and a left single join, both planned as shuffled hash joins with 
`spark.sql.join.forceApplyShuffledHashJoin` (broadcast off). The test now finds 
the join anywhere in the stage, since those two have a project/filter on top of 
it in the same stage.



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