viirya commented on code in PR #60476:
URL: https://github.com/apache/spark/pull/60476#discussion_r4572715450
##########
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:
Done: the expected rows are computed once per case, and the messages include
`usePartitionEvaluator`.
##########
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:
Done: `OutputStream.nullOutputStream()` and `try`/`finally`.
##########
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:
Agreed, that is the plan: after the three PRs are merged, a follow-up adds
one testing-only check in `WholeStageCodegenExec` that `ctx.references` holds
no `SparkPlan`. It cannot be added before, since it would fail on the operators
not yet fixed.
##########
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:
This PR now uses the same helper as #60475 (cutting only `inputRDDs()`).
Whichever of the three merges later will move it to one suite-level private
helper and resolve the imports.
##########
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:
Done. The builder now takes the two metrics in its constructor (by name),
and `build` takes only the iterator; the generated code no longer adds the two
`metricTerm` references.
##########
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:
Done: the reason is only in the class scaladoc now, and the scaladoc of
`build` mentions both callers.
##########
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()
streamedPlan.execute().zipPartitions(buildPlan.execute()) { (streamIter,
buildIter) =>
- val hashed = buildHashedRelation(buildIter)
+ val hashed = relationBuilder.build(buildIter, buildTime, buildDataSize)
Review Comment:
With the metrics now constructor parameters passed by name, the positional
swap is gone. Also added "SPARK-61668: ShuffledHashJoin build metrics with and
without whole-stage codegen" to `SQLMetricsSuite`: an inner shuffled hash join
run with codegen on and off, asserting `buildTime` was updated and
`buildDataSize` is positive and equal on both paths.
--
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]