cloud-fan commented on code in PR #57952:
URL: https://github.com/apache/spark/pull/57952#discussion_r3767957606
##########
python/pyspark/worker.py:
##########
@@ -2199,6 +2212,96 @@ def grouped_func(
# profiling is not supported for UDF
return grouped_func, None, ser, ser
+ if eval_type ==
PythonEvalType.SQL_GROUPED_AGG_ARROW_INCREMENTAL_PARTIAL_UDF:
+ import pyarrow as pa
+
+ # Map-side PARTIAL stage: fold each group's input rows into a
per-group buffer via the
+ # aggregator's `reduce`, and emit one intermediate-buffer struct
column per aggregator.
+ # `udf_func` is the Aggregator object itself (see read_single_udf).
+ return_schema = to_arrow_schema(
+ StructType(
+ [StructField("_%d" % i, agg.bufferSchema) for i, (agg, _, _,
_) in enumerate(udfs)]
+ ),
+ timezone="UTC",
+ prefers_large_types=runner_conf.use_large_var_types,
+ )
+ col_names = ["_%d" % i for i in range(len(udfs))]
+
+ def grouped_func(
+ split_index: int, data: Iterator["GroupedBatch"]
+ ) -> Iterator[pa.RecordBatch]:
+ for group in data:
+ batch_list = list(group)
Review Comment:
**Blocking:**
The partial stage still materializes every Arrow batch for the group before
`reduce` runs, so a skewed group retains the same whole-group peak memory that
this API is meant to avoid. Please fold each incoming batch directly into the
per-aggregator buffers and retain only those buffers.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/PythonIncrementalAggregateExec.scala:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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.python
+
+import java.io.File
+
+import scala.collection.mutable.ArrayBuffer
+
+import org.apache.spark.{JobArtifactSet, SparkEnv, TaskContext}
+import org.apache.spark.api.python.{ChainedPythonFunctions, PythonEvalType}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.plans.physical.{AllTuples,
ClusteredDistribution, Distribution, Partitioning, UnspecifiedDistribution}
+import org.apache.spark.sql.execution.{GroupedIterator, SparkPlan,
UnaryExecNode}
+import org.apache.spark.sql.execution.python.EvalPythonExec.ArgumentMetadata
+import org.apache.spark.sql.types.{DataType, StructField, StructType}
+import org.apache.spark.util.Utils
+
+/**
+ * Shared execution logic for the two stages of an incremental Python
aggregation (see
+ * [[org.apache.spark.sql.catalyst.expressions.PythonAggregate]]). Both stages
group the child rows
+ * by the grouping expressions, send each group's projected input columns to
the Python worker as
+ * Arrow record batches, and join the single result row the worker returns per
group back with the
+ * grouping key.
+ *
+ * The two stages differ only in:
+ * - which columns are sent to Python (`udfInputs`): the aggregator
arguments in the PARTIAL
+ * stage, the intermediate buffer columns in the FINAL stage;
+ * - the Python eval type, which selects `reduce`-into-buffer vs.
`merge`+`finish` in the worker;
+ * - the required child distribution (map-side/local for PARTIAL, clustered
for FINAL);
+ * - the output attributes and the final projection.
+ */
+abstract class PythonIncrementalAggregateExecBase extends UnaryExecNode with
PythonSQLMetrics {
+
+ def groupingExpressions: Seq[NamedExpression]
+ def aggExpressions: Seq[AggregateExpression]
+
+ protected val udfExpressions: Seq[PythonAggregate] =
+ aggExpressions.map(_.aggregateFunction.asInstanceOf[PythonAggregate])
+
+ /** The Python eval type for this stage. */
+ protected def evalType: Int
+
+ /** Per-UDF input expressions to project out of the child and send to the
Python worker. */
+ protected def udfInputs: Seq[Seq[Expression]]
+
+ /** Attributes of the row the Python worker returns per group (right side of
the join). */
+ protected def pythonOutputAttributes: Seq[Attribute]
+
+ /** Expressions producing this operator's output from (groupingKey ++
pythonOutput). */
+ protected def outputExpressions: Seq[NamedExpression]
+
+ /** The grouping attributes as seen in the child's output. */
+ protected def groupingAttributes: Seq[Attribute] =
groupingExpressions.map(_.toAttribute)
+
+ override def output: Seq[Attribute] = outputExpressions.map(_.toAttribute)
+
+ override def producedAttributes: AttributeSet = AttributeSet(output)
+
+ override def requiredChildOrdering: Seq[Seq[SortOrder]] =
+ Seq(groupingExpressions.map(SortOrder(_, Ascending)))
+
+ override protected def doExecute(): RDD[InternalRow] = {
+ val inputRDD = child.execute()
+
+ val sessionLocalTimeZone = conf.sessionLocalTimeZone
+ val largeVarTypes = conf.arrowUseLargeVarTypes
+ val pythonRunnerConf = ArrowPythonRunner.getPythonRunnerConfMap(conf)
+
+ val pyFuncs = udfExpressions.map { u =>
+ (ChainedPythonFunctions(Seq(u.func)), u.resultId.id)
+ }
+
+ // Filter child output attributes down to only those that are UDF inputs,
and eliminate
+ // duplicates, mirroring ArrowAggregatePythonExec.
+ val allInputs = new ArrayBuffer[Expression]
+ val dataTypes = new ArrayBuffer[DataType]
+ val argMetas = udfInputs.map { input =>
+ input.map { e =>
+ val (key, value) = e match {
+ case NamedArgumentExpression(key, value) => (Some(key), value)
+ case _ => (None, e)
+ }
+ if (allInputs.exists(_.semanticEquals(value))) {
+ ArgumentMetadata(allInputs.indexWhere(_.semanticEquals(value)), key)
+ } else {
+ allInputs += value
+ dataTypes += value.dataType
+ ArgumentMetadata(allInputs.length - 1, key)
+ }
+ }.toArray
+ }.toArray
+
+ val aggInputSchema = StructType(dataTypes.zipWithIndex.map { case (dt, i)
=>
+ StructField(s"_$i", dt)
+ }.toArray)
+
+ val jobArtifactUUID = JobArtifactSet.getCurrentJobArtifactState.map(_.uuid)
+ val sessionUUID = Option(session).collect {
+ case s if s.sessionState.conf.pythonWorkerLoggingEnabled => s.sessionUUID
+ }
+
+ val groupingExprs = groupingExpressions
+ val childOutput = child.output
+ val joinedAttributes = groupingAttributes ++ pythonOutputAttributes
+ val resultExprs = outputExpressions
+ val localEvalType = evalType
+
+ inputRDD.mapPartitionsInternal { iter => if (iter.isEmpty) iter else {
Review Comment:
**Blocking:**
This shortcut drops empty global aggregations before Python can apply `zero`
and `finish`, so `df.limit(0).agg(udaf(...))` returns no row instead of the
aggregate's identity result. Please emit an identity partial buffer for the
no-group empty-input case and cover it with a focused test.
--
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]