dongjoon-hyun commented on code in PR #60551:
URL: https://github.com/apache/spark/pull/60551#discussion_r4623379779


##########
sql/core/src/main/scala/org/apache/spark/sql/classic/UDFRegistration.scala:
##########
@@ -50,6 +51,21 @@ import org.apache.spark.sql.types.DataType
 class UDFRegistration private[sql] (session: SparkSession, functionRegistry: 
FunctionRegistry)
   extends sql.UDFRegistration
   with Logging {
+  /**
+   * Registers a columnar user-defined function under its name, so that SQL 
can call it.
+   *
+   * @since 4.4.0
+   */
+  @Evolving
+  def registerColumnar(udf: ColumnarUserDefinedFunction): 
ColumnarUserDefinedFunction = {
+    // A FILE in the return type cannot have a qualifier.
+    TypeUtils.checkNoQualifierInRegisteredRoutineReturnType(udf.dataType, 
udf.name)

Review Comment:
   **[31] CHAR and VARCHAR in the declared types are neither rejected nor 
replaced.**
   
   This method checks only the qualifier of a FILE return type, and 
`ColumnarUserDefinedFunction.builder` does not check the types at all. The 
other ways to define a function run `failIfHasCharVarchar` on their types: 
`registerJavaUDF` for its return type (`UDFRegistration.scala:117`, in sql/api) 
and SQL functions for their parameters and return type 
(`UserDefinedFunction.scala:94-106`, in catalyst). With the default confs it 
fails, and with `spark.sql.legacy.charVarcharAsString` it replaces CHAR and 
VARCHAR with STRING. The builder of a Python UDF rejects them too 
(`UserDefinedPythonFunction.scala:67-70`).
   
   Here, `ColumnarUserDefinedFunction.create("f", Seq(StringType), 
VarcharType(3), fn)` is registered and called without an error. `VarcharType` 
extends `StringType`, so `fn` can return an `OnHeapColumnVector` of 
`VarcharType(3)` that holds `abcdef`, and the result type check accepts it. The 
call then outputs a `varchar(3)` column whose values nothing checks against the 
length. With both first-class CHAR/VARCHAR confs off, a plan is not supposed to 
have such an output: `CheckAnalysis.scala:458-464` raises an internal error for 
a leaf node that has one. Reading the code, `localCheckpoint()` of such a 
DataFrame builds a `LogicalRDD` with that output, so a query over the 
checkpointed DataFrame would hit that internal error.
   
   Could `builder` apply `CharVarcharUtils.failIfHasCharVarchar` to 
`inputTypes` and `dataType`, and use the types that it returns, as 
`registerJavaUDF` does for its return type, with a test?



##########
sql/core/src/main/scala/org/apache/spark/sql/columnar/ColumnarUserDefinedFunction.scala:
##########
@@ -0,0 +1,203 @@
+/*
+ * 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 org.apache.spark.annotation.Evolving
+import org.apache.spark.sql.Column
+import org.apache.spark.sql.catalyst.expressions.{ColumnarUDF, Expression, 
NamedArgumentExpression}
+import org.apache.spark.sql.classic.ClassicConversions._
+import org.apache.spark.sql.classic.ExpressionUtils.expression
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * A columnar user-defined function: a scalar function that is evaluated one 
batch at a time,
+ * with columnar input and output, by an operator of its own.
+ *
+ * A function has any number of implementations, and whoever provides them 
makes sure that they
+ * return the same results:
+ *  - a `ColumnarScalarFunction` is the one that Spark runs, in the JVM;
+ *  - the `ColumnarUDFImplementation`s are for engines that replace Spark's 
operators, such as
+ *    native engines, which run them with their own operator.
+ *
+ * A function may have no implementation that Spark runs. A query that calls 
it then fails when
+ * Spark has to run the call itself.
+ *
+ * A function is created with `ColumnarUserDefinedFunction.create`, and is not 
changed
+ * afterwards: `withEngineImplementation`, `asNondeterministic` and 
`asNonNullable` return a new
+ * definition.
+ *
+ * A function can be applied to columns, or registered to be called from SQL. 
The registration
+ * is a method of the classic `UDFRegistration`, which is the one of a session 
that runs in the
+ * same JVM as the driver:
+ *
+ * {{{
+ *   val addOne = ColumnarUserDefinedFunction.create("add_one", Seq(LongType), 
LongType, new AddOne)
+ *   df.select(addOne(col("id")))
+ *   
spark.udf.asInstanceOf[org.apache.spark.sql.classic.UDFRegistration].registerColumnar(addOne)
+ *   spark.sql("SELECT add_one(id) FROM t")
+ * }}}
+ *
+ * The operator reads the arguments of a call as columns of its child, and 
evaluates together
+ * the calls of one projection or filter. They are evaluated without leaving 
the columnar
+ * format when the child is columnar and the arguments of all of them are 
columns of it, of the
+ * types that the functions declare. If one argument of one of these calls is 
anything else,
+ * including a column that is cast to the declared type, a row-based 
projection computes it
+ * first, and its output is converted back to columns for all of these calls. 
A row-based
+ * operator below the calls, such as a filter over the scan, has the same 
effect.
+ *
+ * Limitations:
+ *  - Calls with named arguments, and calls inside the lambda function of a 
higher-order
+ *    function, are not supported.
+ *  - A call that reads columns of both sides of a join is supported in the 
condition of an
+ *    inner join only. This includes the joins that correlated EXISTS and IN 
subqueries become.
+ *  - A conditional expression does not guard a call. A call in a branch of 
CASE, IF or
+ *    COALESCE, or on one side of AND or OR, is evaluated for every row, and 
so are the
+ *    expressions that compute its arguments, which can then fail for rows 
that the branch
+ *    would have skipped.
+ *
+ * @since 4.4.0
+ */
+@Evolving
+final class ColumnarUserDefinedFunction private (
+    /** The name of the function. */
+    val name: String,
+    /** The types of the arguments, which the arguments of a call are cast to. 
*/
+    val inputTypes: Seq[DataType],

Review Comment:
   **[34] `inputTypes` is still a Scala `Seq` for Java.**
   
   After b4a14abfbe9, Java creates a function from a `DataType[]`, but reads 
its argument types back as a `scala.collection.immutable.Seq`, which needs the 
Scala collection API (`apply(0)`, `length()` or `CollectionConverters`). That 
is the part of [29] that remains: `JavaColumnarUDFSuite` checks `name()`, 
`dataType()`, `deterministic()` and `nullable()`, but not `inputTypes()`. Could 
there also be an accessor for Java, e.g. one that returns a copy as a 
`DataType[]`, as `StructType.fields` is an array, with a check in 
`JavaColumnarUDFSuite`?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/EvalColumnarUDFsExec.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.util.control.NonFatal
+
+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.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.{SparkPlan, SparkStrategy, UnaryExecNode}
+import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics}
+import org.apache.spark.sql.execution.vectorized.WritableColumnVector
+import org.apache.spark.sql.types.{DataType, StructType, UserDefinedType}
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnVector}
+import org.apache.spark.util.Utils
+
+/** 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 driverFunctions: 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 closures of the nodes of a stage are serialized together, so the 
nodes would share one
+    // instance of a function that several of them call, and an operator 
between them can read
+    // its child from another thread. The functions are serialized apart here, 
so that each
+    // partition of this node reads its own instances, which only this node 
calls.
+    val serializedFunctions: Array[Byte] = Utils.serialize(driverFunctions)
+    // 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 inputTypeStrings: Array[String] =
+      udfs.map(_.children.map(_.dataType.catalogString).mkString(", ")).toArray
+    val resultTypes: Array[DataType] = udfs.map(_.dataType).toArray
+    // A column vector has the SQL type of a user-defined type, so the type of 
a result is
+    // compared with the declared type after the same replacement.
+    val resultVectorTypes: Array[DataType] = 
resultTypes.map(_.transformRecursively {
+      case udt: UserDefinedType[_] => udt.sqlType
+    })
+    val numOutputRows = longMetric("numOutputRows")
+    val numOutputBatches = longMetric("numOutputBatches")
+    val evalTime = longMetric("evalTime")
+    val numInputColumns = child.output.length
+    val numFunctions = udfs.length
+
+    child.executeColumnar().mapPartitionsInternal { batches =>
+      new Iterator[ColumnarBatch] {
+        private val functions = 
Utils.deserialize[Array[ColumnarScalarFunction]](
+          serializedFunctions, Utils.getContextOrSparkClassLoader)
+
+        // 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()))
+
+        // Whether `vector` is `column` or a vector inside it. A writable 
vector, which the
+        // vectorized readers and `RowToColumnarExec` produce, gives its 
children for every
+        // type that has them: the fields of a struct, the elements of an 
array, the keys and
+        // values of a map. Other vectors are only known to give the fields of 
a struct.
+        private def isPartOf(column: ColumnVector, vector: ColumnVector): 
Boolean = {
+          (column eq vector) || (column match {
+            case w: WritableColumnVector =>
+              (0 until w.getNumChildren).exists(i => isPartOf(w.getChild(i), 
vector))
+            case _ => column.dataType() match {
+              case s: StructType =>
+                s.fields.indices.exists(i => isPartOf(column.getChild(i), 
vector))
+              case _ => false
+            }
+          })
+        }
+
+        private def isInputColumn(batch: ColumnarBatch, vector: ColumnVector): 
Boolean = {
+          var i = 0
+          while (i < numInputColumns) {
+            if (isPartOf(batch.column(i), vector)) return true

Review Comment:
   **[35] Minor: the check of a result walks every input column, not only the 
arguments of the calls.**
   
   `isInputColumn` compares the result with every column of the batch, and 
since ac91b552ef4 `isPartOf` also walks every child of a writable vector: the 
element vector of an array, the key and value vectors of a map, and the byte 
vector of a string or a binary. A function gets only the columns of 
`argOrdinals(i)` (L183), so only the argument columns of the calls of this node 
can hold the vector that it returns. Over a wide Parquet scan, e.g. 300 columns 
with arrays, maps and strings, and two calls that read one column each, every 
batch walks every vector of every column twice. This is small next to the work 
per row, but it is done for every batch. Could the check walk only the columns 
that are arguments of a call of this node, e.g. the distinct ordinals of 
`argOrdinals`?



##########
sql/core/src/main/scala/org/apache/spark/sql/columnar/ColumnarUserDefinedFunction.scala:
##########
@@ -0,0 +1,203 @@
+/*
+ * 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 org.apache.spark.annotation.Evolving
+import org.apache.spark.sql.Column
+import org.apache.spark.sql.catalyst.expressions.{ColumnarUDF, Expression, 
NamedArgumentExpression}
+import org.apache.spark.sql.classic.ClassicConversions._
+import org.apache.spark.sql.classic.ExpressionUtils.expression
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * A columnar user-defined function: a scalar function that is evaluated one 
batch at a time,
+ * with columnar input and output, by an operator of its own.
+ *
+ * A function has any number of implementations, and whoever provides them 
makes sure that they
+ * return the same results:
+ *  - a `ColumnarScalarFunction` is the one that Spark runs, in the JVM;
+ *  - the `ColumnarUDFImplementation`s are for engines that replace Spark's 
operators, such as
+ *    native engines, which run them with their own operator.
+ *
+ * A function may have no implementation that Spark runs. A query that calls 
it then fails when
+ * Spark has to run the call itself.
+ *
+ * A function is created with `ColumnarUserDefinedFunction.create`, and is not 
changed
+ * afterwards: `withEngineImplementation`, `asNondeterministic` and 
`asNonNullable` return a new
+ * definition.
+ *
+ * A function can be applied to columns, or registered to be called from SQL. 
The registration
+ * is a method of the classic `UDFRegistration`, which is the one of a session 
that runs in the
+ * same JVM as the driver:
+ *
+ * {{{
+ *   val addOne = ColumnarUserDefinedFunction.create("add_one", Seq(LongType), 
LongType, new AddOne)
+ *   df.select(addOne(col("id")))
+ *   
spark.udf.asInstanceOf[org.apache.spark.sql.classic.UDFRegistration].registerColumnar(addOne)
+ *   spark.sql("SELECT add_one(id) FROM t")
+ * }}}
+ *
+ * The operator reads the arguments of a call as columns of its child, and 
evaluates together
+ * the calls of one projection or filter. They are evaluated without leaving 
the columnar
+ * format when the child is columnar and the arguments of all of them are 
columns of it, of the
+ * types that the functions declare. If one argument of one of these calls is 
anything else,
+ * including a column that is cast to the declared type, a row-based 
projection computes it
+ * first, and its output is converted back to columns for all of these calls. 
A row-based
+ * operator below the calls, such as a filter over the scan, has the same 
effect.
+ *
+ * Limitations:
+ *  - Calls with named arguments, and calls inside the lambda function of a 
higher-order
+ *    function, are not supported.
+ *  - A call that reads columns of both sides of a join is supported in the 
condition of an
+ *    inner join only. This includes the joins that correlated EXISTS and IN 
subqueries become.
+ *  - A conditional expression does not guard a call. A call in a branch of 
CASE, IF or
+ *    COALESCE, or on one side of AND or OR, is evaluated for every row, and 
so are the
+ *    expressions that compute its arguments, which can then fail for rows 
that the branch
+ *    would have skipped.
+ *
+ * @since 4.4.0
+ */
+@Evolving
+final class ColumnarUserDefinedFunction private (
+    /** The name of the function. */
+    val name: String,
+    /** The types of the arguments, which the arguments of a call are cast to. 
*/
+    val inputTypes: Seq[DataType],
+    /** The type of the result. */
+    val dataType: DataType,
+    private[sql] val function: Option[ColumnarScalarFunction],
+    private[sql] val engineImplementations: Seq[ColumnarUDFImplementation],
+    /** Whether the function returns the same result for the same arguments. */
+    val deterministic: Boolean,
+    /** Whether the function can return null. */
+    val nullable: Boolean) extends Serializable {
+
+  /**
+   * Returns this function with one more implementation for an engine other 
than Spark.
+   */
+  def withEngineImplementation(
+      implementation: ColumnarUDFImplementation): ColumnarUserDefinedFunction 
= {
+    new ColumnarUserDefinedFunction(
+      name, inputTypes, dataType, function, engineImplementations :+ 
implementation,
+      deterministic, nullable)
+  }
+
+  /**
+   * Returns this function as one that may return different results for the 
same arguments.
+   */
+  def asNondeterministic(): ColumnarUserDefinedFunction = {
+    new ColumnarUserDefinedFunction(
+      name, inputTypes, dataType, function, engineImplementations, false, 
nullable)
+  }
+
+  /**
+   * Returns this function as one that never returns null.
+   */
+  def asNonNullable(): ColumnarUserDefinedFunction = {
+    new ColumnarUserDefinedFunction(
+      name, inputTypes, dataType, function, engineImplementations, 
deterministic, false)
+  }
+
+  private[sql] def builder(children: Seq[Expression]): Expression = {
+    if (children.exists(_.isInstanceOf[NamedArgumentExpression])) {
+      throw QueryCompilationErrors.namedArgumentsNotSupported(name)
+    }
+    if (children.length != inputTypes.length) {
+      throw QueryCompilationErrors.wrongNumArgsError(
+        name, Seq(inputTypes.length), children.length)
+    }
+    ColumnarUDF(
+      name, function, engineImplementations, inputTypes, dataType, children, 
deterministic,
+      nullable)
+  }
+
+  /** Returns a `Column` that evaluates this function with the given 
arguments. */
+  @scala.annotation.varargs
+  def apply(cols: Column*): Column = Column(builder(cols.map(expression)))
+
+  override def toString: String = {
+    s"ColumnarUserDefinedFunction($name, ${inputTypes.map(_.sql).mkString("(", 
", ", ")")}, " +
+      s"${dataType.sql})"
+  }
+}
+
+/**
+ * @since 4.4.0
+ */
+@Evolving
+object ColumnarUserDefinedFunction {
+
+  /**
+   * Creates a deterministic function that can return null, with an 
implementation that Spark
+   * runs.
+   *
+   * @param name the name of the function
+   * @param inputTypes the types of the arguments, which the arguments of a 
call are cast to
+   * @param dataType the type of the result
+   * @param function the implementation that Spark runs, in the JVM
+   */
+  def create(
+      name: String,
+      inputTypes: Seq[DataType],
+      dataType: DataType,
+      function: ColumnarScalarFunction): ColumnarUserDefinedFunction = {
+    require(function != null, "The function of a columnar user-defined 
function cannot be null.")

Review Comment:
   **[33] The factories check only `function` for null.**
   
   This `require` rejects a null `function`, but `create` accepts a null 
`name`, `inputTypes` or `dataType`, and `withEngineImplementation` and 
`ColumnarUDFImplementation.create` accept null arguments too. From Java, these 
fail later, far from the mistake:
   
   - `create("f", (DataType[]) null, LongType, fn)` succeeds, since 
`toImmutableArraySeq` of a null array returns null, and `f.apply(col("id"))` 
then throws an NPE at `inputTypes.length` in `builder` (L122).
   - `withEngineImplementation(null)` on a function without a 
`ColumnarScalarFunction` makes `EvalColumnarUDFsExec` throw an NPE at `_.kind` 
(`EvalColumnarUDFsExec.scala:89`), where it should raise 
`COLUMNAR_UDF_NOT_EXECUTABLE`.
   - `ColumnarUDFImplementation.create(null, map)` throws an NPE from 
`hashCode` once the plan hashes the call, e.g. in the `ExpressionSet` of 
`ExtractColumnarUDFs.extract`.
   
   Could the factories and `withEngineImplementation` check each argument, as 
they check `function`?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/EvalColumnarUDFsExec.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.util.control.NonFatal
+
+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.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.{SparkPlan, SparkStrategy, UnaryExecNode}
+import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics}
+import org.apache.spark.sql.execution.vectorized.WritableColumnVector
+import org.apache.spark.sql.types.{DataType, StructType, UserDefinedType}
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnVector}
+import org.apache.spark.util.Utils
+
+/** 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 driverFunctions: 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 closures of the nodes of a stage are serialized together, so the 
nodes would share one
+    // instance of a function that several of them call, and an operator 
between them can read
+    // its child from another thread. The functions are serialized apart here, 
so that each
+    // partition of this node reads its own instances, which only this node 
calls.
+    val serializedFunctions: Array[Byte] = Utils.serialize(driverFunctions)
+    // 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 inputTypeStrings: Array[String] =
+      udfs.map(_.children.map(_.dataType.catalogString).mkString(", ")).toArray
+    val resultTypes: Array[DataType] = udfs.map(_.dataType).toArray
+    // A column vector has the SQL type of a user-defined type, so the type of 
a result is
+    // compared with the declared type after the same replacement.
+    val resultVectorTypes: Array[DataType] = 
resultTypes.map(_.transformRecursively {
+      case udt: UserDefinedType[_] => udt.sqlType
+    })
+    val numOutputRows = longMetric("numOutputRows")
+    val numOutputBatches = longMetric("numOutputBatches")
+    val evalTime = longMetric("evalTime")
+    val numInputColumns = child.output.length
+    val numFunctions = udfs.length
+
+    child.executeColumnar().mapPartitionsInternal { batches =>
+      new Iterator[ColumnarBatch] {
+        private val functions = 
Utils.deserialize[Array[ColumnarScalarFunction]](
+          serializedFunctions, Utils.getContextOrSparkClassLoader)
+
+        // 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()))
+
+        // Whether `vector` is `column` or a vector inside it. A writable 
vector, which the
+        // vectorized readers and `RowToColumnarExec` produce, gives its 
children for every
+        // type that has them: the fields of a struct, the elements of an 
array, the keys and
+        // values of a map. Other vectors are only known to give the fields of 
a struct.
+        private def isPartOf(column: ColumnVector, vector: ColumnVector): 
Boolean = {
+          (column eq vector) || (column match {
+            case w: WritableColumnVector =>
+              (0 until w.getNumChildren).exists(i => isPartOf(w.getChild(i), 
vector))
+            case _ => column.dataType() match {
+              case s: StructType =>
+                s.fields.indices.exists(i => isPartOf(column.getChild(i), 
vector))
+              case _ => false
+            }
+          })
+        }
+
+        private def isInputColumn(batch: ColumnarBatch, vector: ColumnVector): 
Boolean = {
+          var i = 0
+          while (i < numInputColumns) {
+            if (isPartOf(batch.column(i), vector)) return true
+            i += 1
+          }
+          false
+        }
+
+        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 + numFunctions)
+          var i = 0
+          while (i < numInputColumns) {
+            columns(i) = batch.column(i)
+            i += 1
+          }
+          val start = System.nanoTime()
+          val newResults = new Array[ColumnVector](numFunctions)
+          results = newResults
+          i = 0
+          while (i < numFunctions) {
+            val args = new ColumnarBatch(argOrdinals(i).map(batch.column), 
numRows)
+            val result = try {
+              functions(i).eval(args)
+            } catch {
+              case NonFatal(e) =>
+                throw 
QueryExecutionErrors.failedExecuteUserDefinedFunctionError(
+                  names(i), inputTypeStrings(i), resultTypes(i).catalogString, 
e)
+            }
+            // This node closes the results, and the child still owns its 
columns: it can use
+            // them again for its next batch. So a result that is a column of 
the child, or a
+            // field of one, is not kept as a result, and is rejected.

Review Comment:
   **[36] Nit: this comment still says "or a field of one".**
   
   ac91b552ef4 changed the error message, the comment of `isPartOf` and the 
Javadoc of `eval` to "a vector inside one", but this comment still says that a 
result that is "a column of the child, or a field of one" is rejected. 
`isPartOf` also rejects the element vector of an array and the key and value 
vectors of a map.
   
   ```suggestion
               // vector inside one, is not kept as a result, and is rejected.
   ```



##########
sql/core/src/main/scala/org/apache/spark/sql/columnar/ColumnarUserDefinedFunction.scala:
##########
@@ -0,0 +1,203 @@
+/*
+ * 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 org.apache.spark.annotation.Evolving
+import org.apache.spark.sql.Column
+import org.apache.spark.sql.catalyst.expressions.{ColumnarUDF, Expression, 
NamedArgumentExpression}
+import org.apache.spark.sql.classic.ClassicConversions._
+import org.apache.spark.sql.classic.ExpressionUtils.expression
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.util.ArrayImplicits._
+
+/**
+ * A columnar user-defined function: a scalar function that is evaluated one 
batch at a time,
+ * with columnar input and output, by an operator of its own.
+ *
+ * A function has any number of implementations, and whoever provides them 
makes sure that they
+ * return the same results:
+ *  - a `ColumnarScalarFunction` is the one that Spark runs, in the JVM;
+ *  - the `ColumnarUDFImplementation`s are for engines that replace Spark's 
operators, such as
+ *    native engines, which run them with their own operator.
+ *
+ * A function may have no implementation that Spark runs. A query that calls 
it then fails when
+ * Spark has to run the call itself.
+ *
+ * A function is created with `ColumnarUserDefinedFunction.create`, and is not 
changed
+ * afterwards: `withEngineImplementation`, `asNondeterministic` and 
`asNonNullable` return a new
+ * definition.
+ *
+ * A function can be applied to columns, or registered to be called from SQL. 
The registration
+ * is a method of the classic `UDFRegistration`, which is the one of a session 
that runs in the
+ * same JVM as the driver:
+ *
+ * {{{
+ *   val addOne = ColumnarUserDefinedFunction.create("add_one", Seq(LongType), 
LongType, new AddOne)
+ *   df.select(addOne(col("id")))
+ *   
spark.udf.asInstanceOf[org.apache.spark.sql.classic.UDFRegistration].registerColumnar(addOne)
+ *   spark.sql("SELECT add_one(id) FROM t")
+ * }}}
+ *
+ * The operator reads the arguments of a call as columns of its child, and 
evaluates together
+ * the calls of one projection or filter. They are evaluated without leaving 
the columnar
+ * format when the child is columnar and the arguments of all of them are 
columns of it, of the
+ * types that the functions declare. If one argument of one of these calls is 
anything else,
+ * including a column that is cast to the declared type, a row-based 
projection computes it
+ * first, and its output is converted back to columns for all of these calls. 
A row-based
+ * operator below the calls, such as a filter over the scan, has the same 
effect.
+ *
+ * Limitations:
+ *  - Calls with named arguments, and calls inside the lambda function of a 
higher-order
+ *    function, are not supported.
+ *  - A call that reads columns of both sides of a join is supported in the 
condition of an
+ *    inner join only. This includes the joins that correlated EXISTS and IN 
subqueries become.
+ *  - A conditional expression does not guard a call. A call in a branch of 
CASE, IF or
+ *    COALESCE, or on one side of AND or OR, is evaluated for every row, and 
so are the
+ *    expressions that compute its arguments, which can then fail for rows 
that the branch
+ *    would have skipped.
+ *
+ * @since 4.4.0
+ */
+@Evolving
+final class ColumnarUserDefinedFunction private (
+    /** The name of the function. */
+    val name: String,
+    /** The types of the arguments, which the arguments of a call are cast to. 
*/
+    val inputTypes: Seq[DataType],
+    /** The type of the result. */
+    val dataType: DataType,
+    private[sql] val function: Option[ColumnarScalarFunction],
+    private[sql] val engineImplementations: Seq[ColumnarUDFImplementation],
+    /** Whether the function returns the same result for the same arguments. */
+    val deterministic: Boolean,
+    /** Whether the function can return null. */
+    val nullable: Boolean) extends Serializable {
+
+  /**
+   * Returns this function with one more implementation for an engine other 
than Spark.
+   */
+  def withEngineImplementation(
+      implementation: ColumnarUDFImplementation): ColumnarUserDefinedFunction 
= {
+    new ColumnarUserDefinedFunction(
+      name, inputTypes, dataType, function, engineImplementations :+ 
implementation,
+      deterministic, nullable)
+  }
+
+  /**
+   * Returns this function as one that may return different results for the 
same arguments.
+   */
+  def asNondeterministic(): ColumnarUserDefinedFunction = {
+    new ColumnarUserDefinedFunction(
+      name, inputTypes, dataType, function, engineImplementations, false, 
nullable)
+  }
+
+  /**
+   * Returns this function as one that never returns null.
+   */
+  def asNonNullable(): ColumnarUserDefinedFunction = {
+    new ColumnarUserDefinedFunction(
+      name, inputTypes, dataType, function, engineImplementations, 
deterministic, false)
+  }
+
+  private[sql] def builder(children: Seq[Expression]): Expression = {
+    if (children.exists(_.isInstanceOf[NamedArgumentExpression])) {
+      throw QueryCompilationErrors.namedArgumentsNotSupported(name)
+    }
+    if (children.length != inputTypes.length) {
+      throw QueryCompilationErrors.wrongNumArgsError(
+        name, Seq(inputTypes.length), children.length)
+    }
+    ColumnarUDF(
+      name, function, engineImplementations, inputTypes, dataType, children, 
deterministic,
+      nullable)
+  }
+
+  /** Returns a `Column` that evaluates this function with the given 
arguments. */
+  @scala.annotation.varargs
+  def apply(cols: Column*): Column = Column(builder(cols.map(expression)))
+
+  override def toString: String = {
+    s"ColumnarUserDefinedFunction($name, ${inputTypes.map(_.sql).mkString("(", 
", ", ")")}, " +
+      s"${dataType.sql})"
+  }
+}
+
+/**
+ * @since 4.4.0
+ */
+@Evolving
+object ColumnarUserDefinedFunction {
+
+  /**
+   * Creates a deterministic function that can return null, with an 
implementation that Spark
+   * runs.
+   *
+   * @param name the name of the function
+   * @param inputTypes the types of the arguments, which the arguments of a 
call are cast to
+   * @param dataType the type of the result
+   * @param function the implementation that Spark runs, in the JVM
+   */
+  def create(
+      name: String,
+      inputTypes: Seq[DataType],
+      dataType: DataType,
+      function: ColumnarScalarFunction): ColumnarUserDefinedFunction = {
+    require(function != null, "The function of a columnar user-defined 
function cannot be null.")
+    new ColumnarUserDefinedFunction(name, inputTypes, dataType, 
Some(function), Nil, true, true)
+  }
+
+  /**
+   * Creates a deterministic function that can return null, with an 
implementation that Spark
+   * runs. This is the variant for Java.
+   */
+  def create(
+      name: String,
+      inputTypes: Array[DataType],
+      dataType: DataType,
+      function: ColumnarScalarFunction): ColumnarUserDefinedFunction = {
+    create(name, inputTypes.toImmutableArraySeq, dataType, function)

Review Comment:
   **[32] The Java variants of `create` keep the caller's array.**
   
   `toImmutableArraySeq` wraps the array without copying it 
(`ArrayImplicits.scala:30-33`). So a change of the `DataType[]` after `create` 
changes `inputTypes` of the function, and of the `ColumnarUDF` calls built from 
it, although the class doc says that a function "is not changed afterwards". 
`ColumnarUDFImplementation.create` copies its map for the same reason, and 
`JavaColumnarUDFSuite` checks that. For example:
   
   ```java
   DataType[] types = { DataTypes.LongType };
   ColumnarUserDefinedFunction f =
     ColumnarUserDefinedFunction.create("f", types, DataTypes.LongType, new 
AddOne());
   types[0] = DataTypes.StringType;
   // f.inputTypes() is now [STRING], so its calls cast their arguments to 
STRING.
   ```
   
   Could both Java variants, here and at L201, copy the array, e.g. with 
`inputTypes.toSeq`, with a check in `JavaColumnarUDFSuite`?



##########
sql/core/src/test/java/test/org/apache/spark/sql/JavaColumnarUDFSuite.java:
##########
@@ -0,0 +1,117 @@
+/*
+ * 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 test.org.apache.spark.sql;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import org.apache.spark.sql.Row;
+import org.apache.spark.sql.classic.SparkSession;
+import org.apache.spark.sql.columnar.ColumnarScalarFunction;
+import org.apache.spark.sql.columnar.ColumnarUDFImplementation;
+import org.apache.spark.sql.columnar.ColumnarUserDefinedFunction;
+import org.apache.spark.sql.execution.vectorized.OnHeapColumnVector;
+import org.apache.spark.sql.types.DataType;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.vectorized.ColumnVector;
+import org.apache.spark.sql.vectorized.ColumnarBatch;
+
+import static org.apache.spark.sql.functions.col;
+
+public class JavaColumnarUDFSuite {
+  private transient SparkSession spark;
+
+  /** Adds one to a bigint, and keeps nulls. */
+  public static class AddOne implements ColumnarScalarFunction {
+    @Override
+    public ColumnVector eval(ColumnarBatch args) {
+      int numRows = args.numRows();
+      ColumnVector input = args.column(0);
+      OnHeapColumnVector result = new OnHeapColumnVector(numRows, 
DataTypes.LongType);
+      for (int i = 0; i < numRows; i++) {
+        if (input.isNullAt(i)) {
+          result.putNull(i);
+        } else {
+          result.putLong(i, input.getLong(i) + 1);
+        }
+      }
+      return result;
+    }
+  }
+
+  @BeforeEach
+  public void setUp() {
+    spark = SparkSession.builder()
+      .master("local[*]")
+      .appName("testing")
+      .getOrCreate();
+  }
+
+  @AfterEach
+  public void tearDown() {
+    spark.stop();
+    spark = null;
+  }
+
+  @Test
+  public void columnarUDF() {
+    ColumnarUserDefinedFunction addOne = ColumnarUserDefinedFunction.create(
+      "java_add_one", new DataType[] { DataTypes.LongType }, 
DataTypes.LongType, new AddOne());
+    Assertions.assertEquals("java_add_one", addOne.name());
+    Assertions.assertEquals(DataTypes.LongType, addOne.dataType());
+    Assertions.assertTrue(addOne.deterministic());
+    Assertions.assertTrue(addOne.nullable());
+
+    List<Row> applied = 
spark.range(3).select(addOne.apply(col("id"))).collectAsList();
+    Assertions.assertEquals(3, applied.size());
+    for (int i = 0; i < 3; i++) {
+      Assertions.assertEquals(i + 1L, applied.get(i).getLong(0));
+    }
+
+    spark.udf().registerColumnar(addOne);
+    List<Row> called = spark.sql("SELECT java_add_one(id) FROM 
range(3)").collectAsList();
+    Assertions.assertEquals(applied, called);
+  }
+
+  @Test
+  public void columnarUDFWithEngineImplementation() {
+    Map<String, String> properties = new HashMap<>();
+    properties.put("library", "/lib.so");
+    ColumnarUDFImplementation implementation =
+      ColumnarUDFImplementation.create("some-engine", properties);
+    // A later change of the map does not change the implementation.
+    properties.put("name", "f");
+    Assertions.assertEquals("some-engine", implementation.kind());
+    Assertions.assertEquals(1, implementation.properties().size());
+    Assertions.assertEquals("/lib.so", 
implementation.properties().get("library"));
+
+    ColumnarUserDefinedFunction engineOnly = ColumnarUserDefinedFunction
+      .create("java_engine_only", new DataType[] { DataTypes.LongType }, 
DataTypes.LongType)
+      .withEngineImplementation(implementation)

Review Comment:
   **[37] Nit: this test does not check what `withEngineImplementation` and 
`properties()` promise.**
   
   `engineOnly` gets an implementation here, but the test checks only 
`deterministic()` and `nullable()`, so it would still pass if 
`withEngineImplementation` dropped its argument. Nothing checks either that the 
map of `properties()` "cannot be modified", as its doc says. Applying 
`engineOnly`, e.g. with 
`spark.range(1).select(engineOnly.apply(col("id"))).collectAsList()`, and 
checking that the error is `COLUMNAR_UDF_NOT_EXECUTABLE` with the kinds 
`[some-engine]`, and that `implementation.properties().put("k", "v")` throws 
`UnsupportedOperationException`, would cover both from Java.



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