dongjoon-hyun commented on code in PR #60551: URL: https://github.com/apache/spark/pull/60551#discussion_r4645995732
########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/ExtractColumnarUDFs.scala: ########## @@ -0,0 +1,232 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.execution.columnar.udf + +import scala.collection.mutable + +import org.apache.spark.SparkException +import org.apache.spark.internal.LogKeys.JOIN_CONDITION +import org.apache.spark.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression +import org.apache.spark.sql.catalyst.plans.InnerLike +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, EvalColumnarUDFs, Filter, Join, LogicalPlan, Project, Subquery} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.{AGGREGATE, COLUMNAR_UDF, JOIN} +import org.apache.spark.sql.errors.QueryCompilationErrors + +/** + * Extracts the calls of columnar user-defined functions from the operators and evaluates them + * in an [[EvalColumnarUDFs]] below the operator, as `ExtractPythonUDFs` does for Python UDFs. + * + * The calls of one operator that need no other call share an [[EvalColumnarUDFs]]. A call whose + * argument is another call gets its own, above that of its argument. An argument that is not + * an attribute is computed by a [[Project]] below, so that the arguments of the calls in an + * [[EvalColumnarUDFs]] are all columns of its child. + * + * Two kinds of calls cannot be evaluated below their operator, and are moved above it first, + * as `ExtractPythonUDFFromJoinCondition` and `ExtractPythonUDFFromAggregate` do: + * - a call in a join condition that reads both sides of the join is moved to a [[Filter]] + * above the join, which is possible for an inner join only; + * - a call in the result of an [[Aggregate]] that reads aggregate functions or grouping + * expressions, or no column at all, is moved to a [[Project]] above the aggregate. + */ +object ExtractColumnarUDFs extends Rule[LogicalPlan] with PredicateHelper { + + def apply(plan: LogicalPlan): LogicalPlan = plan match { + // A correlated subquery is rewritten into a join later, and goes through this rule then. + case s: Subquery if s.correlated => plan + + case _ if !plan.containsPattern(COLUMNAR_UDF) => plan + + case _ => + val prepared = extractFromAggregate(extractFromJoinCondition(plan)) + prepared.transformUpWithPruning(_.containsPattern(COLUMNAR_UDF)) { + case e: EvalColumnarUDFs => e + case p: LogicalPlan => extract(p) + } + } + + private def hasColumnarUDF(e: Expression): Boolean = e.containsPattern(COLUMNAR_UDF) + + // --------------------------------------------------------------------------------------- + // Calls in a join condition that read both sides + // --------------------------------------------------------------------------------------- + + private def hasUDFOverBothSides(e: Expression, join: Join): Boolean = e.exists { + case udf: ColumnarUDF => !canEvaluate(udf, join.left) && !canEvaluate(udf, join.right) + case _ => false + } + + private def extractFromJoinCondition(plan: LogicalPlan): LogicalPlan = { + plan.transformUpWithPruning(_.containsAllPatterns(COLUMNAR_UDF, JOIN)) { + case join @ Join(_, _, joinType, Some(condition), _) + if hasUDFOverBothSides(condition, join) => + if (!joinType.isInstanceOf[InnerLike]) { + // Evaluating a part of the condition after the join changes the result of a join + // that is not an inner join. + throw QueryCompilationErrors.useColumnarUDFInJoinConditionUnsupportedError(joinType) + } + val (udfConditions, otherConditions) = + splitConjunctivePredicates(condition).partition(hasUDFOverBothSides(_, join)) + val newCondition = if (otherConditions.isEmpty) { + logWarning(log"The join condition:${MDC(JOIN_CONDITION, condition)} " + + log"of the join plan contains columnar UDFs only, " + + log"so it will be moved out and the join plan will become a cross join.") + None + } else { + Some(otherConditions.reduceLeft(And)) + } + Filter(udfConditions.reduceLeft(And), join.copy(condition = newCondition)) + } + } + + // --------------------------------------------------------------------------------------- + // Calls in the result of an aggregate that can only be evaluated after it + // --------------------------------------------------------------------------------------- + + /** Whether the aggregate computes the expression: an aggregate function or a grouping key. */ + private def belongsToAggregate(e: Expression, agg: Aggregate): Boolean = { + e.isInstanceOf[AggregateExpression] || agg.groupingExpressions.exists(_.semanticEquals(e)) + } + + private def hasUDFOverAggregate(e: Expression, agg: Aggregate): Boolean = e.exists { + case udf: ColumnarUDF => udf.references.isEmpty || udf.exists(belongsToAggregate(_, agg)) + case _ => false + } + + private def extractFromAggregate(plan: LogicalPlan): LogicalPlan = { + plan.transformUpWithPruning(_.containsAllPatterns(COLUMNAR_UDF, AGGREGATE)) { + case agg: Aggregate if agg.aggregateExpressions.exists(hasUDFOverAggregate(_, agg)) => + val projectList = mutable.ArrayBuffer[NamedExpression]() + val aggregateExpressions = mutable.ArrayBuffer[NamedExpression]() + // Equal expressions share an alias, so that equal calls over them stay equal. + val aliases = mutable.HashMap[Expression, NamedExpression]() + agg.aggregateExpressions.foreach { expr => + if (hasUDFOverAggregate(expr, agg)) { + // The aggregate computes what the calls read, and the project above evaluates + // the calls. + val newExpr = expr.transformDown { + case e: Expression if belongsToAggregate(e, agg) => + val named = e match { + case n: NamedExpression => n + case other if other.deterministic => + aliases.getOrElseUpdate(other.canonicalized, Alias(other, "agg")()) + case other => Alias(other, "agg")() + } + if (!aggregateExpressions.exists(_.exprId == named.exprId)) { + aggregateExpressions += named + } + named.toAttribute + } + projectList += newExpr.asInstanceOf[NamedExpression] + } else { + aggregateExpressions += expr + projectList += expr.toAttribute + } + } + Project(projectList.toSeq, agg.copy(aggregateExpressions = aggregateExpressions.toSeq)) + } + } + + // --------------------------------------------------------------------------------------- + // Calls that are evaluated below their operator + // --------------------------------------------------------------------------------------- + + /** The calls that can be evaluated now: those whose arguments contain no other call. */ + private def collectEvaluableUDFs(e: Expression): Seq[ColumnarUDF] = e match { + case udf: ColumnarUDF if !udf.children.exists(hasColumnarUDF) => Seq(udf) + case other => other.children.flatMap(collectEvaluableUDFs) + } + + /** + * Equal calls of a deterministic function are evaluated once. The calls of a function that is + * not deterministic are kept apart, by their `resultId`. + */ + private def canonicalizeDeterministic(u: ColumnarUDF): ColumnarUDF = { + if (u.deterministic) u.canonicalized.asInstanceOf[ColumnarUDF] else u + } + + private def extract(plan: LogicalPlan): LogicalPlan = { + // An `ExpressionSet` keeps every expression that is not deterministic, so one call of such + // a function that the operator holds twice, as when a `Column` is selected twice, is in it + // twice. It is one call, with one `resultId`, and is evaluated once. + val udfs = ExpressionSet(plan.expressions.flatMap(collectEvaluableUDFs)) Review Comment: **[47] A call over an aggregate in a correlated subquery is evaluated for every outer row after the COUNT-bug rewrite.** When `DecorrelateInnerQuery` handles the COUNT bug, the output of an aggregate becomes `If(isnull(alwaysTrue), <its result over zero rows>, <its result>)`. The result over zero rows keeps a call as it is, since a `ColumnarUDF` is not foldable (`subquery.scala` L732-L735). For Python and external UDFs, SPARK-61482 wraps it in an `EvalOnlyWhen` marker (`DecorrelateInnerQuery.scala` L899-L903), so that `ExtractPythonUDFs` and `PlanExternalUDFs` evaluate the UDF only for the outer rows without matching rows. `EvalOnlyWhen.hasLiftedUDF` (`conditionalExpressions.scala` L227-L229) does not look for `ColumnarUDF`, and `EvalColumnarUDFs` has no condition, so `collectEvaluableUDFs` takes the call out of the `If` here, and the node evaluates it for every row of the join. For example, with a columnar `inv` over BIGINT that throws for 0, like `TestFailingPythonUDF` in the SPARK-61482 test (`SubquerySuite.scala` L1766-L1803): ```sql SELECT lo.a, (SELECT sum(x) FROM (SELECT inv(count(*)) AS x FROM ri WHERE ri.c = lo.a)) FROM lo ``` fails with `FAILED_EXECUTE_UDF`, although every outer row has matching rows, so the query never needs `inv(0)`. The LATERAL and IN forms of these tests go through the same rewrite. The scaladoc says that a conditional expression does not guard a call, but this query has no conditional expression of its own: the optimizer adds it. A subquery with a single aggregate goes through `constructLeftJoins` instead, where Python UDFs have the same issue (the TODO for SPARK-61660 at `subquery.scala` L984). Could `hasLiftedUDF` include `ColumnarUDF`, and the node evaluate such a call only for the rows where its condition holds, as `ConditionalUDFEvaluation` does for the other UDFs, with a test for this query? If that is out of scope for this PR, could the Limitations mention this case? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/ExtractColumnarUDFs.scala: ########## @@ -0,0 +1,232 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.execution.columnar.udf + +import scala.collection.mutable + +import org.apache.spark.SparkException +import org.apache.spark.internal.LogKeys.JOIN_CONDITION +import org.apache.spark.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression +import org.apache.spark.sql.catalyst.plans.InnerLike +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, EvalColumnarUDFs, Filter, Join, LogicalPlan, Project, Subquery} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.{AGGREGATE, COLUMNAR_UDF, JOIN} +import org.apache.spark.sql.errors.QueryCompilationErrors + +/** + * Extracts the calls of columnar user-defined functions from the operators and evaluates them + * in an [[EvalColumnarUDFs]] below the operator, as `ExtractPythonUDFs` does for Python UDFs. + * + * The calls of one operator that need no other call share an [[EvalColumnarUDFs]]. A call whose + * argument is another call gets its own, above that of its argument. An argument that is not + * an attribute is computed by a [[Project]] below, so that the arguments of the calls in an + * [[EvalColumnarUDFs]] are all columns of its child. + * + * Two kinds of calls cannot be evaluated below their operator, and are moved above it first, + * as `ExtractPythonUDFFromJoinCondition` and `ExtractPythonUDFFromAggregate` do: + * - a call in a join condition that reads both sides of the join is moved to a [[Filter]] + * above the join, which is possible for an inner join only; + * - a call in the result of an [[Aggregate]] that reads aggregate functions or grouping + * expressions, or no column at all, is moved to a [[Project]] above the aggregate. + */ +object ExtractColumnarUDFs extends Rule[LogicalPlan] with PredicateHelper { + + def apply(plan: LogicalPlan): LogicalPlan = plan match { + // A correlated subquery is rewritten into a join later, and goes through this rule then. + case s: Subquery if s.correlated => plan + + case _ if !plan.containsPattern(COLUMNAR_UDF) => plan + + case _ => + val prepared = extractFromAggregate(extractFromJoinCondition(plan)) + prepared.transformUpWithPruning(_.containsPattern(COLUMNAR_UDF)) { + case e: EvalColumnarUDFs => e + case p: LogicalPlan => extract(p) Review Comment: **[48] A call in the default of `DECLARE VARIABLE` fails with an INTERNAL_ERROR.** `CheckAnalysis` rejects only a subquery in the default of a variable (`CheckAnalysis.scala` L1058-L1067), so `DECLARE VARIABLE v BIGINT DEFAULT add_one(1)` passes analysis. `CreateVariable` is a command whose children are the `ResolvedIdentifier`s of its names, and whose default is one of its expressions. Reading the code, this rule extracts the call from it as from any other operator, and puts an `EvalColumnarUDFs` above the `ResolvedIdentifier` of its name. `V2CommandStrategy` plans a `CreateVariable` only when all its children are `ResolvedIdentifier`s (`V2CommandStrategy.scala` L30-L31), so planning fails with `No plan for CreateVariable ...`, which is an INTERNAL_ERROR. `SET VAR v = add_one(1)` should not have this problem, since its query is a plan of its own. A Python UDF seems to take the same path in `ExtractPythonUDFs`, but a new kind of function could start with a user-facing error. Could `CheckAnalysis` reject a columnar call in the default of `DECLARE VARIABLE`, as it rejects a subquery there, with a test? ########## common/utils/src/main/resources/error/error-conditions.json: ########## @@ -9607,6 +9631,11 @@ "Collated strings for keys of maps" ] }, + "COLUMNAR_UDF_IN_JOIN_CONDITION" : { + "message" : [ + "Columnar UDF over columns of both sides in the condition of a <joinType> join. The condition is the ON clause of the join, or the correlated predicate of an EXISTS or IN subquery, which is evaluated as such a join." Review Comment: **[49] The error for a call over both sides does not explain the join of a correlated scalar subquery.** The message says that the condition is the ON clause of the join, or the correlated predicate of an EXISTS or IN subquery. A correlated scalar subquery that is not aggregated also becomes a join with its correlated predicate as the condition, a `LEFT SINGLE` join (`subquery.scala` L940-L943). So with `add` registered and `t` from `spark.range(5).toDF("v")`, ```sql SELECT id, (SELECT v FROM t WHERE add(t.v, r.id) = 3) FROM range(3) r ``` fails with `COLUMNAR_UDF_IN_JOIN_CONDITION` for "a LEFT SINGLE join", although the query has no join, and a LEFT SINGLE join has no SQL form. With `t.v + r.id = 3` instead, it returns `(0, 3)`, `(1, 2)` and `(2, 1)`. Could the message also name a correlated scalar subquery, with a test for this query in "a call in a correlated subquery that reads both sides"? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/EvalColumnarUDFsExec.scala: ########## @@ -0,0 +1,242 @@ +/* + * 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 + // 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. CHAR and VARCHAR, which a + // declared type has when they are first-class types, are compared as STRING, 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 { + case NonFatal(e) => Review Comment: **[50] Minor: a `LinkageError` from the function is not wrapped.** `NonFatal` does not match a `LinkageError`, such as an `UnsatisfiedLinkError`, a `NoClassDefFoundError` or an `ExceptionInInitializerError`. A JVM implementation that calls a native library through JNI gets the first one when the library is missing or does not match the platform. The task then fails with the error as it is, which does not name the function, while the Javadoc of `ColumnarScalarFunction` says that an exception from the function fails the query with `FAILED_EXECUTE_UDF`. The code that `ScalaUDF` generates wraps every `Throwable` (`ScalaUDF.scala` L1192). Could this case also match a `LinkageError`? ```suggestion case e @ (NonFatal(_) | _: LinkageError) => ``` ########## sql/core/src/main/scala/org/apache/spark/sql/columnar/ColumnarUserDefinedFunction.scala: ########## @@ -0,0 +1,228 @@ +/* + * 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. + * - 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 = { + require(implementation != null, + "An implementation of a columnar user-defined function cannot be null.") + 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) + } + // As for the other kinds of functions, CHAR and VARCHAR are not types of a function, unless + // they are first-class types: they fail, or are replaced with STRING when the legacy conf + // says so. This reads the conf of the session that builds the call. + val checkedInputTypes = inputTypes.map(CharVarcharUtils.failIfHasCharVarchar) + val checkedDataType = CharVarcharUtils.failIfHasCharVarchar(dataType) + ColumnarUDF( + name, function, engineImplementations, checkedInputTypes, checkedDataType, 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 = { + checkSignature(name, inputTypes, dataType) + 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, which copies the array. + */ + def create( + name: String, + inputTypes: Array[DataType], + dataType: DataType, + function: ColumnarScalarFunction): ColumnarUserDefinedFunction = { + create(name, copyOf(inputTypes), dataType, function) + } + + /** + * Creates a deterministic function that can return null, with no implementation that Spark + * runs. Its implementations for other engines are added with `withEngineImplementation`, and + * a query that calls it fails when Spark has to run the call itself. + * + * @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 + */ + def create( + name: String, + inputTypes: Seq[DataType], + dataType: DataType): ColumnarUserDefinedFunction = { + checkSignature(name, inputTypes, dataType) + new ColumnarUserDefinedFunction(name, inputTypes, dataType, None, Nil, true, true) Review Comment: **[51] Minor: a function without any implementation fails only when a query runs it.** `create(name, inputTypes, dataType)` returns a function whose implementations are added with `withEngineImplementation`. When none is added, the function can still be applied and registered, and a query that calls it is analyzed and planned, and then fails with `COLUMNAR_UDF_NOT_EXECUTABLE`, which says "Its implementations are of the kinds [], which need an engine that supports one of them". No engine can run such a function. Could `builder`, which both `apply` and the calls from SQL go through, reject a function that has neither a `ColumnarScalarFunction` nor an engine implementation, with a test? ########## sql/catalyst/src/main/java/org/apache/spark/sql/columnar/ColumnarScalarFunction.java: ########## @@ -0,0 +1,66 @@ +/* + * 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 java.io.Serializable; + +import org.apache.spark.annotation.Evolving; +import org.apache.spark.sql.vectorized.ColumnVector; +import org.apache.spark.sql.vectorized.ColumnarBatch; + +/** + * A scalar function that Spark evaluates one batch at a time, in the JVM. It is the + * implementation of a columnar user-defined function that Spark itself can run; an engine that + * replaces Spark's operators can run another implementation of the same function instead, see + * {@link ColumnarUDFImplementation}. + * <p> + * Spark serializes the function to the executors. There, each operator that evaluates calls of + * the function gets its own instance for each task, and calls it from one thread. The calls + * that one operator evaluates share that instance. Two calls in one projection are evaluated by + * one operator, unless the argument of one of them is another call: such a call is evaluated + * by an operator of its own, with its own instance. + * <p> + * An exception that the function throws fails the query with the error condition + * {@code FAILED_EXECUTE_UDF}, with the exception as its cause. + * <p> + * The result must not depend on how the rows are split into batches, nor on the order of the + * rows or of the batches. Spark evaluates the function for every row that reaches it, also for + * rows whose result the query does not use, such as in a branch of a CASE expression that is + * not taken. + * + * @since 4.4.0 Review Comment: **[52] The new API is `@since 4.4.0`, but it ships first in 4.5.0.** `branch-4.4` is cut, and SPARK-61832 changed the version of `branch-4.x` to 4.5.0 on 2026-11-17, so a new feature that is merged to `master` and `branch-4.x` ships first in 4.5.0. The same holds for `ColumnarUDFImplementation.scala` L36 and L59, `ColumnarUserDefinedFunction.scala` L76 and L150, and `UDFRegistration.scala` L57. Unless this PR is meant for `branch-4.4` too, could all six be 4.5.0? ```suggestion * @since 4.5.0 ``` ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/EvalColumnarUDFsExec.scala: ########## @@ -0,0 +1,242 @@ +/* + * 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 + // 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. CHAR and VARCHAR, which a + // declared type has when they are first-class types, are compared as STRING, 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 { + 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 + // vector inside one, is not kept as a result, and is rejected. + if (result != null && isInputColumn(batch, result)) { + throw QueryExecutionErrors.columnarUDFResultIsArgumentError(names(i)) + } + // Set before the checks, so that a vector that fails them is closed as well. + newResults(i) = result + if (result == null || !EvalColumnarUDFsExec.hasType(result, resultVectorTypes(i))) { + throw QueryExecutionErrors.columnarUDFResultTypeMismatchError( + names(i), Option(result).map(_.dataType()), resultTypes(i)) + } + // A vector that is too short would be read past its end by the operators above. + // A writable vector tells how many values it can hold, and an Arrow vector how + // many values it has, which its count of nulls also depends on. Other vectors do + // not tell either. + result match { + case w: WritableColumnVector if w.getCapacity < numRows => + throw QueryExecutionErrors.columnarUDFResultTooShortError( + names(i), w.getCapacity, numRows) + case a: ArrowColumnVector if a.getValueVector.getValueCount < numRows => + throw QueryExecutionErrors.columnarUDFResultTooShortError( + names(i), a.getValueVector.getValueCount, numRows) + case _ => + } + columns(numInputColumns + i) = newResults(i) + i += 1 + } + evalTime += System.nanoTime() - start + numOutputRows += numRows + numOutputBatches += 1 + new ColumnarBatch(columns, numRows) + } + } + } + } + + override protected def withNewChildInternal(newChild: SparkPlan): EvalColumnarUDFsExec = + copy(child = newChild) +} + +object EvalColumnarUDFsExec { + + /** The type that the vector of a result of the given type has. */ + private def vectorType(dataType: DataType): DataType = { + CharVarcharUtils.replaceCharVarcharWithStringAlways(dataType.transformRecursively { + case udt: UserDefinedType[_] => udt.sqlType + }) + } + + private def hasType(result: ColumnVector, expected: DataType): Boolean = { + DataType.equalsStructurally(result.dataType(), expected, true) || + DataType.equalsStructurally(vectorType(result.dataType()), expected, true) + } Review Comment: **[53] Nit: the second comparison of `hasType` needs only the replacement of CHAR and VARCHAR.** `result.dataType()` never has a user-defined type, since the `ColumnVector` constructor replaces it with its `sqlType` (`ColumnVector.java` L376-L392), and `expected` has neither a user-defined type nor CHAR or VARCHAR, since it is the `vectorType` of the declared type (L112). So the UDT replacement in `vectorType(result.dataType())` does nothing, and the first comparison holds only when the second one does. The comment at L108-L109, "the type of a result is compared with the declared type after the same replacement", also reads as if the type of a result needed it. Could this be one comparison? ```suggestion private def hasType(result: ColumnVector, expected: DataType): Boolean = { DataType.equalsStructurally( CharVarcharUtils.replaceCharVarcharWithStringAlways(result.dataType()), expected, true) } ``` -- 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]
