viirya commented on code in PR #60551:
URL: https://github.com/apache/spark/pull/60551#discussion_r4606126803
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkOptimizer.scala:
##########
@@ -120,6 +121,7 @@ class SparkOptimizer(
ExtractGroupingPythonUDFFromAggregate,
ExtractPythonUDFs,
ExtractPythonUDTFs,
+ ExtractColumnarUDFs,
Review Comment:
This was addressed in 7cc0a6c1314 and 9389e35888c: a call is kept out of
partition filters (`PruneFileSourcePartitions`, `PruneHiveTablePartitions`,
`FileScanBuilder.pushFilters`, `PushDownUtils`), of the creation side of a
runtime filter, of a standalone DPP subquery, and of the lookup stage of an
external lookup join. There are tests for a partition column with DSv1 and
DSv2, for the bloom filter, and for DPP.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/ExtractColumnarUDFs.scala:
##########
@@ -0,0 +1,225 @@
+/*
+ * 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.columnar.udf
+
+import scala.collection.mutable
+
+import org.apache.spark.SparkException
+import org.apache.spark.internal.LogKeys.JOIN_CONDITION
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.plans.InnerLike
+import org.apache.spark.sql.catalyst.plans.logical.{Aggregate,
EvalColumnarUDFs, Filter, Join, LogicalPlan, Project, Subquery}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.{AGGREGATE,
COLUMNAR_UDF, JOIN}
+import org.apache.spark.sql.errors.QueryCompilationErrors
+
+/**
+ * Extracts the calls of columnar user-defined functions from the operators
and evaluates them
+ * in an [[EvalColumnarUDFs]] below the operator, as `ExtractPythonUDFs` does
for Python UDFs.
+ *
+ * The calls of one operator that need no other call share an
[[EvalColumnarUDFs]]. A call whose
+ * argument is another call gets its own, above that of its argument. An
argument that is not
+ * an attribute is computed by a [[Project]] below, so that the arguments of
the calls in an
+ * [[EvalColumnarUDFs]] are all columns of its child.
+ *
+ * Two kinds of calls cannot be evaluated below their operator, and are moved
above it first,
+ * as `ExtractPythonUDFFromJoinCondition` and `ExtractPythonUDFFromAggregate`
do:
+ * - a call in a join condition that reads both sides of the join is moved to
a [[Filter]]
+ * above the join, which is possible for an inner join only;
+ * - a call in the result of an [[Aggregate]] that reads aggregate functions
or grouping
+ * expressions, or no column at all, is moved to a [[Project]] above the
aggregate.
+ */
+object ExtractColumnarUDFs extends Rule[LogicalPlan] with PredicateHelper {
+
+ def apply(plan: LogicalPlan): LogicalPlan = plan match {
+ // A correlated subquery is rewritten into a join later, and goes through
this rule then.
+ case s: Subquery if s.correlated => plan
+
+ case _ if !plan.containsPattern(COLUMNAR_UDF) => plan
+
+ case _ =>
+ val prepared = extractFromAggregate(extractFromJoinCondition(plan))
+ prepared.transformUpWithPruning(_.containsPattern(COLUMNAR_UDF)) {
+ case e: EvalColumnarUDFs => e
+ case p: LogicalPlan => extract(p)
+ }
+ }
+
+ private def hasColumnarUDF(e: Expression): Boolean =
e.containsPattern(COLUMNAR_UDF)
+
+ //
---------------------------------------------------------------------------------------
+ // Calls in a join condition that read both sides
+ //
---------------------------------------------------------------------------------------
+
+ private def hasUDFOverBothSides(e: Expression, join: Join): Boolean =
e.exists {
+ case udf: ColumnarUDF => !canEvaluate(udf, join.left) && !canEvaluate(udf,
join.right)
+ case _ => false
+ }
+
+ private def extractFromJoinCondition(plan: LogicalPlan): LogicalPlan = {
Review Comment:
This was addressed in 7cc0a6c1314: `canEvaluateWithinJoin` accepts a
`ColumnarUDF` as it does a `PythonUDF`. af8e4337779 extends the join key test
with the three-way join from this comment.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ColumnarUDF.scala:
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.catalyst.expressions
+
+import org.apache.spark.sql.catalyst.trees.TreePattern.{COLUMNAR_UDF,
TreePattern}
+import org.apache.spark.sql.columnar.{ColumnarScalarFunction,
ColumnarUDFImplementation}
+import org.apache.spark.sql.types.{AbstractDataType, DataType}
+
+/**
+ * A call of a columnar user-defined function: a scalar function that is
evaluated one batch at
+ * a time, by the `EvalColumnarUDFs` operator that `ExtractColumnarUDFs` plans
for it.
+ *
+ * A function has any number of implementations. Spark can run `function`, in
the JVM. The
+ * others, `engineImplementations`, are for engines that replace Spark's
operators, and Spark
+ * only carries them. A function without `function` fails when Spark has to
run it.
+ *
+ * @param name the name of the function
+ * @param function the implementation that Spark runs, if there is one
+ * @param engineImplementations the implementations for other engines
+ * @param inputTypes the types of the arguments, which the analyzer casts the
arguments to
+ * @param dataType the type of the result
+ * @param children the arguments
+ * @param udfDeterministic whether the function returns the same result for
the same arguments
+ * @param udfNullable whether the function can return null
+ * @param resultId the id of the call, which tells two calls of a function
that is not
+ * deterministic apart
+ */
+case class ColumnarUDF(
+ name: String,
+ function: Option[ColumnarScalarFunction],
+ engineImplementations: Seq[ColumnarUDFImplementation],
+ inputTypes: Seq[AbstractDataType],
+ dataType: DataType,
+ children: Seq[Expression],
+ udfDeterministic: Boolean = true,
+ udfNullable: Boolean = true,
+ resultId: ExprId = NamedExpression.newExprId)
+ extends Expression with Unevaluable with ImplicitCastInputTypes {
+
+ override lazy val deterministic: Boolean = udfDeterministic &&
children.forall(_.deterministic)
Review Comment:
`expensive` was overridden in 7cc0a6c1314. The `PhysicalOperation` guard was
still missing, and it mattered: over a Parquet scan,
`PruneFileSourcePartitions` collected the filter through the projection before
the extraction and the call was evaluated twice. af8e4337779 makes the guard
recognize a columnar call, and the test now also covers Parquet with DSv1 and
DSv2.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ColumnarUDF.scala:
##########
@@ -0,0 +1,73 @@
+/*
+ * 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.catalyst.expressions
+
+import org.apache.spark.sql.catalyst.trees.TreePattern.{COLUMNAR_UDF,
TreePattern}
+import org.apache.spark.sql.columnar.{ColumnarScalarFunction,
ColumnarUDFImplementation}
+import org.apache.spark.sql.types.{AbstractDataType, DataType}
+
+/**
+ * A call of a columnar user-defined function: a scalar function that is
evaluated one batch at
+ * a time, by the `EvalColumnarUDFs` operator that `ExtractColumnarUDFs` plans
for it.
+ *
+ * A function has any number of implementations. Spark can run `function`, in
the JVM. The
+ * others, `engineImplementations`, are for engines that replace Spark's
operators, and Spark
+ * only carries them. A function without `function` fails when Spark has to
run it.
+ *
+ * @param name the name of the function
+ * @param function the implementation that Spark runs, if there is one
+ * @param engineImplementations the implementations for other engines
+ * @param inputTypes the types of the arguments, which the analyzer casts the
arguments to
+ * @param dataType the type of the result
+ * @param children the arguments
+ * @param udfDeterministic whether the function returns the same result for
the same arguments
+ * @param udfNullable whether the function can return null
+ * @param resultId the id of the call, which tells two calls of a function
that is not
+ * deterministic apart
+ */
+case class ColumnarUDF(
+ name: String,
+ function: Option[ColumnarScalarFunction],
+ engineImplementations: Seq[ColumnarUDFImplementation],
+ inputTypes: Seq[AbstractDataType],
+ dataType: DataType,
+ children: Seq[Expression],
+ udfDeterministic: Boolean = true,
+ udfNullable: Boolean = true,
+ resultId: ExprId = NamedExpression.newExprId)
+ extends Expression with Unevaluable with ImplicitCastInputTypes {
Review Comment:
This was addressed in 7cc0a6c1314: `ColumnarUDF` is a
`UserDefinedExpression`. There are tests for a nondeterministic call in
grouping and sort keys; af8e4337779 adds one for a qualified FILE result type
in `registerColumnar`.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/EvalColumnarUDFsExec.scala:
##########
@@ -0,0 +1,165 @@
+/*
+ * 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.columnar.udf
+
+import org.apache.spark.{SparkException, SparkRuntimeException,
SparkUnsupportedOperationException, TaskContext}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet,
BindReferences, BoundReference, ColumnarUDF, SortOrder}
+import org.apache.spark.sql.catalyst.plans.logical.{EvalColumnarUDFs,
LogicalPlan}
+import org.apache.spark.sql.catalyst.plans.physical.Partitioning
+import org.apache.spark.sql.catalyst.util.TypeUtils.toSQLType
+import org.apache.spark.sql.columnar.ColumnarScalarFunction
+import org.apache.spark.sql.execution.{SparkPlan, SparkStrategy, UnaryExecNode}
+import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics}
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnVector}
+
+/** Plans the evaluation of columnar user-defined functions. */
+object ColumnarUDFEvals extends SparkStrategy {
+ override def apply(plan: LogicalPlan): Seq[SparkPlan] = plan match {
+ case EvalColumnarUDFs(udfs, resultAttrs, child) =>
+ EvalColumnarUDFsExec(udfs, resultAttrs, planLater(child)) :: Nil
+ case _ => Nil
+ }
+}
+
+/**
+ * Evaluates calls of columnar user-defined functions, one batch at a time.
The input and the
+ * output are columnar: an output batch is the columns of the input batch, as
they are, followed
+ * by one column per call. The arguments of the calls are columns of the child.
+ *
+ * This node runs the implementation of each function that Spark can run, its
+ * [[ColumnarScalarFunction]]. An engine that replaces Spark's operators can
replace this node
+ * with one that runs another implementation, from
`ColumnarUDF.engineImplementations`. A
+ * function that Spark cannot run fails only when this node is executed, so
that such an engine
+ * has replaced the node by then.
+ */
+case class EvalColumnarUDFsExec(
+ udfs: Seq[ColumnarUDF],
+ resultAttrs: Seq[Attribute],
+ child: SparkPlan) extends UnaryExecNode {
+
+ override def output: Seq[Attribute] = child.output ++ resultAttrs
+
+ override def producedAttributes: AttributeSet = AttributeSet(resultAttrs)
+
+ override def outputPartitioning: Partitioning = child.outputPartitioning
+
+ override def outputOrdering: Seq[SortOrder] = child.outputOrdering
+
+ override def supportsColumnar: Boolean = true
+
+ override lazy val metrics: Map[String, SQLMetric] = Map(
+ "numOutputRows" -> SQLMetrics.createMetric(sparkContext, "number of output
rows"),
+ "numOutputBatches" -> SQLMetrics.createMetric(sparkContext, "number of
output batches"),
+ "evalTime" -> SQLMetrics.createNanoTimingMetric(sparkContext, "time in
functions"))
+
+ override protected def doExecute(): RDD[InternalRow] = {
+ throw SparkException.internalError(s"$nodeName only supports columnar
execution.")
+ }
+
+ override protected def doExecuteColumnar(): RDD[ColumnarBatch] = {
+ val functions: Array[ColumnarScalarFunction] = udfs.map { udf =>
+ udf.function.getOrElse {
+ throw new SparkUnsupportedOperationException(
+ errorClass = "COLUMNAR_UDF_NOT_EXECUTABLE",
+ messageParameters = Map(
+ "name" -> udf.name,
+ "kinds" -> udf.engineImplementations.map(_.kind).mkString("[", ",
", "]")))
+ }
+ }.toArray
+ // The ordinals, in the input batch, of the arguments of each call.
+ val argOrdinals: Array[Array[Int]] = udfs.map { udf =>
+ udf.children.map { arg =>
+ BindReferences.bindReference(arg, child.output) match {
+ case b: BoundReference => b.ordinal
+ case other => throw SparkException.internalError(
+ s"The argument $other of ${udf.name} is not a column of the
child.")
+ }
+ }.toArray
+ }.toArray
+ val names: Array[String] = udfs.map(_.name).toArray
+ val resultTypes: Array[DataType] = udfs.map(_.dataType).toArray
+ val numOutputRows = longMetric("numOutputRows")
+ val numOutputBatches = longMetric("numOutputBatches")
+ val evalTime = longMetric("evalTime")
+ val numInputColumns = child.output.length
+
+ child.executeColumnar().mapPartitionsInternal { batches =>
+ new Iterator[ColumnarBatch] {
+ // The results of the current batch, which this node owns.
+ private var results: Array[ColumnVector] = Array.empty
+
+ private def closeResults(): Unit = {
+ results.foreach(r => if (r != null) r.close())
Review Comment:
Since 7cc0a6c1314 the node fails with `COLUMNAR_UDF_RESULT_IS_ARGUMENT` when
a function returns one of its argument columns, before anything is closed. I
kept an error rather than skipping the close: a result that aliases the child's
vector is only valid until the child's next batch, and an engine that replaces
the node would have to follow the same exception to the ownership rule.
af8e4337779 extends the check to the fields of a struct argument, at any depth,
and the Javadoc now says that the result must share no memory with the
arguments. The element vectors of arrays and maps cannot be reached through the
public `ColumnVector` API, so for those the Javadoc is the only guard.
##########
sql/catalyst/src/main/java/org/apache/spark/sql/columnar/ColumnarScalarFunction.java:
##########
@@ -0,0 +1,55 @@
+/*
+ * 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.columnar;
+
+import java.io.Serializable;
+
+import org.apache.spark.annotation.Evolving;
+import org.apache.spark.sql.vectorized.ColumnVector;
+import org.apache.spark.sql.vectorized.ColumnarBatch;
+
+/**
+ * A scalar function that Spark evaluates one batch at a time, in the JVM. It
is the
+ * implementation of a columnar user-defined function that Spark itself can
run; an engine that
+ * replaces Spark's operators can run another implementation of the same
function instead, see
+ * {@link ColumnarUDFImplementation}.
+ * <p>
+ * Spark serializes the function to the executors, where each task gets its
own instance and
Review Comment:
Right. I confirmed it with nested calls of a function that counts its rows:
the outer call continued the count of the inner one. af8e4337779 serializes the
functions once on the driver and deserializes them in each partition iterator,
so each node has its own instances in each task; the calls of one node still
share an instance. The Javadoc states this, and there is a test for it. The
test covers the sharing, not two threads calling at once.
--
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]