dongjoon-hyun commented on code in PR #60551:
URL: https://github.com/apache/spark/pull/60551#discussion_r4593583041
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkOptimizer.scala:
##########
@@ -120,6 +121,7 @@ class SparkOptimizer(
ExtractGroupingPythonUDFFromAggregate,
ExtractPythonUDFs,
ExtractPythonUDTFs,
+ ExtractColumnarUDFs,
Review Comment:
**[16] The partition pruning rules that run before this rule evaluate a call
in a partition filter.** `PruneFileSourcePartitions` is in
`earlyScanPushDownRules`, before this batch, and drops only the filters with a
Python UDF (PruneFileSourcePartitions.scala L66-69, "Python UDFs might exist
because this rule is applied before `ExtractPythonUDFs`"). So for a partitioned
catalog table `t` with partition column `p`, `SELECT * FROM t WHERE add_one(p)
= 2` passes `add_one(p) = 2` to `catalogFileIndex.filterPartitions`, which
evaluates it with an `InterpretedPredicate`, and the `Unevaluable`
`ColumnarUDF` fails with an INTERNAL_ERROR (`Cannot evaluate expression`).
`PruneHiveTablePartitions` (L60), `FileScanBuilder.pushFilters` (L78) and
`PushDownUtils.isPushablePartitionFilter` (L657) have the same Python-only
check. Could these exclude columnar UDFs too, with a test over a partitioned
table?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/trees/TreePatterns.scala:
##########
@@ -38,6 +38,7 @@ object TreePattern extends Enumeration {
val CAST: Value = Value
val CAST_TO_TIMESTAMP: Value = Value
val COALESCE: Value = Value
+ val COLUMNAR_UDF: Value = Value
Review Comment:
**[17] `InjectRuntimeFilter` can put a call in a bloom filter subquery,
where it is never extracted.** InjectRuntimeFilter.scala L85-89 gives up on a
creation side with `PYTHON_UDF`, because runtime filters are introduced after
subquery optimization, so a Python UDF in the new subquery cannot be extracted
into its operator. The same holds for a columnar UDF, but the check does not
look for `COLUMNAR_UDF`, and `isSimpleExpression` (L258-261) does not exclude
it either, so a filter with a call counts as selective. When a bloom filter is
injected for a shuffle join (e.g. with
`spark.sql.autoBroadcastJoinThreshold=-1`) whose small side has `WHERE
add_one(v) = 5`, the subquery keeps `Filter(add_one(v) = 5)`, and
`PlanSubqueries` plans it without optimization, so the `FilterExec` fails with
an INTERNAL_ERROR when the subquery runs. Could both checks include
`COLUMNAR_UDF`?
##########
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:
**[15] `ColumnarUDF` does not extend `UserDefinedExpression`, so the rules
that match user-defined functions do not see it.** `ScalaUDF` and the Python
UDFs extend this trait, and these places depend on it:
- `NondeterministicExpressionCollection` (L33), which
`PullOutNondeterministic` uses. For a function with `deterministic = false`,
`df.groupBy(nd(col("id"))).count()` fails with an INTERNAL_ERROR
(`Non-deterministic expression ... should not appear in grouping expression`,
PullOutNondeterministic.scala L49), and `df.orderBy(nd(col("id")))` fails with
`INVALID_NON_DETERMINISTIC_EXPRESSIONS`. Both work with a nondeterministic
Scala UDF.
- `StoredExpressionFunctions.findUserDefinedFunctionCall` (L42), which the
CHECK constraint (constraints.scala L141) and generated column
(CreateTableValidation.scala L111) validations use, so a call of a registered
columnar function is not rejected there, although a write in another session
resolves the name to another function or to none.
- `InMemoryRelation.hasSafeExpressions` (L491) and
`PartitionPruning.isCheaplyRecomputableMaterializedPlan` (L292), which treat
user-defined expressions as opaque.
Could `ColumnarUDF` extend `UserDefinedExpression`, which needs only `name`,
with tests for the first two?
##########
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 = {
+ plan.transformUpWithPruning(_.containsAllPatterns(COLUMNAR_UDF, JOIN)) {
+ case join @ Join(_, _, joinType, Some(condition), _)
Review Comment:
**[18] A call in the condition of an `ExternalLookupJoin` is neither moved
nor rejected.** `PrepareExternalLookupJoin` moves a Python or external UDF over
lookup columns itself, since "the rules that move one out of a join condition
match only Join and run later" (PrepareExternalLookupJoin.scala L119-121): an
inner join evaluates the conjunct in a filter above the join, and other join
types are rejected. `lookupSideUDF` (L351-355) does not look for `ColumnarUDF`,
and this case matches only `Join`. So for an `EXTERNAL_LOOKUP` join with `ON
add(s.x, t.y) = 1`, `extract` throws the INTERNAL_ERROR at L208 (`requires
attributes from more than one child`), and a call over lookup columns alone
puts an `EvalColumnarUDFs` below the lookup side. Could `lookupSideUDF` include
`ColumnarUDF`, with `useColumnarUDFInJoinConditionUnsupportedError` for the
other join types?
##########
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())
+ results = Array.empty
+ }
+
+ Option(TaskContext.get()).foreach(_.addTaskCompletionListener[Unit](_
=> closeResults()))
+
+ override def hasNext: Boolean = {
+ val more = batches.hasNext
+ if (!more) closeResults()
+ more
+ }
+
+ override def next(): ColumnarBatch = {
+ closeResults()
+ val batch = batches.next()
+ val numRows = batch.numRows()
+ val columns = new Array[ColumnVector](numInputColumns +
functions.length)
+ var i = 0
+ while (i < numInputColumns) {
+ columns(i) = batch.column(i)
+ i += 1
+ }
+ val start = System.nanoTime()
+ val newResults = new Array[ColumnVector](functions.length)
+ results = newResults
+ i = 0
+ while (i < functions.length) {
+ val args = new ColumnarBatch(argOrdinals(i).map(batch.column),
numRows)
+ val result = functions(i).eval(args)
+ // Set before the check, so that a vector of the wrong type is
closed as well.
+ newResults(i) = result
Review Comment:
**[19] A function that returns one of its argument columns gets that column
closed.** The type check below accepts any vector of the declared type, so an
identity-like function that returns `args.column(0)` passes, and
`closeResults()` at L123 then closes a column of the child's batch. The
vectorized Parquet reader and `RowToColumnarExec` reuse their vectors for the
next batch (ColumnarEvaluatorFactory.scala L80-84, L96-97), so the next batch
reads a closed vector: an NPE for on-heap vectors, and freed memory for
off-heap ones. The Javadoc of `ColumnarScalarFunction.eval` says that Spark
closes the result and that the function must not use its arguments after it
returns, but not that the result must be a new vector. Could the Javadoc say
so, and could this node reject a result that is one of the argument columns?
##########
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 {
Review Comment:
**[21] A predicate that compares a call with a column of the other side does
not become a join condition, so the join becomes a cartesian product.**
`PredicateHelper.canEvaluateWithinJoin` (predicates.scala L225-229) returns
true for a `PythonUDF`, because it "will be executed by dedicated physical
operator later", and false for any other `Unevaluable`, which includes
`ColumnarUDF`. So for `SELECT * FROM a, b WHERE add_one(a.x) = b.y`,
`PushPredicateThroughJoin` leaves the predicate in a `Filter` above a join
without a condition, and the query runs as a cartesian product (or a broadcast
nested loop join) that evaluates the predicate for every pair of rows.
`ReorderJoin` does the same with an `ON` condition when three or more tables
are joined. With a Python UDF, the predicate becomes an equi-join key, and
`ExtractPythonUDFs` evaluates the call below the left side. Since this rule now
moves a call over both sides out of a join condition, could
`canEvaluateWithinJoin` return true fo
r `ColumnarUDF` as well?
##########
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 = {
+ plan.transformUpWithPruning(_.containsAllPatterns(COLUMNAR_UDF, JOIN)) {
+ case join @ Join(_, _, joinType, Some(condition), _)
+ if hasUDFOverBothSides(condition, join) =>
+ if (!joinType.isInstanceOf[InnerLike]) {
+ // Evaluating a part of the condition after the join changes the
result of a join
+ // that is not an inner join.
+ throw
QueryCompilationErrors.useColumnarUDFInJoinConditionUnsupportedError(joinType)
Review Comment:
**[20] Minor: the error for a join type other than inner can fail itself, or
name a clause that the query does not have.** `RewritePredicateSubquery` runs
before this rule, so a correlated `EXISTS` or `IN` subquery whose condition
calls a function over both sides becomes a semi, anti or existence join with
the call in its condition. For `SELECT * FROM a WHERE a.x > 3 OR EXISTS (SELECT
1 FROM b WHERE add(a.x, b.y) = 1)`, the join is an `ExistenceJoin`, whose `sql`
throws (joinTypes.scala L103-107), so
`useColumnarUDFInJoinConditionUnsupportedError` fails with that
`SparkUnsupportedOperationException` instead of `COLUMNAR_UDF_IN_ON_CLAUSE`.
Without the `OR`, the message names "the ON clause of a LEFT SEMI JOIN", which
the query does not have. Could the error handle these join types, with a test
for a correlated subquery?
##########
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)
+
+ override def nullable: Boolean = udfNullable
Review Comment:
**[22] `expensive` is not overridden, so a filter over the alias of a call
is pushed below the `Project`, and the call is evaluated twice.** `ScalaUDF`
(L1224) and the Python UDFs (PythonUDF.scala L314) declare `override def
expensive: Boolean = true`. With `spark.sql.optimizer.avoidDoubleFilterEval`
(default true), `PushPredicateThroughNonJoin` pushes a condition below a
`Project` when the aliases it reads are not expensive (Optimizer.scala L2711),
so for `df.select(addOne(col("id")).as("r")).filter(col("r") > 5)`,
`Filter(add_one(id) > 5)` goes below `Project(add_one(id) AS r)`. They are
different operators, so `ExtractColumnarUDFs` plans an `EvalColumnarUDFs` for
each, and the function runs again for every row that passes the filter. Could
`ColumnarUDF` override `expensive` too, with a test that checks there is one
`EvalColumnarUDFs`?
##########
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)
Review Comment:
**[23] Nit: `NormalizePlan.normalizeExprIds` does not normalize
`resultId`.** It resets the `resultId` of `PythonUDF`, `PythonUDAF` and
`PythonAggregate` (NormalizePlan.scala L110-115), but not the new
`ColumnarUDF.resultId`, and every call gets a new one from the default value
here. So two plans that differ only in these ids, e.g. the same query analyzed
twice, are not equal in `comparePlans`. Could `normalizeExprIds` reset it too?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/trees/TreePatterns.scala:
##########
@@ -157,6 +158,7 @@ object TreePattern extends Enumeration {
val DESERIALIZE_TO_OBJECT: Value = Value
val DF_DROP_COLUMNS: Value = Value
val DISTINCT_LIKE: Value = Value
+ val EVAL_COLUMNAR_UDF: Value = Value
Review Comment:
**[24] Nit: `EVAL_COLUMNAR_UDF` is not used.**
`EvalColumnarUDFs.nodePatterns` sets it, but no rule checks it.
`EVAL_PYTHON_UDF` is used by `MarkSingleTaskExecution.unsupportedPatterns`
(L68-77), together with `PYTHON_UDF`, because these operators "run user code
whose behavior we should not change". Should columnar UDFs be in that list too?
If not, could this pattern be removed until a rule needs it?
--
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]