viirya commented on code in PR #60475:
URL: https://github.com/apache/spark/pull/60475#discussion_r4572716723
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala:
##########
@@ -229,4 +204,103 @@ object SortExec {
spillSize += metrics.memoryBytesSpilled - spillSizeBefore
metrics.incPeakExecutionMemory(sorter.getPeakMemoryUsage)
}
+
+ /**
+ * The sorter holders of the [[SortExec]]s that run in the same task as
`plan`: those in its
+ * subtree, but not beyond an [[Exchange]]. A join that releases its
children's resources early
+ * from its generated code (see [[genCleanupSorters]]) references these
instead of its child
+ * plans, so that the plans are not serialized into every task.
+ */
+ private[sql] def sorterHoldersInStage(plan: SparkPlan):
Array[SortExecSorterHolder] = {
+ val holders = mutable.ArrayBuffer[SortExecSorterHolder]()
+ def visit(p: SparkPlan): Unit = p match {
+ case _: Exchange =>
+ case s: SortExec =>
+ holders += s.sorterHolder
+ visit(s.child)
+ case other => other.children.foreach(visit)
+ }
+ visit(plan)
+ holders.toArray
+ }
+
+ /**
+ * Generates the code that closes the sorters of the [[SortExec]]s below
`join`, for a join that
+ * releases its children's resources early. This does in generated code what
+ * `join.cleanupResources()` does, without referencing the plan: only the
sorter holders from
+ * [[sorterHoldersInStage]]. The other plan nodes that override
[[SparkPlan.cleanupResources]]
+ * hold nothing to release in a task.
+ */
+ private[sql] def genCleanupSorters(ctx: CodegenContext, join: SparkPlan):
String = {
Review Comment:
Good point. I went for parity: both the generated and the interpreted sort
merge join (and the generated as-of join) now release the same thing. Operators
expose a serializable `taskResourceCleaner` (a new `SparkPlan` hook, see the
other thread), and the joins release the cleaners of the operators below them
in the stage instead of calling `cleanupResources()` on their children. The
`cleanupResources()` scaladoc now states the contract: early release in a task
goes through `taskResourceCleaner`, so an operator that holds resources in a
task and wants them released early has to provide one; otherwise they are
released when the task completes, on both paths.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala:
##########
@@ -229,4 +204,103 @@ object SortExec {
spillSize += metrics.memoryBytesSpilled - spillSizeBefore
metrics.incPeakExecutionMemory(sorter.getPeakMemoryUsage)
}
+
+ /**
+ * The sorter holders of the [[SortExec]]s that run in the same task as
`plan`: those in its
+ * subtree, but not beyond an [[Exchange]]. A join that releases its
children's resources early
+ * from its generated code (see [[genCleanupSorters]]) references these
instead of its child
+ * plans, so that the plans are not serialized into every task.
+ */
+ private[sql] def sorterHoldersInStage(plan: SparkPlan):
Array[SortExecSorterHolder] = {
Review Comment:
Agreed, done along these lines. `SparkPlan.taskResourceCleaner:
Option[TaskResourceCleaner]` (default `None`) returns a serializable handle
that releases what the operator holds in a task without referencing it;
`SortExec` returns its `SortExecSorterHolder`. `TaskResourceCleaner.inStage`
collects them below an operator up to an `Exchange` (or a leaf such as a query
stage), and `TaskResourceCleaner.genCleanupInStage` generates the release code.
The joins no longer know about `SortExec`.
##########
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") {
Review Comment:
Added "SPARK-61666: sort merge joins release the sorters of their children
early" in `JoinSuite`. It joins a small side with a big one so that the join
stops reading the big side early, reads the join to its end in a task, and
asserts that the task holds no execution memory afterwards. It runs inner,
left/right outer, semi, anti and existence joins with everything generated,
with generated sorts under an interpreted join (`spark.sql.codegen.maxFields`),
and without codegen, each with AQE on and off, plus a generated as-of join.
With `sorterHolder` changed to a `def`, it fails with about 67 MB still held
after the join.
##########
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:
The serialization test now runs with AQE on and off, adds an existence join,
and also checks the operators outside codegen: generated sorts under an
interpreted join (via `maxFields`) and no codegen at all. Covering the
interpreted paths needed a change there too: `SortExec.doExecute`, the
interpreted sort merge join and the concurrent output writer now capture the
holder (or the cleaners) instead of the node, so they no longer ship the plan
either. With this, `sorterHolder` is `@transient`, since nothing in a task
reaches it through the node any more.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala:
##########
@@ -229,4 +204,103 @@ object SortExec {
spillSize += metrics.memoryBytesSpilled - spillSizeBefore
metrics.incPeakExecutionMemory(sorter.getPeakMemoryUsage)
}
+
+ /**
+ * The sorter holders of the [[SortExec]]s that run in the same task as
`plan`: those in its
+ * subtree, but not beyond an [[Exchange]]. A join that releases its
children's resources early
+ * from its generated code (see [[genCleanupSorters]]) references these
instead of its child
+ * plans, so that the plans are not serialized into every task.
+ */
+ private[sql] def sorterHoldersInStage(plan: SparkPlan):
Array[SortExecSorterHolder] = {
+ val holders = mutable.ArrayBuffer[SortExecSorterHolder]()
+ def visit(p: SparkPlan): Unit = p match {
+ case _: Exchange =>
+ case s: SortExec =>
+ holders += s.sorterHolder
+ visit(s.child)
+ case other => other.children.foreach(visit)
+ }
+ visit(plan)
+ holders.toArray
+ }
+
+ /**
+ * Generates the code that closes the sorters of the [[SortExec]]s below
`join`, for a join that
+ * releases its children's resources early. This does in generated code what
+ * `join.cleanupResources()` does, without referencing the plan: only the
sorter holders from
+ * [[sorterHoldersInStage]]. The other plan nodes that override
[[SparkPlan.cleanupResources]]
+ * hold nothing to release in a task.
+ */
+ private[sql] def genCleanupSorters(ctx: CodegenContext, join: SparkPlan):
String = {
+ val holders = ctx.addReferenceObj("sorterHolders",
sorterHoldersInStage(join),
+ s"${classOf[SortExecSorterHolder].getName}[]")
+ s"${classOf[SortExec].getName}.cleanupSorters($holders);"
Review Comment:
Done, no reference and no code when there is nothing to release.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala:
##########
@@ -229,4 +204,103 @@ object SortExec {
spillSize += metrics.memoryBytesSpilled - spillSizeBefore
metrics.incPeakExecutionMemory(sorter.getPeakMemoryUsage)
}
+
+ /**
+ * The sorter holders of the [[SortExec]]s that run in the same task as
`plan`: those in its
+ * subtree, but not beyond an [[Exchange]]. A join that releases its
children's resources early
+ * from its generated code (see [[genCleanupSorters]]) references these
instead of its child
+ * plans, so that the plans are not serialized into every task.
+ */
+ private[sql] def sorterHoldersInStage(plan: SparkPlan):
Array[SortExecSorterHolder] = {
+ val holders = mutable.ArrayBuffer[SortExecSorterHolder]()
+ def visit(p: SparkPlan): Unit = p match {
+ case _: Exchange =>
+ case s: SortExec =>
+ holders += s.sorterHolder
+ visit(s.child)
+ case other => other.children.foreach(visit)
+ }
+ visit(plan)
+ holders.toArray
+ }
+
+ /**
+ * Generates the code that closes the sorters of the [[SortExec]]s below
`join`, for a join that
+ * releases its children's resources early. This does in generated code what
+ * `join.cleanupResources()` does, without referencing the plan: only the
sorter holders from
+ * [[sorterHoldersInStage]]. The other plan nodes that override
[[SparkPlan.cleanupResources]]
+ * hold nothing to release in a task.
+ */
+ private[sql] def genCleanupSorters(ctx: CodegenContext, join: SparkPlan):
String = {
+ val holders = ctx.addReferenceObj("sorterHolders",
sorterHoldersInStage(join),
+ s"${classOf[SortExecSorterHolder].getName}[]")
Review Comment:
Done.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SortExec.scala:
##########
@@ -229,4 +204,103 @@ object SortExec {
spillSize += metrics.memoryBytesSpilled - spillSizeBefore
metrics.incPeakExecutionMemory(sorter.getPeakMemoryUsage)
}
+
+ /**
+ * The sorter holders of the [[SortExec]]s that run in the same task as
`plan`: those in its
+ * subtree, but not beyond an [[Exchange]]. A join that releases its
children's resources early
+ * from its generated code (see [[genCleanupSorters]]) references these
instead of its child
+ * plans, so that the plans are not serialized into every task.
+ */
+ private[sql] def sorterHoldersInStage(plan: SparkPlan):
Array[SortExecSorterHolder] = {
+ val holders = mutable.ArrayBuffer[SortExecSorterHolder]()
+ def visit(p: SparkPlan): Unit = p match {
+ case _: Exchange =>
+ case s: SortExec =>
+ holders += s.sorterHolder
+ visit(s.child)
+ case other => other.children.foreach(visit)
+ }
+ visit(plan)
+ holders.toArray
+ }
+
+ /**
+ * Generates the code that closes the sorters of the [[SortExec]]s below
`join`, for a join that
+ * releases its children's resources early. This does in generated code what
+ * `join.cleanupResources()` does, without referencing the plan: only the
sorter holders from
+ * [[sorterHoldersInStage]]. The other plan nodes that override
[[SparkPlan.cleanupResources]]
+ * hold nothing to release in a task.
+ */
+ private[sql] def genCleanupSorters(ctx: CodegenContext, join: SparkPlan):
String = {
+ val holders = ctx.addReferenceObj("sorterHolders",
sorterHoldersInStage(join),
+ s"${classOf[SortExecSorterHolder].getName}[]")
+ s"${classOf[SortExec].getName}.cleanupSorters($holders);"
+ }
+
+ /** Closes the sorters of `holders`. Called from the code of
[[genCleanupSorters]]. */
+ def cleanupSorters(holders: Array[SortExecSorterHolder]): Unit = {
+ holders.foreach(_.cleanupResources())
+ }
+}
+
+/**
+ * Creates the sorter of a [[SortExec]] and holds it until
[[cleanupResources]]. It holds only what
+ * the sorter needs, not the plan, and is referenced by the generated code of
the [[SortExec]] and
+ * of joins that release the sorter early (see
[[SortExec.sorterHoldersInStage]]).
+ *
+ * WARNING: the sorter is per-task mutable state. Each task deserializes its
own copy of the
+ * holder from the task binary, so it must not be shared across tasks or
accessed from multiple
+ * threads concurrently.
+ */
+private[sql] class SortExecSorterHolder(
+ sortOrder: Seq[SortOrder],
+ output: Seq[Attribute],
+ enableRadixSort: Boolean,
+ testSpillFrequency: Int) extends Serializable {
+
+ @transient private var rowSorter: UnsafeExternalRowSorter = _
+
+ 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(DataTypeUtils.fromAttributes(output), ordering,
Review Comment:
Done, it is a `@transient lazy val` in the holder now.
##########
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:
`sorterHolder` is now `@transient`. Every use in a task captures the holder
on the driver (the generated code, the interpreted sort's closure, the joins'
cleaners, the concurrent writer), so a `SortExec` that another operator still
serializes no longer carries one.
--
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]