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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/EvalColumnarUDFsExec.scala:
##########
@@ -0,0 +1,216 @@
+/*
+ * 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.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

Review Comment:
   **[27] `InsertSortForLimitAndOffset` does not pass through this node, so a 
`LIMIT` or `OFFSET` that is not at the root can lose the order of an `ORDER BY` 
below a call.** With `df = (1 to 10).map(v => v -> v).toDF("c1", 
"c2").orderBy($"c1" % 8)` from `InsertSortForLimitAndOffsetSuite`, 
`df.select(addOne($"c2")).limit(2)` is 
`Limit(Project(EvalColumnarUDFs(...Sort)))` after `ExtractColumnarUDFs`, which 
`planTakeOrdered` (SparkStrategies.scala L141-L148) does not match. When the 
limit is not the root, e.g. under the `distinct()` that the suite's 
`verifySortAdded` adds, it becomes a `GlobalLimitExec` over a single-partition 
shuffle of `LocalLimitExec`, `ProjectExec`, this node, the `ProjectExec` that 
casts the `INT` column `c2` to `BIGINT`, and the `SortExec`. That shuffle reads 
its blocks in any order, and `InsertSortForLimitAndOffset` restores the order 
with a local sort after it. But `extractOrderingAndPropagateOrderingColumns` 
(InsertSortForLimitAndOffset.scala L72-L118) passes o
 nly through `LocalLimitExec`, `WholeStageCodegenExec`, `FilterExec`, 
`EvalPythonExec` and `ProjectExec`, and returns `None` at this node. The rule 
runs before `ApplyColumnarRulesAndInsertTransitions` (QueryExecution.scala 
L858, L880), so there is no transition between the nodes yet. The limit can 
then return two rows other than the first two in the sort order. The suite 
checks this for a Python UDF (InsertSortForLimitAndOffsetSuite.scala L105-L106, 
L128-L129). Since this node passes every column of its child through, could the 
rule pass through it as it does through `FilterExec` 
(InsertSortForLimitAndOffset.scala L75-L78), with the same `verifySortAdded` 
checks for a columnar call?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/EvalColumnarUDFsExec.scala:
##########
@@ -0,0 +1,216 @@
+/*
+ * 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.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 one of the fields of `column` if 
it is a struct.
+        private def isPartOf(column: ColumnVector, vector: ColumnVector): 
Boolean = {
+          (column eq vector) || (column.dataType() match {
+            case s: StructType => s.fields.indices.exists(i => 
isPartOf(column.getChild(i), vector))

Review Comment:
   **[28] The check for a result that is part of an argument column does not 
look into arrays and maps.** `isPartOf` follows only the fields of a struct. 
`ColumnVector.getChild(int)` is public, and a `WritableColumnVector`, which the 
vectorized Parquet reader and `RowToColumnarExec` produce, returns 
`childColumns[ordinal]` for any type (WritableColumnVector.java L946): the 
element vector of an array, and the key and value vectors of a map. So a 
function `f(ARRAY<ARRAY<BIGINT>>): ARRAY<BIGINT>` that returns 
`args.column(0).getChild(0)` passes this check and the type check below, and 
`closeResults()` closes the child's inner vector, which the child fills again 
for its next batch: an NPE for on-heap vectors and freed memory for off-heap 
ones, as in [19]. The reply in 
https://github.com/apache/spark/pull/60551#discussion_r4606128201 says that 
these vectors cannot be reached through the public `ColumnVector` API. That 
holds for an `ArrowColumnVector`, whose `getChild` has children only fo
 r a struct, but not for these vectors. Could `isPartOf` also follow the 
children of a `WritableColumnVector` of an array or map type, using 
`getNumChildren` (WritableColumnVector.java L951), with a test over a Parquet 
scan?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/columnarUDFOperators.scala:
##########
@@ -0,0 +1,40 @@
+/*
+ * 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.plans.logical
+
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet, 
ColumnarUDF}
+import org.apache.spark.sql.catalyst.trees.TreePattern.{EVAL_COLUMNAR_UDF, 
TreePattern}
+
+/**
+ * Evaluates calls of columnar user-defined functions: its output is the 
output of its child
+ * followed by one column per call. The arguments of the calls are attributes 
of the child.
+ */
+case class EvalColumnarUDFs(

Review Comment:
   **[30] Minor: the logical node does not pass `maxRows` and 
`maxRowsPerPartition` through.** `ExecuteExternalUDF` 
(logicalExternalUDFOperators.scala L69-L71), which also outputs every row of 
its child, overrides both with its child's, and this node keeps the default 
`None`. It exists only after the "Extract UDFs" batch, so it hides the bound 
from the rules that read it later: `EliminateLimits` in the "Infer window group 
limit" batch, and the `EliminateLimits` and `OptimizeOneRowPlan` of AQE 
(AQEOptimizer.scala L45-L46), which read the row count of a materialized stage 
through `LogicalQueryStage.maxRows`. For example, a `LIMIT` over a call over an 
aggregation whose stage returned fewer rows than the limit stays in the plan. 
Could this node override both, as `ExecuteExternalUDF` does?



##########
sql/core/src/main/scala/org/apache/spark/sql/columnar/ColumnarUserDefinedFunction.scala:
##########
@@ -0,0 +1,105 @@
+/*
+ * 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
+
+/**
+ * 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:
+ *  - `function` is the one that Spark runs, in the JVM;
+ *  - `engineImplementations` are for engines that replace Spark's operators, 
such as native
+ *    engines, which run them with their own operator.
+ *
+ * A function may have no `function`. A query that calls it then fails when 
Spark has to run
+ * the call itself.
+ *
+ * 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("add_one", Seq(LongType), 
LongType, Some(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.
+ *
+ * @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, if there is one
+ * @param engineImplementations the implementations for other engines
+ * @param deterministic whether the function returns the same result for the 
same arguments
+ * @param nullable whether the function can return null
+ * @since 4.4.0
+ */
+@Evolving
+case class ColumnarUserDefinedFunction(

Review Comment:
   **[29] The public definition is a case class with Scala `Seq`, `Option` and 
`Map` fields.** `ColumnarScalarFunction` is a Java interface, but a Java 
application can create `ColumnarUserDefinedFunction` and 
`ColumnarUDFImplementation` only with `scala.collection.immutable.Seq`, 
`scala.Option` and `scala.collection.immutable.Map` values. It also has to pass 
all seven arguments, since Scala default arguments are not available from Java. 
As a public case class, it also exposes `apply`, `copy`, `unapply` and the 
`Product` methods, whose signatures change when a field is added later, e.g. 
for named arguments. `@Evolving` allows that, but each change needs MiMa 
exclusions. `UserDefinedFunction` in sql/api is an abstract class that 
`functions.udf` creates, with `asNonNullable()`, `asNondeterministic()` and 
`withName()`. Could these classes follow that shape, e.g. a class with factory 
methods that also take Java types, and builder methods for `deterministic` and 
`nullable`?



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