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


##########
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:
   Fixed in 7cc0a6c1314. `ColumnarUDF` now extends `UserDefinedExpression`. 
Added tests that a call of a function that is not deterministic works in 
grouping and sort keys, and that 
`StoredExpressionFunctions.findUserDefinedFunctionCall` finds a call.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkOptimizer.scala:
##########
@@ -120,6 +121,7 @@ class SparkOptimizer(
         ExtractGroupingPythonUDFFromAggregate,
         ExtractPythonUDFs,
         ExtractPythonUDTFs,
+        ExtractColumnarUDFs,

Review Comment:
   Fixed in 7cc0a6c1314. A filter with a `ColumnarUDF` is no longer a partition 
filter in `PruneFileSourcePartitions`, `PruneHiveTablePartitions`, 
`FileScanBuilder.pushFilters` and `PushDownUtils`, the same places that exclude 
`PythonUDF`. The new test filters on a call over a partition column with both 
the DSv1 and the DSv2 Parquet source.
   



##########
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:
   Fixed in 7cc0a6c1314. `InjectRuntimeFilter` gives up on a creation side with 
`COLUMNAR_UDF`, and a call is not a simple expression. The test has a control 
query without the call that does get a bloom filter, and checks that the same 
query with the call gets none and returns the right rows.
   



##########
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:
   Fixed in 7cc0a6c1314. `PrepareExternalLookupJoin` treats a `ColumnarUDF` 
over lookup columns as it does a Python UDF: it becomes a `Filter` above an 
inner join, and other join types fail with the same error as a regular join. I 
also added `ColumnarUDF` to 
`ExternalLookupJoinShapes.canEvaluateInLookupStage`, which had the same gap. 
Test added to `PrepareExternalLookupJoinSuite`.
   



##########
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:
   Fixed in 7cc0a6c1314. The operator now checks, before it takes ownership of 
a result, that the vector is not one of the columns of the input batch, and 
fails with the new `COLUMNAR_UDF_RESULT_IS_ARGUMENT` otherwise. The check is 
against all the input columns, not only the arguments of that call, since the 
batch that a function gets holds only its arguments but they are the vectors of 
the child. The Javadoc of `eval` now says that the result must be a vector of 
the function's own.
   



##########
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:
   Fixed in 7cc0a6c1314. The error no longer calls `sql` on an `ExistenceJoin` 
and reports it as `EXISTENCE`. I renamed the condition to 
`UNSUPPORTED_FEATURE.COLUMNAR_UDF_IN_JOIN_CONDITION`, and the message says that 
the condition is the ON clause or the correlated predicate of an `EXISTS` or 
`IN` subquery. Tests cover `EXISTS` (LEFT SEMI) and `OR EXISTS` (existence 
join).
   



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