viirya commented on code in PR #60551: URL: https://github.com/apache/spark/pull/60551#discussion_r4622509502
########## 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: Fixed in ac91b552ef4. `extractOrderingAndPropagateOrderingColumns` now passes through `EvalColumnarUDFsExec` in the same branch as `FilterExec`, since the node outputs every column of its child. `InsertSortForLimitAndOffsetSuite` has the `verifySortAdded` checks for a columnar call in a filter and in a projection, for LIMIT and for OFFSET. They fail without the change (`hasLocalSort` is false). ########## 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: You are right, and my earlier reply was wrong: it holds for an `ArrowColumnVector` only. Fixed in ac91b552ef4. For a `WritableColumnVector`, `isPartOf` now follows all the children with `getNumChildren`, at any depth, so the elements of an array and the keys and values of a map are covered as well as the fields of a struct. `getNumChildren` returns 0 for a vector without children, where it threw an NPE before. For other vectors the check still follows the fields of a struct only. The error message and the Javadoc of `eval` name these vectors too. The new test returns the element vector of an array and the key vector of a map, over a Parquet scan and over a row-based child; without the change no error is raised. ########## 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: Fixed in ac91b552ef4. `EvalColumnarUDFs` overrides `maxRows` and `maxRowsPerPartition` with its child's, as `ExecuteExternalUDF` does, with a test. -- 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]
