dongjoon-hyun commented on code in PR #60468:
URL: https://github.com/apache/spark/pull/60468#discussion_r4569446096
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/HashAggregateExec.scala:
##########
@@ -290,136 +289,17 @@ case class HashAggregateExec(
private var adaptivePassThroughBufferTerm: String = _
/**
- * This is called by generated Java class, should be public.
+ * Creates the helper that the generated code calls at runtime. It holds
only what those calls
+ * need, so the generated code does not reference this plan node and its
child subtree.
*/
- def createHashMap(): UnsafeFixedWidthAggregationMap = {
- // create initialized aggregate buffer
- val initExpr = declFunctions.flatMap(f => f.initialValues)
- val initialBuffer = UnsafeProjection.create(initExpr)(EmptyRow)
-
- // create hashMap
- new UnsafeFixedWidthAggregationMap(
- initialBuffer,
- bufferSchema,
+ private def createCodegenHelper(): HashAggregateCodegenHelper = {
+ new HashAggregateCodegenHelper(
groupingKeySchema,
- TaskContext.get(),
- 1024 * 16, // initial capacity
- TaskContext.get().taskMemoryManager().pageSizeBytes
- )
- }
-
- def getTaskContext(): TaskContext = {
- TaskContext.get()
- }
-
- /**
- * Registers a task-completion hook to close the generated fast hash map, so
that the close hook
- * is a plain method call on this plan, with the listener being a lambda in
compiled Scala code,
- * rather than an anonymous `TaskCompletionListener` emitted per fast hash
map (one fewer
- * generated inner class per map). This is called by the generated Java
class, should be public.
- */
- def addFastHashMapCloseHook(fastHashMap: AutoCloseable): Unit = {
- TaskContext.get().addTaskCompletionListener[Unit](_ => fastHashMap.close())
- }
-
- def getEmptyAggregationBuffer(): InternalRow = {
- val initExpr = declFunctions.flatMap(f => f.initialValues)
- val initialBuffer = UnsafeProjection.create(initExpr)(EmptyRow)
- initialBuffer
- }
-
- /**
- * This is called by generated Java class, should be public.
- */
- def createUnsafeJoiner(): UnsafeRowJoiner = {
Review Comment:
nit. The removal of the unused `createUnsafeJoiner()` is unrelated to the
goal of this PR. It's okay since the PR description mentions it, but it could
be a separate PR.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/HashAggregateExec.scala:
##########
@@ -290,136 +289,17 @@ case class HashAggregateExec(
private var adaptivePassThroughBufferTerm: String = _
/**
- * This is called by generated Java class, should be public.
+ * Creates the helper that the generated code calls at runtime. It holds
only what those calls
+ * need, so the generated code does not reference this plan node and its
child subtree.
*/
- def createHashMap(): UnsafeFixedWidthAggregationMap = {
Review Comment:
FYI, this removes the public methods (`createHashMap`,
`getEmptyAggregationBuffer`, `getTaskContext`, `addFastHashMapCloseHook`,
`finishAggregate` and `createUnsafeJoiner`) from `HashAggregateExec`. MiMa
doesn't report it because of the `org.apache.spark.sql.execution.*` exclusion,
and this is an internal package, so it's fine to me. Just mentioning it in case
some external extensions call them.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/HashAggregateExec.scala:
##########
@@ -612,11 +492,14 @@ case class HashAggregateExec(
case _ => conf.fastHashAggregateRowMaxCapacityBit
}
- val thisPlan = ctx.addReferenceObj("plan", this)
+ // The generated code calls into a helper rather than into this plan node:
a reference to the
+ // node would serialize its whole child subtree into every task binary (see
+ // `HashAggregateCodegenHelper`).
+ val aggHelper = ctx.addReferenceObj("aggHelper", createCodegenHelper())
Review Comment:
Not for this PR, but the same `ctx.addReferenceObj("plan", this)` pattern
still exists in `SortExec` (`createSorter`), `ShuffledHashJoinExec`
(`buildHashedRelation`), `SortMergeJoinExec` and `SortMergeAsOfJoinExec`
(`cleanupResources`). So, in the `sort-merge join + aggregate` benchmark case,
the SMJ stage still serializes its plan subtree into every task. Shall we file
a follow-up JIRA for them? A generic guard (at least in tests) that rejects
`SparkPlan` objects in the codegen references of all WSCG stages would prevent
this pattern from coming back.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/HashAggregateCodegenHelper.scala:
##########
@@ -0,0 +1,177 @@
+/*
+ * 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.aggregate
+
+import org.apache.spark.TaskContext
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.execution.{UnsafeFixedWidthAggregationMap,
UnsafeKVExternalSorter}
+import org.apache.spark.sql.execution.metric.SQLMetric
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.unsafe.KVIterator
+
+/**
+ * The runtime helper that the code generated by [[HashAggregateExec]] calls
into.
+ *
+ * The generated code is shipped to executors together with its `references`,
which are
+ * serialized into every task binary and deserialized by every task.
Referencing the
+ * [[HashAggregateExec]] node itself from the generated code would carry its
whole child plan
+ * subtree (and, after a shuffle, the plan of the previous stage through the
exchange) into
+ * every task, although the methods called at runtime only need schemas and
the aggregate
+ * buffer expressions. This class holds exactly that state and nothing from
the plan tree.
+ *
+ * Like any other reference of the generated code, each task deserializes its
own copy, so
+ * the expressions held here are never shared between tasks. Metrics are not
held here; they
+ * are passed in as arguments by the generated code, which references the
plan's registered
+ * [[SQLMetric]]s directly.
+ *
+ * @param groupingKeySchema the schema of the grouping key rows.
+ * @param bufferSchema the schema of the aggregation buffer rows.
+ * @param initialValues the initial values of the aggregation buffer, one per
buffer slot.
+ * @param mergeExpressions the expressions that merge two aggregation buffers,
used when the
+ * hash map has spilled and the sorted rows of a key
are merged.
+ * @param mergeInputAttributes the input of `mergeExpressions`: the
aggregation buffer
+ * attributes followed by the input aggregation
buffer attributes.
+ */
+private[execution] class HashAggregateCodegenHelper(
+ groupingKeySchema: StructType,
+ bufferSchema: StructType,
+ initialValues: Seq[Expression],
+ mergeExpressions: Seq[Expression],
+ mergeInputAttributes: Seq[Attribute]) extends Serializable {
Review Comment:
nit. Since `mergeInputAttributes` is only used to bind `mergeExpressions`,
we could bind them once on the driver (`bindReferences(mergeExpressions,
mergeInputAttributes)`) and pass only the bound expressions
(`MutableProjection.create(boundMergeExpressions)`). It would drop
`mergeInputAttributes` from every task binary and avoid re-binding in every
task that falls back, which matches the goal of this PR.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/HashAggregateCodegenHelper.scala:
##########
@@ -0,0 +1,177 @@
+/*
+ * 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.aggregate
+
+import org.apache.spark.TaskContext
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.execution.{UnsafeFixedWidthAggregationMap,
UnsafeKVExternalSorter}
+import org.apache.spark.sql.execution.metric.SQLMetric
+import org.apache.spark.sql.types.StructType
+import org.apache.spark.unsafe.KVIterator
+
+/**
+ * The runtime helper that the code generated by [[HashAggregateExec]] calls
into.
+ *
+ * The generated code is shipped to executors together with its `references`,
which are
+ * serialized into every task binary and deserialized by every task.
Referencing the
+ * [[HashAggregateExec]] node itself from the generated code would carry its
whole child plan
+ * subtree (and, after a shuffle, the plan of the previous stage through the
exchange) into
+ * every task, although the methods called at runtime only need schemas and
the aggregate
+ * buffer expressions. This class holds exactly that state and nothing from
the plan tree.
+ *
+ * Like any other reference of the generated code, each task deserializes its
own copy, so
+ * the expressions held here are never shared between tasks. Metrics are not
held here; they
+ * are passed in as arguments by the generated code, which references the
plan's registered
+ * [[SQLMetric]]s directly.
+ *
+ * @param groupingKeySchema the schema of the grouping key rows.
+ * @param bufferSchema the schema of the aggregation buffer rows.
+ * @param initialValues the initial values of the aggregation buffer, one per
buffer slot.
+ * @param mergeExpressions the expressions that merge two aggregation buffers,
used when the
+ * hash map has spilled and the sorted rows of a key
are merged.
+ * @param mergeInputAttributes the input of `mergeExpressions`: the
aggregation buffer
+ * attributes followed by the input aggregation
buffer attributes.
+ */
+private[execution] class HashAggregateCodegenHelper(
Review Comment:
nit. `spillHashMapToSorter` is still in `object HashAggregateExec`, so the
generated code calls the runtime helpers in two places: the spill path calls
the static `HashAggregateExec.spillHashMapToSorter` while the finish path calls
`aggHelper.finishAggregate`. What about moving it into this class (or its
companion object) to keep the runtime helpers together?
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/HashAggregateExec.scala:
##########
@@ -290,136 +289,17 @@ case class HashAggregateExec(
private var adaptivePassThroughBufferTerm: String = _
/**
- * This is called by generated Java class, should be public.
+ * Creates the helper that the generated code calls at runtime. It holds
only what those calls
+ * need, so the generated code does not reference this plan node and its
child subtree.
*/
- def createHashMap(): UnsafeFixedWidthAggregationMap = {
- // create initialized aggregate buffer
- val initExpr = declFunctions.flatMap(f => f.initialValues)
- val initialBuffer = UnsafeProjection.create(initExpr)(EmptyRow)
-
- // create hashMap
- new UnsafeFixedWidthAggregationMap(
- initialBuffer,
- bufferSchema,
+ private def createCodegenHelper(): HashAggregateCodegenHelper = {
+ new HashAggregateCodegenHelper(
groupingKeySchema,
- TaskContext.get(),
- 1024 * 16, // initial capacity
- TaskContext.get().taskMemoryManager().pageSizeBytes
- )
- }
-
- def getTaskContext(): TaskContext = {
- TaskContext.get()
- }
-
- /**
- * Registers a task-completion hook to close the generated fast hash map, so
that the close hook
- * is a plain method call on this plan, with the listener being a lambda in
compiled Scala code,
- * rather than an anonymous `TaskCompletionListener` emitted per fast hash
map (one fewer
- * generated inner class per map). This is called by the generated Java
class, should be public.
- */
- def addFastHashMapCloseHook(fastHashMap: AutoCloseable): Unit = {
- TaskContext.get().addTaskCompletionListener[Unit](_ => fastHashMap.close())
- }
-
- def getEmptyAggregationBuffer(): InternalRow = {
- val initExpr = declFunctions.flatMap(f => f.initialValues)
- val initialBuffer = UnsafeProjection.create(initExpr)(EmptyRow)
- initialBuffer
- }
-
- /**
- * This is called by generated Java class, should be public.
- */
- def createUnsafeJoiner(): UnsafeRowJoiner = {
- GenerateUnsafeRowJoiner.create(groupingKeySchema, bufferSchema)
- }
-
- /**
- * Called by generated Java class to finish the aggregate and return a
KVIterator.
- */
- def finishAggregate(
- hashMap: UnsafeFixedWidthAggregationMap,
- sorter: UnsafeKVExternalSorter,
- peakMemory: SQLMetric,
- spillSize: SQLMetric,
- avgHashProbe: SQLMetric,
- numTasksFallBacked: SQLMetric): KVIterator[UnsafeRow, UnsafeRow] = {
-
- // update peak execution memory
- val mapMemory = hashMap.getPeakMemoryUsedBytes
- val sorterMemory =
Option(sorter).map(_.getPeakMemoryUsedBytes).getOrElse(0L)
- val maxMemory = Math.max(mapMemory, sorterMemory)
- val metrics = TaskContext.get().taskMetrics()
- peakMemory.add(maxMemory)
- metrics.incPeakExecutionMemory(maxMemory)
-
- // Update average hashmap probe
- avgHashProbe.set(hashMap.getAvgHashProbesPerKey)
-
- if (sorter == null) {
- // not spilled
- return hashMap.iterator()
- }
-
- // merge the final hashMap into sorter
- numTasksFallBacked += 1
- sorter.merge(hashMap.destructAndCreateExternalSorter())
- hashMap.free()
- val sortedIter = sorter.sortedIterator()
-
- // Create a KVIterator based on the sorted iterator.
- new KVIterator[UnsafeRow, UnsafeRow] {
-
- // Create a MutableProjection to merge the rows of same key together
- val mergeExpr = declFunctions.flatMap(_.mergeExpressions)
- val mergeProjection = MutableProjection.create(
- mergeExpr,
+ bufferSchema,
+ initialValues = declFunctions.flatMap(_.initialValues),
+ mergeExpressions = declFunctions.flatMap(_.mergeExpressions),
Review Comment:
This makes `mergeExpressions` of every declarative aggregate evaluated
eagerly on the driver at codegen time, even for `Partial`-only stages.
Previously, it was evaluated lazily on the executor only when a task fell back
to the sort-based aggregation. In-tree aggregates are fine, but a third-party
`DeclarativeAggregate` whose `mergeExpressions` is expensive or throws (like
the `AggregateWindowFunction` pattern) would see a behavior change. Is this
intended?
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala:
##########
@@ -381,6 +383,57 @@ class WholeStageCodegenSuite extends SharedSparkSession
assert(df.collect() === Array(Row(0, 1), Row(2, 1), Row(4, 1)))
}
+ test("SPARK-61661: HashAggregate codegen references do not serialize plan
nodes") {
+ // The references of the generated code are serialized into every task
binary. A plan node
+ // among them would drag its whole child subtree along (for the final
aggregate, the whole
+ // map-side plan through the exchange), so the generated code must not
reference one.
+ def serializedPlanNodes(stage: WholeStageCodegenExec): Seq[String] = {
+ 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
+ case _ =>
+ }
+ obj
+ }
+ }
+ out.writeObject(stage.doCodeGen()._1.references.toArray)
Review Comment:
This test checks only `doCodeGen()._1.references`, not what is actually
shipped to the tasks (the `WholeStageCodegenEvaluatorFactory` and the RDD
closure created in `doExecute`). If a future change makes them capture a plan
node, this test will still pass. If it's not too complex, could we check the
serialized evaluator factory or task closure too?
--
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]