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


##########
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:
   Good point. I checked where this can actually change behavior. Stages that 
run in `Final` or `PartialMerge` mode already evaluate `mergeExpressions` on 
the driver during codegen, in `doConsumeWithKeys`. A `Partial` aggregate is 
always planned together with a `Final` aggregate of the same functions, which 
evaluates them as well. The only mode where they were not evaluated on the 
driver before is `Complete`, which `AggUtils` now plans only under 
`spark.sql.execution.bypassPartialAggregation`. There, an aggregate whose 
`mergeExpressions` throws would now fail at codegen. Before this change it 
failed only when a task fell back to sort-based aggregation, which happens as 
soon as any task spills. `AggregateWindowFunction` itself never reaches 
`HashAggregateExec`. I kept the eager evaluation because it is what lets the 
helper avoid carrying the aggregate functions and their input expressions. If 
you think the `Complete` case matters, I can ship the functions only in that 
case and build t
 he merge expressions lazily there.
   



##########
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:
   Thanks. These were only called by the generated code; I found no other 
callers in the repo. After the update below, `createUnsafeJoiner()` stays where 
it was.
   



##########
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:
   Agreed, restored it. Its removal can be a separate change.
   



##########
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:
   Filed two follow-ups. SPARK-61666 covers `SortExec`, `SortMergeJoinExec` and 
`SortMergeAsOfJoinExec`. They need to change together: `SortExec.createSorter` 
writes `rowSorter` on the node, and the joins' `cleanupResources` reach it 
through their children, which works today only because both `plan` references 
deserialize to the same object within a task. SPARK-61668 covers 
`ShuffledHashJoinExec`. The generic guard over all WSCG stages would fail on 
these operators today, so it is planned to land with whichever of the two goes 
in second.
   



##########
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:
   Done. The merge expressions are now bound on the driver, and the helper 
takes only the bound expressions.
   



##########
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:
   Done. Moved it to `object HashAggregateCodegenHelper`; the generated code 
and `HashAggregateExecSuite` now call it there.
   



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