dongjoon-hyun commented on code in PR #60551: URL: https://github.com/apache/spark/pull/60551#discussion_r4655210650
########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/EvalColumnarUDFsExec.scala: ########## @@ -0,0 +1,245 @@ +/* + * 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, 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.CharVarcharUtils +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.{ArrowColumnVector, 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 QueryExecutionErrors.columnarUDFNotExecutableError( + udf.name, udf.engineImplementations.map(_.kind)) + } + }.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 + // The types that the results are compared with. A column vector has the SQL type of a + // user-defined type, so a declared type gets the same replacement. CHAR and VARCHAR, which + // a declared type has when they are first-class types, are compared as STRING on both + // sides, so that the vector of such a result can be of either type. + val resultVectorTypes: Array[DataType] = resultTypes.map(EvalColumnarUDFsExec.vectorType) + 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 { + // A function that calls a native library can fail with a `LinkageError`, which + // is not a `NonFatal` one. + case e @ (NonFatal(_) | _: LinkageError) => + 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 + // vector inside one, is not kept as a result, and is rejected. + if (result != null && isInputColumn(batch, result)) { Review Comment: **[54] Nothing checks that a function returns a new vector for each call, so a function that reuses its result vector gives wrong values, or writes into a vector that Spark has closed.** This follows up on @spark-test's [P2](https://github.com/apache/spark/pull/60551#discussion_r4594444914), whose recommendation also said that a returned vector must not be kept by the function. The Javadoc of `ColumnarScalarFunction` says that Spark closes the result once it is done with the batch, and the PR description says that a function "can keep buffers between batches", so an implementation may well keep its result vector in the instance and reset it in each `eval`. Reading the code, two things then go wrong: - The calls of one node share an instance, so with `f` written that way, `select(f(col("a")), f(col("b")))` gets the same vector from both calls. The second call overwrites the first, both columns hold `f(b)` without any error, and `closeResults` closes the vector twice. - `next()` closes the results of the previous batch (L166) before it calls the function again, so the function then writes into a closed vector. An `OnHeapColumnVector` has no arrays left (`OnHeapColumnVector.java` L84-L94), so the task fails with `FAILED_EXECUTE_UDF` caused by a `NullPointerException`, which does not tell what went wrong. An `OffHeapColumnVector` has freed its memory and set its addresses to 0 (`OffHeapColumnVector.java` L97-L106), so the next `putLong` writes near address 0 and crashes the executor JVM. Could the Javadoc say that each call must return a new vector, and this check also reject a result that is the same vector as an earlier result of the batch, or as a result of the previous batch, as `COLUMNAR_UDF_RESULT_IS_ARGUMENT` does for an argument column? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/EvalColumnarUDFsExec.scala: ########## @@ -0,0 +1,245 @@ +/* + * 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, 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.CharVarcharUtils +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.{ArrowColumnVector, 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 QueryExecutionErrors.columnarUDFNotExecutableError( + udf.name, udf.engineImplementations.map(_.kind)) + } + }.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 + // The types that the results are compared with. A column vector has the SQL type of a + // user-defined type, so a declared type gets the same replacement. CHAR and VARCHAR, which + // a declared type has when they are first-class types, are compared as STRING on both + // sides, so that the vector of such a result can be of either type. + val resultVectorTypes: Array[DataType] = resultTypes.map(EvalColumnarUDFsExec.vectorType) + 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())) Review Comment: **[55] Minor: nothing releases the function instances that each task deserializes.** Each partition iterator deserializes its own instances (L121), and the PR description says that a function can keep buffers between batches. A JVM implementation that wraps a native library would keep an Arrow allocator, a JNI handle or off-heap scratch memory there. This listener closes only the results, and `ColumnarScalarFunction` has no method to release anything, so every task leaves such resources behind, and a native allocation is never freed. Since the API is still `@Evolving`, could this listener also close each instance that implements `AutoCloseable`, once per distinct instance since the calls of one node can share one, with a sentence in the Javadoc of `ColumnarScalarFunction`? ########## sql/core/src/main/java/org/apache/spark/sql/execution/vectorized/WritableColumnVector.java: ########## @@ -1006,6 +1006,11 @@ public final boolean isAllNull() { */ protected int capacity; + /** + * Returns the maximum number of rows that can be stored in this column. + */ + public final int getCapacity() { return capacity; } Review Comment: **[56] Minor: the new `final` `getCapacity()` clashes with a downstream subclass that declares the same method.** `WritableColumnVector` is subclassed outside Spark, and `OmniColumnVector` in the OmniRuntime backend of openEuler's Gluten (`openeuler-mirror/Gluten`, `backends-omni/src/main/java/org/apache/gluten/vectorized/OmniColumnVector.java` L1057) already declares `public int getCapacity()`. With this method `final`, that class no longer compiles against Spark, and an existing build fails to load, since the JVM rejects a class that overrides a final method. `EvalColumnarUDFsExec` only needs to read the capacity. Could the method be non-final? ```suggestion public int getCapacity() { return capacity; } ``` ########## sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryExecutionErrors.scala: ########## @@ -185,6 +185,38 @@ private[sql] object QueryExecutionErrors extends QueryErrorsBase with ExecutionE cause = e) } + def columnarUDFNotExecutableError(name: String, kinds: Seq[String]): Throwable = { + new SparkUnsupportedOperationException( + errorClass = "COLUMNAR_UDF_NOT_EXECUTABLE", + messageParameters = Map("name" -> name, "kinds" -> kinds.mkString("[", ", ", "]"))) Review Comment: **[58] Minor: four of the new errors pass the function name as it is, while the others quote it.** `COLUMNAR_UDF_NOT_EXECUTABLE` here, and `COLUMNAR_UDF_RESULT_IS_ARGUMENT`, `COLUMNAR_UDF_RESULT_TOO_SHORT` and `COLUMNAR_UDF_RESULT_TYPE_MISMATCH` below, put `name` into the message as it is, so the suite expects `engine_only` or `identity`. `COLUMNAR_UDF_NO_IMPLEMENTATION` (QueryCompilationErrors.scala:3135) and `FAILED_EXECUTE_UDF` (L181), which come from the same function, use `toSQLId`, so the suite expects `` `no_impl` ``. One function then appears in two forms, and the message parameters are hard to change once released. Could the four use `toSQLId(name)` too? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/PruneFileSourcePartitions.scala: ########## @@ -65,8 +65,9 @@ private[sql] object PruneFileSourcePartitions extends Rule[LogicalPlan] { filters.filter { f => f.deterministic && !SubqueryExpression.hasSubquery(f) && - // Python UDFs might exist because this rule is applied before ``ExtractPythonUDFs``. - !f.exists(_.isInstanceOf[PythonUDF]) + // Python and columnar UDFs might exist because this rule is applied before the rules + // that extract them. + !f.exists(e => e.isInstanceOf[PythonUDF] || e.isInstanceOf[ColumnarUDF]) Review Comment: **[57] Minor: `ColumnarUDF` is added next to `PythonUDF` by hand at about a dozen places.** Besides this rule, `PruneHiveTablePartitions`, `FileScanBuilder`, `PushDownUtils`, `PartitionPruning`, `InjectRuntimeFilter` (three places), `OperationHelper`, `PredicateHelper.canEvaluateWithinJoin`, `ExternalLookupJoinShapes`, `PrepareExternalLookupJoin` and `MarkSingleTaskExecution` each got a case of their own, each with its own list of UDF kinds. Several issues in the earlier rounds came from a place that was missed, and the next kind of UDF would repeat the exercise. In [9](https://github.com/apache/spark/pull/60551#discussion_r4591907194), the unification of the extractors was left to the TODO of SPARK-55278. Could these checks go through one shared predicate, or a marker trait, for a UDF that an operator of its own evaluates, either in this PR or as part of that follow-up? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/EvalColumnarUDFsExec.scala: ########## @@ -0,0 +1,245 @@ +/* + * 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, 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.CharVarcharUtils +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.{ArrowColumnVector, 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 QueryExecutionErrors.columnarUDFNotExecutableError( + udf.name, udf.engineImplementations.map(_.kind)) + } + }.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) Review Comment: **[59] Minor: a function that cannot be serialized fails with a bare `NotSerializableException`.** `Utils.serialize` writes with a plain `ObjectOutputStream`, outside Spark's closure serializer. So for a function with a field that is not serializable, `doExecuteColumnar` throws `java.io.NotSerializableException: <class of the field>` on the driver, without the name of the function, and without the `Task not serializable` error and the serialization stack that Spark gives for a Scala UDF over the same object. Could the failure be wrapped in an error that names the function, as the other errors of this node do? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/EvalColumnarUDFsExec.scala: ########## @@ -0,0 +1,245 @@ +/* + * 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, 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.CharVarcharUtils +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.{ArrowColumnVector, 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 Review Comment: **[61] Nit: the node does not pass on `child.vectorTypes`, so the generated code above it reads every column through `ColumnVector`.** `ColumnarToRowExec` generates calls on the classes that `child.vectorTypes` gives (Columnar.scala:148-149), e.g. `OnHeapColumnVector` over a vectorized Parquet scan (DataSourceScanExec.scala:363). This node outputs the child's columns as they are, but does not override `vectorTypes`, so over a Parquet scan even the columns that only pass through are read through the abstract `ColumnVector`. `InputAdapter` passes on its child's types (WholeStageCodegenExec.scala:527). Could this node do the same for the columns of its child? ```suggestion override def supportsColumnar: Boolean = true override def vectorTypes: Option[Seq[String]] = child.vectorTypes.map( _ ++ Seq.fill(resultAttrs.length)(classOf[ColumnVector].getName)) ``` ########## sql/core/src/main/scala/org/apache/spark/sql/columnar/ColumnarUserDefinedFunction.scala: ########## @@ -0,0 +1,238 @@ +/* + * 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.catalyst.util.CharVarcharUtils +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. Review Comment: **[60] Nit: the Limitations still say that only correlated EXISTS and IN subqueries become such joins.** The fix for [49] added correlated scalar subqueries to the error message, and the test added in 9c845c2 checks one, but L69-L70 still read "This includes the joins that correlated EXISTS and IN subqueries become." Could this line name scalar subqueries too? ```suggestion * inner join only. This includes the joins that correlated EXISTS, IN and scalar * subqueries become. ``` ########## sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryCompilationErrors.scala: ########## @@ -3116,6 +3116,25 @@ private[sql] object QueryCompilationErrors extends QueryErrorsBase with Compilat messageParameters = Map("joinType" -> toSQLStmt(joinType.sql))) } + def useColumnarUDFInJoinConditionUnsupportedError(joinType: JoinType): Throwable = { + // The join can also come from a correlated EXISTS or IN subquery, as a semi, anti or + // existence join, or from a correlated scalar subquery, as a left single join. An + // existence join has no SQL form. + val joinTypeName = joinType match { + case _: ExistenceJoin => "EXISTENCE" + case other => other.sql + } + new AnalysisException( + errorClass = "UNSUPPORTED_FEATURE.COLUMNAR_UDF_IN_JOIN_CONDITION", + messageParameters = Map("joinType" -> toSQLStmt(joinTypeName))) + } + + def columnarUDFNoImplementationError(name: String): Throwable = { Review Comment: **[62] Nit: `columnarUDFNoImplementationError` sits between the join-condition errors of columnar and external UDFs.** `usePythonUDFInJoinConditionUnsupportedError`, `useColumnarUDFInJoinConditionUnsupportedError` and `useExternalUDFInJoinConditionUnsupportedError` (L3113-L3142) belong together, and this error is not about a join. Could it go after them, e.g. after L3142? -- 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]
