dongjoon-hyun commented on code in PR #60551: URL: https://github.com/apache/spark/pull/60551#discussion_r4591907163
########## sql/core/src/main/scala/org/apache/spark/sql/columnar/ColumnarUserDefinedFunction.scala: ########## @@ -0,0 +1,80 @@ +/* + * 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} +import org.apache.spark.sql.classic.ClassicConversions._ +import org.apache.spark.sql.classic.ExpressionUtils.expression +import org.apache.spark.sql.errors.QueryCompilationErrors +import org.apache.spark.sql.types.DataType + +/** + * A columnar user-defined function: a scalar function that is evaluated one batch at a time, + * with columnar input and output, by an operator of its own. + * + * A function has any number of implementations, and whoever provides them makes sure that they + * return the same results: + * - `function` is the one that Spark runs, in the JVM; + * - `engineImplementations` are for engines that replace Spark's operators, such as native + * engines, which run them with their own operator. + * + * A function may have no `function`. A query that calls it then fails when Spark has to run + * the call itself. + * + * {{{ + * val addOne = ColumnarUserDefinedFunction("add_one", Seq(LongType), LongType, Some(new AddOne)) + * df.select(addOne(col("id"))) + * spark.udf.registerColumnar(addOne) + * spark.sql("SELECT add_one(id) FROM t") + * }}} + * + * @param name the name of the function + * @param inputTypes the types of the arguments, which the arguments of a call are cast to + * @param dataType the type of the result + * @param function the implementation that Spark runs, if there is one + * @param engineImplementations the implementations for other engines + * @param deterministic whether the function returns the same result for the same arguments + * @param nullable whether the function can return null + * @since 4.4.0 + */ +@Evolving +case class ColumnarUserDefinedFunction( + name: String, + inputTypes: Seq[DataType], + dataType: DataType, + function: Option[ColumnarScalarFunction] = None, + engineImplementations: Seq[ColumnarUDFImplementation] = Nil, + deterministic: Boolean = true, + nullable: Boolean = true) { + + private[sql] def builder(children: Seq[Expression]): Expression = { Review Comment: **[6] Named arguments are not rejected.** `SELECT add_one(x => id) FROM range(3)` passes the count check here, and the `ColumnarUDF` gets a `NamedArgumentExpression` child. It is not an `Attribute`, so `ExtractColumnarUDFs` computes it in a `Project` below the node, where the `Unevaluable` `NamedArgumentExpression` fails with an INTERNAL_ERROR. `UserDefinedPythonFunction.builder` (for the eval types without named argument support) and `PlanExternalUDFs` throw `QueryCompilationErrors.namedArgumentsNotSupported` for this. As far as I can see, Scala UDFs registered with `udf.register` do not check it either, but a new API could start with the check. Could this builder throw the same error? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/ExtractColumnarUDFs.scala: ########## @@ -0,0 +1,131 @@ +/* + * 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.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression +import org.apache.spark.sql.catalyst.plans.logical.{EvalColumnarUDFs, LogicalPlan, Project, Subquery} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.COLUMNAR_UDF + +/** + * 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. + */ +object ExtractColumnarUDFs extends Rule[LogicalPlan] { + + 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 _ => plan.transformUpWithPruning(_.containsPattern(COLUMNAR_UDF)) { + case e: EvalColumnarUDFs => e + case p: LogicalPlan => extract(p) + } + } + + private def hasColumnarUDF(e: Expression): Boolean = e.containsPattern(COLUMNAR_UDF) + + /** 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) => + // A call over an aggregate or a window function cannot move below its operator. + val overAggregate = udf.exists { e => + e.isInstanceOf[AggregateExpression] || e.isInstanceOf[WindowExpression] + } + if (overAggregate) { + Nil + } else { + Seq(udf) + } + case other => other.children.flatMap(collectEvaluableUDFs) + } + + private def canonicalizeDeterministic(u: ColumnarUDF): ColumnarUDF = { + if (u.deterministic) u.canonicalized.asInstanceOf[ColumnarUDF] else u + } + + private def extract(plan: LogicalPlan): LogicalPlan = { + val udfs = ExpressionSet(plan.expressions.flatMap(collectEvaluableUDFs)) + .filter(_.references.subsetOf(plan.inputSet)) Review Comment: **[4] A call inside a lambda function is not extracted, and the analyzer does not reject it.** In `SELECT transform(array(1L, 2L), x -> add_one(x))`, the call references the lambda variable (`NamedLambdaVariable.references` is its own attribute), which is not in `plan.inputSet`, so this filter drops it and the `ColumnarUDF` stays inside `ArrayTransform`. `CheckAnalysis` rejects Python UDFs (`LAMBDA_FUNCTION_WITH_PYTHON_UDF`) and external UDFs (`LAMBDA_FUNCTION_WITH_EXTERNAL_UDF`) in lambda functions, but not columnar UDFs, so this query passes analysis and fails during execution with an INTERNAL_ERROR (`Cannot evaluate expression`). Could `CheckAnalysis` reject columnar UDFs in lambda functions too, with a test? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/ExtractColumnarUDFs.scala: ########## @@ -0,0 +1,131 @@ +/* + * 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.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression +import org.apache.spark.sql.catalyst.plans.logical.{EvalColumnarUDFs, LogicalPlan, Project, Subquery} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.COLUMNAR_UDF + +/** + * 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. + */ +object ExtractColumnarUDFs extends Rule[LogicalPlan] { + + 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 _ => plan.transformUpWithPruning(_.containsPattern(COLUMNAR_UDF)) { + case e: EvalColumnarUDFs => e + case p: LogicalPlan => extract(p) + } + } + + private def hasColumnarUDF(e: Expression): Boolean = e.containsPattern(COLUMNAR_UDF) + + /** 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) => + // A call over an aggregate or a window function cannot move below its operator. + val overAggregate = udf.exists { e => + e.isInstanceOf[AggregateExpression] || e.isInstanceOf[WindowExpression] + } + if (overAggregate) { + Nil + } else { + Seq(udf) + } + case other => other.children.flatMap(collectEvaluableUDFs) + } + + private def canonicalizeDeterministic(u: ColumnarUDF): ColumnarUDF = { + if (u.deterministic) u.canonicalized.asInstanceOf[ColumnarUDF] else u + } + + private def extract(plan: LogicalPlan): LogicalPlan = { + val udfs = ExpressionSet(plan.expressions.flatMap(collectEvaluableUDFs)) + .filter(_.references.subsetOf(plan.inputSet)) + .toSeq.asInstanceOf[Seq[ColumnarUDF]] + if (udfs.isEmpty) { + plan + } else { + val attributeMap = mutable.HashMap[ColumnarUDF, Expression]() + val newChildren = plan.children.map { child => + val validUdfs = udfs.filter(_.references.subsetOf(child.outputSet)) + if (validUdfs.nonEmpty) { + // The arguments that are not attributes of the child are computed below. + val argAliases = mutable.LinkedHashMap[Expression, Alias]() + val udfsOverColumns = validUdfs.map { udf => + val newArgs = udf.children.map { + case a: Attribute => a + case arg => + argAliases.getOrElseUpdate( + arg.canonicalized, Alias(arg, s"columnarUDFArg${argAliases.size}")()).toAttribute + } + udf.withNewChildren(newArgs).asInstanceOf[ColumnarUDF] + } + val input = if (argAliases.isEmpty) { + child + } else { + Project(child.output ++ argAliases.values, child) + } + val resultAttrs = validUdfs.zipWithIndex.map { case (u, i) => + AttributeReference(s"columnarUDF$i", u.dataType, u.nullable)() + } + attributeMap ++= validUdfs.map(canonicalizeDeterministic).zip(resultAttrs) Review Comment: **[5] Two equal nondeterministic calls share one result.** `ExpressionSet` keeps every nondeterministic expression, so for `nd = ColumnarUserDefinedFunction("rnd", Seq(LongType), DoubleType, Some(f), deterministic = false)` and `df.select(nd(col("id")), nd(col("id")))`, the node evaluates both calls. But `ColumnarUDF` has no per-call id like `PythonUDF.resultId`, so the two calls are equal as case classes, the second entry here replaces the first in `attributeMap`, and L119 maps both calls to the second result. The first evaluation is wasted, and the two output columns are always equal, while two calls of a nondeterministic Scala UDF are evaluated separately. `argAliases` at L88 has the same issue: it keys on `arg.canonicalized`, so equal nondeterministic arguments of different calls share one alias. Could the keys tell nondeterministic calls apart, e.g. by reference identity, or by a result id as `PythonUDF` does? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/ExtractColumnarUDFs.scala: ########## @@ -0,0 +1,131 @@ +/* + * 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.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression +import org.apache.spark.sql.catalyst.plans.logical.{EvalColumnarUDFs, LogicalPlan, Project, Subquery} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.COLUMNAR_UDF + +/** + * 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. + */ +object ExtractColumnarUDFs extends Rule[LogicalPlan] { + + 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 _ => plan.transformUpWithPruning(_.containsPattern(COLUMNAR_UDF)) { + case e: EvalColumnarUDFs => e + case p: LogicalPlan => extract(p) + } + } + + private def hasColumnarUDF(e: Expression): Boolean = e.containsPattern(COLUMNAR_UDF) + + /** 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) => + // A call over an aggregate or a window function cannot move below its operator. + val overAggregate = udf.exists { e => Review Comment: **[2] A call over an aggregate function is left in the `Aggregate`, and nothing rejects it.** The description says such calls are not extracted, but they are not rejected either: `ColumnarUDF` is `Unevaluable`, and `CheckAnalysis` has no check for it. So `SELECT add_one(max(id)) FROM range(10)` or `SELECT k, add_one(sum(v)) FROM t GROUP BY k` passes analysis and planning, and fails during execution, when `HashAggregateExec` evaluates its result expressions, with an INTERNAL_ERROR (`Cannot evaluate expression`). Could the rule move such calls above the `Aggregate`, as `ExtractPythonUDFFromAggregate` does? If that is out of scope for this PR, could the analyzer reject them with a user-facing error instead? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/ExtractColumnarUDFs.scala: ########## @@ -0,0 +1,131 @@ +/* + * 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.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression +import org.apache.spark.sql.catalyst.plans.logical.{EvalColumnarUDFs, LogicalPlan, Project, Subquery} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.COLUMNAR_UDF + +/** + * 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. + */ +object ExtractColumnarUDFs extends Rule[LogicalPlan] { + + 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 _ => plan.transformUpWithPruning(_.containsPattern(COLUMNAR_UDF)) { + case e: EvalColumnarUDFs => e + case p: LogicalPlan => extract(p) + } + } + + private def hasColumnarUDF(e: Expression): Boolean = e.containsPattern(COLUMNAR_UDF) + + /** 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) => + // A call over an aggregate or a window function cannot move below its operator. + val overAggregate = udf.exists { e => + e.isInstanceOf[AggregateExpression] || e.isInstanceOf[WindowExpression] + } + if (overAggregate) { + Nil + } else { + Seq(udf) + } + case other => other.children.flatMap(collectEvaluableUDFs) + } + + private def canonicalizeDeterministic(u: ColumnarUDF): ColumnarUDF = { + if (u.deterministic) u.canonicalized.asInstanceOf[ColumnarUDF] else u + } + + private def extract(plan: LogicalPlan): LogicalPlan = { + val udfs = ExpressionSet(plan.expressions.flatMap(collectEvaluableUDFs)) + .filter(_.references.subsetOf(plan.inputSet)) + .toSeq.asInstanceOf[Seq[ColumnarUDF]] + if (udfs.isEmpty) { + plan + } else { + val attributeMap = mutable.HashMap[ColumnarUDF, Expression]() + val newChildren = plan.children.map { child => + val validUdfs = udfs.filter(_.references.subsetOf(child.outputSet)) + if (validUdfs.nonEmpty) { + // The arguments that are not attributes of the child are computed below. + val argAliases = mutable.LinkedHashMap[Expression, Alias]() + val udfsOverColumns = validUdfs.map { udf => + val newArgs = udf.children.map { + case a: Attribute => a + case arg => + argAliases.getOrElseUpdate( + arg.canonicalized, Alias(arg, s"columnarUDFArg${argAliases.size}")()).toAttribute + } + udf.withNewChildren(newArgs).asInstanceOf[ColumnarUDF] + } + val input = if (argAliases.isEmpty) { + child + } else { + Project(child.output ++ argAliases.values, child) + } + val resultAttrs = validUdfs.zipWithIndex.map { case (u, i) => + AttributeReference(s"columnarUDF$i", u.dataType, u.nullable)() + } + attributeMap ++= validUdfs.map(canonicalizeDeterministic).zip(resultAttrs) + val evaluation = EvalColumnarUDFs(udfsOverColumns, resultAttrs, input) + if (argAliases.isEmpty) { + evaluation + } else { + // Drop the columns of the arguments. + Project(child.output ++ resultAttrs, evaluation) + } + } else { + child + } + } + udfs.map(canonicalizeDeterministic).filterNot(attributeMap.contains).foreach { udf => Review Comment: **[3] A call in a join condition that reads both sides fails with an internal error.** For `a.join(b, add(a("x"), b("y")) === 1)` or `... JOIN b ON add(a.x, b.y) = 1`, the call passes the `inputSet` filter at L73 but matches neither child at L80, so L114 throws `Invalid columnar function call ..., requires attributes from more than one child`, an INTERNAL_ERROR, during optimization. `ExtractPythonUDFFromJoinCondition` (joins.scala:272) and `PlanExternalUDFs.extractExternalUDFFromJoinCondition` handle this case: for an inner join they move the condition to a `Filter` above the join, and for other join types they raise a user-facing error. Could columnar UDFs get the same handling? ########## sql/core/src/main/scala/org/apache/spark/sql/classic/UDFRegistration.scala: ########## @@ -50,6 +51,18 @@ import org.apache.spark.sql.types.DataType class UDFRegistration private[sql] (session: SparkSession, functionRegistry: FunctionRegistry) extends sql.UDFRegistration with Logging { + /** + * Registers a columnar user-defined function under its name, so that SQL can call it. + * + * @since 4.4.0 + */ + def registerColumnar(udf: ColumnarUserDefinedFunction): ColumnarUserDefinedFunction = { + // `ExpressionInfo` accepts a fixed set of sources. This is the one of a Scala UDF, which is + // what the JVM implementation of a columnar function is closest to. + functionRegistry.createOrReplaceTempFunction(udf.name, udf.builder, "scala_udf") Review Comment: **[8] Minor: the return type check of the other `register` methods is missing.** `registerPython` (L81), `register(name, udaf)` (L100) and `register(name, udf, ...)` (L120) call `TypeUtils.checkNoQualifierInRegisteredRoutineReturnType`, so a FILE type with a qualifier in the return type is rejected when the function is registered. `registerColumnar` registers such a function. Could it call the same check on `udf.dataType`? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/ExtractColumnarUDFs.scala: ########## @@ -0,0 +1,131 @@ +/* + * 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.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression +import org.apache.spark.sql.catalyst.plans.logical.{EvalColumnarUDFs, LogicalPlan, Project, Subquery} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.COLUMNAR_UDF + +/** + * 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. + */ +object ExtractColumnarUDFs extends Rule[LogicalPlan] { + + 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 _ => plan.transformUpWithPruning(_.containsPattern(COLUMNAR_UDF)) { + case e: EvalColumnarUDFs => e + case p: LogicalPlan => extract(p) + } + } + + private def hasColumnarUDF(e: Expression): Boolean = e.containsPattern(COLUMNAR_UDF) + + /** 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) => + // A call over an aggregate or a window function cannot move below its operator. + val overAggregate = udf.exists { e => + e.isInstanceOf[AggregateExpression] || e.isInstanceOf[WindowExpression] + } + if (overAggregate) { + Nil + } else { + Seq(udf) + } + case other => other.children.flatMap(collectEvaluableUDFs) + } + + private def canonicalizeDeterministic(u: ColumnarUDF): ColumnarUDF = { + if (u.deterministic) u.canonicalized.asInstanceOf[ColumnarUDF] else u + } + + private def extract(plan: LogicalPlan): LogicalPlan = { + val udfs = ExpressionSet(plan.expressions.flatMap(collectEvaluableUDFs)) + .filter(_.references.subsetOf(plan.inputSet)) + .toSeq.asInstanceOf[Seq[ColumnarUDF]] + if (udfs.isEmpty) { + plan + } else { + val attributeMap = mutable.HashMap[ColumnarUDF, Expression]() + val newChildren = plan.children.map { child => + val validUdfs = udfs.filter(_.references.subsetOf(child.outputSet)) + if (validUdfs.nonEmpty) { + // The arguments that are not attributes of the child are computed below. + val argAliases = mutable.LinkedHashMap[Expression, Alias]() + val udfsOverColumns = validUdfs.map { udf => + val newArgs = udf.children.map { + case a: Attribute => a + case arg => + argAliases.getOrElseUpdate( + arg.canonicalized, Alias(arg, s"columnarUDFArg${argAliases.size}")()).toAttribute + } + udf.withNewChildren(newArgs).asInstanceOf[ColumnarUDF] + } + val input = if (argAliases.isEmpty) { + child + } else { + Project(child.output ++ argAliases.values, child) Review Comment: **[10] Arguments that are not columns add a row round trip over a columnar scan.** This `Project` is a row operator, so over Parquet, `SELECT s, add_one(int_col)` (the implicit cast from INT to BIGINT that the analyzer adds is such an argument) or `shout(concat(s, 'x'))` is planned as `Scan -> ColumnarToRow -> Project -> RowToColumnar -> EvalColumnarUDFsExec -> ColumnarToRow -> Project`. `RowToColumnarExec` copies every column that the query keeps into new vectors, strings included, so these calls are likely slower than the Scala UDFs they replace. The benchmark and the columnar-scan test use only bare columns of the declared types. Could the description and the scaladoc mention this, and could the benchmark cover a cast argument? ########## sql/core/src/main/scala/org/apache/spark/sql/classic/UDFRegistration.scala: ########## @@ -50,6 +51,18 @@ import org.apache.spark.sql.types.DataType class UDFRegistration private[sql] (session: SparkSession, functionRegistry: FunctionRegistry) extends sql.UDFRegistration with Logging { + /** + * Registers a columnar user-defined function under its name, so that SQL can call it. + * + * @since 4.4.0 + */ + def registerColumnar(udf: ColumnarUserDefinedFunction): ColumnarUserDefinedFunction = { Review Comment: **[7] `registerColumnar` is only on `classic.UDFRegistration`.** `SparkSession.builder().getOrCreate()` returns an `org.apache.spark.sql.SparkSession`, whose `udf` is an `org.apache.spark.sql.UDFRegistration`, so the scaladoc example in ColumnarUserDefinedFunction.scala:44, `spark.udf.registerColumnar(addOne)`, does not compile in a normal application without a cast to `classic.SparkSession`. The suite compiles because `SharedSparkSession.spark` is a classic session. Also, the description lists `UDFRegistration.registerColumnar` as `@Evolving`, but the method has no annotation, inside a `@Stable` class. Could the scaladoc and the description say how users reach this method, and could it be marked `@Evolving`? ########## sql/core/src/test/scala/org/apache/spark/sql/execution/columnar/udf/ColumnarUDFSuite.scala: ########## @@ -0,0 +1,190 @@ +/* + * 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 java.util.Locale + +import org.apache.spark.{SparkRuntimeException, SparkUnsupportedOperationException} +import org.apache.spark.sql.{QueryTest, Row} +import org.apache.spark.sql.columnar.{ColumnarScalarFunction, ColumnarUDFImplementation, ColumnarUserDefinedFunction} +import org.apache.spark.sql.execution.{RowToColumnarExec, SparkPlan} +import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper +import org.apache.spark.sql.execution.vectorized.OnHeapColumnVector +import org.apache.spark.sql.functions.{col, lit} +import org.apache.spark.sql.test.SharedSparkSession +import org.apache.spark.sql.types.{LongType, StringType} +import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnVector} +import org.apache.spark.unsafe.types.UTF8String + +/** Adds one to a bigint, and keeps nulls. */ +class AddOneFunction extends ColumnarScalarFunction { + override def eval(args: ColumnarBatch): ColumnVector = { + val n = args.numRows() + val in = args.column(0) + val out = new OnHeapColumnVector(n, LongType) + var i = 0 + if (in.hasNull) { + while (i < n) { + if (in.isNullAt(i)) out.putNull(i) else out.putLong(i, in.getLong(i) + 1) + i += 1 + } + } else { + while (i < n) { + out.putLong(i, in.getLong(i) + 1) + i += 1 + } + } + out + } +} + +/** Adds two bigints, and returns null if either is null. */ +class AddFunction extends ColumnarScalarFunction { + override def eval(args: ColumnarBatch): ColumnVector = { + val n = args.numRows() + val a = args.column(0) + val b = args.column(1) + val out = new OnHeapColumnVector(n, LongType) + var i = 0 + while (i < n) { + if (a.isNullAt(i) || b.isNullAt(i)) { + out.putNull(i) + } else { + out.putLong(i, a.getLong(i) + b.getLong(i)) + } + i += 1 + } + out + } +} + +/** The upper case of a string, followed by an exclamation mark. */ +class ShoutFunction extends ColumnarScalarFunction { + override def eval(args: ColumnarBatch): ColumnVector = { + val n = args.numRows() + val in = args.column(0) + val out = new OnHeapColumnVector(n, StringType) + var i = 0 + while (i < n) { + if (in.isNullAt(i)) { + out.putNull(i) + } else { + val upper = in.getUTF8String(i).toString.toUpperCase(Locale.ROOT) + val bytes = UTF8String.fromString(upper + "!").getBytes + out.putByteArray(i, bytes) + } + i += 1 + } + out + } +} + +class ColumnarUDFSuite extends QueryTest with SharedSparkSession with AdaptiveSparkPlanHelper { + import testImplicits._ + + private val addOne = + ColumnarUserDefinedFunction("add_one", Seq(LongType), LongType, Some(new AddOneFunction)) + private val add = + ColumnarUserDefinedFunction("add", Seq(LongType, LongType), LongType, Some(new AddFunction)) + private val shout = + ColumnarUserDefinedFunction("shout", Seq(StringType), StringType, Some(new ShoutFunction)) + + private def evalNodes(plan: SparkPlan): Seq[EvalColumnarUDFsExec] = collect(plan) { + case e: EvalColumnarUDFsExec => e + } + + test("a call over a row-based child") { + val df = spark.range(5).select(col("id"), addOne(col("id"))) + checkAnswer(df, (0 until 5).map(i => Row(i.toLong, i + 1L))) + assert(evalNodes(df.queryExecution.executedPlan).length == 1) + } + + test("a call from SQL, with an argument that is cast") { + spark.udf.registerColumnar(addOne) Review Comment: **[13] Nit: `add_one` stays registered in the shared session.** This test registers `add_one` and does not drop it, so a later test that calls `add_one` from SQL would pass only when this test runs first. Could it use `withUserDefinedFunction("add_one" -> true) { ... }`? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/ExtractColumnarUDFs.scala: ########## @@ -0,0 +1,131 @@ +/* + * 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.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression +import org.apache.spark.sql.catalyst.plans.logical.{EvalColumnarUDFs, LogicalPlan, Project, Subquery} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.COLUMNAR_UDF + +/** + * 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. + */ +object ExtractColumnarUDFs extends Rule[LogicalPlan] { Review Comment: **[9] This is a third copy of the placement logic of `ExtractPythonUDFs.extract`, without its helper rules.** Items 1-4 come from the rules that run around `ExtractPythonUDFs` and that have no counterpart here: `ExtractPythonUDFFromAggregate`, `ExtractPythonUDFFromJoinCondition`, `ExtractPythonUDFFromLambda` and the lambda check in `CheckAnalysis`. `PlanExternalUDFs` has the same structure, with a TODO (PlanExternalUDFs.scala:38) to share the placement logic with the Python UDF extractors. Could the shared rules take a predicate for a UDF that is evaluated by an operator of its own (Python, external, columnar), so that columnar UDFs get the aggregate, join condition and lambda handling at once? ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala: ########## @@ -2873,6 +2873,7 @@ object PushPredicateThroughNonJoin extends Rule[LogicalPlan] with PredicateHelpe case _: ExecuteExternalUDF => true case _: BatchEvalPython => true case _: ArrowEvalPython => true + case _: EvalColumnarUDFs => true Review Comment: **[11] Minor: `LimitPushDown` has no case for `EvalColumnarUDFs`.** This PR adds `EvalColumnarUDFs` to `canPushThrough` here, but `LimitPushDown` (L1036-1048) pushes a `LocalLimit` through `BatchEvalPython`, `ArrowEvalPython` and `ExecuteExternalUDF`, with or without a `Project` on top, and not through `EvalColumnarUDFs`. So over a row-based child, `df.select(addOne(col("id"))).limit(1)` converts and evaluates whole batches (up to `columnBatchSize`, 10000 rows by default) in each partition. Over a columnar scan, a pushed limit could add a transition instead. Could `LimitPushDown` get the two cases, or could a comment say why they are left out? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/ExtractColumnarUDFs.scala: ########## @@ -0,0 +1,131 @@ +/* + * 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.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression +import org.apache.spark.sql.catalyst.plans.logical.{EvalColumnarUDFs, LogicalPlan, Project, Subquery} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.COLUMNAR_UDF + +/** + * 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. + */ +object ExtractColumnarUDFs extends Rule[LogicalPlan] { + + 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 _ => plan.transformUpWithPruning(_.containsPattern(COLUMNAR_UDF)) { + case e: EvalColumnarUDFs => e + case p: LogicalPlan => extract(p) + } + } + + private def hasColumnarUDF(e: Expression): Boolean = e.containsPattern(COLUMNAR_UDF) + + /** 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) => + // A call over an aggregate or a window function cannot move below its operator. + val overAggregate = udf.exists { e => + e.isInstanceOf[AggregateExpression] || e.isInstanceOf[WindowExpression] + } + if (overAggregate) { + Nil + } else { + Seq(udf) + } + case other => other.children.flatMap(collectEvaluableUDFs) + } + + private def canonicalizeDeterministic(u: ColumnarUDF): ColumnarUDF = { + if (u.deterministic) u.canonicalized.asInstanceOf[ColumnarUDF] else u + } + + private def extract(plan: LogicalPlan): LogicalPlan = { + val udfs = ExpressionSet(plan.expressions.flatMap(collectEvaluableUDFs)) Review Comment: **[1] A call in the result expressions of an `Aggregate` that reads only grouping keys, or no column at all, is moved below the `Aggregate`.** `plan.expressions` of an `Aggregate` includes its `aggregateExpressions`, so for `SELECT add_one(k), count(*) FROM t GROUP BY k`, `df.groupBy("k").agg(addOne(col("k")))` or `SELECT add_one(1), count(*) FROM t`, this rule builds `Aggregate([k], [columnarUDF0 AS ..., count(1)], EvalColumnarUDFs(...))`. `columnarUDF0` is neither a grouping expression nor inside an aggregate function, so I think this fails the plan validation in tests (`validateAggregateExpressions`), and otherwise the binding of the `HashAggregateExec` result expressions with an INTERNAL_ERROR (`Couldn't find columnarUDF0`). Python UDFs have `ExtractPythonUDFFromAggregate` for this, and external UDFs have `PlanExternalUDFs.extractExternalUDFFromAggregate`; both move such calls to a `Project` above the `Aggregate`. Could this rule do the same, with tests for the three queries a bove? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/ExtractColumnarUDFs.scala: ########## @@ -0,0 +1,131 @@ +/* + * 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.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression +import org.apache.spark.sql.catalyst.plans.logical.{EvalColumnarUDFs, LogicalPlan, Project, Subquery} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.COLUMNAR_UDF + +/** + * 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. + */ +object ExtractColumnarUDFs extends Rule[LogicalPlan] { + + 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 _ => plan.transformUpWithPruning(_.containsPattern(COLUMNAR_UDF)) { + case e: EvalColumnarUDFs => e + case p: LogicalPlan => extract(p) + } + } + + private def hasColumnarUDF(e: Expression): Boolean = e.containsPattern(COLUMNAR_UDF) + + /** 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) => + // A call over an aggregate or a window function cannot move below its operator. + val overAggregate = udf.exists { e => + e.isInstanceOf[AggregateExpression] || e.isInstanceOf[WindowExpression] + } + if (overAggregate) { + Nil + } else { + Seq(udf) + } + case other => other.children.flatMap(collectEvaluableUDFs) + } + + private def canonicalizeDeterministic(u: ColumnarUDF): ColumnarUDF = { + if (u.deterministic) u.canonicalized.asInstanceOf[ColumnarUDF] else u + } + + private def extract(plan: LogicalPlan): LogicalPlan = { + val udfs = ExpressionSet(plan.expressions.flatMap(collectEvaluableUDFs)) + .filter(_.references.subsetOf(plan.inputSet)) + .toSeq.asInstanceOf[Seq[ColumnarUDF]] + if (udfs.isEmpty) { + plan + } else { + val attributeMap = mutable.HashMap[ColumnarUDF, Expression]() + val newChildren = plan.children.map { child => + val validUdfs = udfs.filter(_.references.subsetOf(child.outputSet)) + if (validUdfs.nonEmpty) { + // The arguments that are not attributes of the child are computed below. + val argAliases = mutable.LinkedHashMap[Expression, Alias]() + val udfsOverColumns = validUdfs.map { udf => + val newArgs = udf.children.map { + case a: Attribute => a + case arg => + argAliases.getOrElseUpdate( + arg.canonicalized, Alias(arg, s"columnarUDFArg${argAliases.size}")()).toAttribute + } + udf.withNewChildren(newArgs).asInstanceOf[ColumnarUDF] + } + val input = if (argAliases.isEmpty) { + child + } else { + Project(child.output ++ argAliases.values, child) + } + val resultAttrs = validUdfs.zipWithIndex.map { case (u, i) => + AttributeReference(s"columnarUDF$i", u.dataType, u.nullable)() + } + attributeMap ++= validUdfs.map(canonicalizeDeterministic).zip(resultAttrs) + val evaluation = EvalColumnarUDFs(udfsOverColumns, resultAttrs, input) + if (argAliases.isEmpty) { + evaluation + } else { + // Drop the columns of the arguments. + Project(child.output ++ resultAttrs, evaluation) Review Comment: **[14] Nit: the inner `Project` looks redundant.** `extract` already adds `Project(plan.output, newPlan)` at L124-125 when the output changes, and `ColumnPruning` runs again in the same batch, so the argument columns are dropped anyway. Could this return `evaluation` directly? ########## sql/core/benchmarks/ColumnarUDFBenchmark-results.txt: ########## @@ -0,0 +1,39 @@ +================================================================================================ +Columnar UDF +================================================================================================ + +OpenJDK 64-Bit Server VM 21.0.8 on Mac OS X 26.7.1 Review Comment: **[12] Minor: the benchmark results are from a local macOS run, and the JDK 25 file is missing.** The other `*-results.txt` files are generated by the GitHub Actions benchmark workflow on Linux (e.g. `UDFBenchmark-results.txt`: AMD EPYC 7763 on Linux), and `BenchmarkBase` writes a separate `-jdk25-results.txt` for JDK 25 (BenchmarkBase.scala:55-57). These Apple M4 Max numbers cannot be compared with the other files, and the next workflow run will replace them. Could you regenerate both files with the benchmark workflow? -- 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]
