viirya commented on code in PR #60551: URL: https://github.com/apache/spark/pull/60551#discussion_r4593066957
########## 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: Fixed in 64d7b36. The rule now moves these calls to a `Project` above the `Aggregate` first, as `ExtractPythonUDFFromAggregate` does. Added tests for the three queries, and for a call that is the grouping key itself (`GROUP BY add_one(k)`). ########## 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: Fixed in 64d7b36 by the same change as [1]: a call over an aggregate function is evaluated by a `Project` above the `Aggregate`. Tests cover `add_one(max(id))`, `add_one(sum(v))` with `GROUP BY`, a call in `HAVING`, and the DataFrame form. A call over a window function already worked, since the analyzer extracts the window expression first; I added a test and corrected the description, which said otherwise. ########## 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: Fixed in 64d7b36. For an inner join the conjuncts with such a call move to a `Filter` above the join; other join types fail with a new `UNSUPPORTED_FEATURE.COLUMNAR_UDF_IN_ON_CLAUSE`. While there, a call that reads no column was evaluated once under each side of a join; it is now evaluated once. ########## 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: Fixed in 64d7b36. `CheckAnalysis` rejects it with a new `UNSUPPORTED_FEATURE.LAMBDA_FUNCTION_WITH_COLUMNAR_UDF`, 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: Good catch. Fixed in 64d7b36: `ColumnarUDF` now has a `resultId` that `canonicalized` drops, as `PythonUDF` does, so equal calls of a deterministic function still share a result and the others are kept apart. Arguments that are not deterministic no longer share an alias either. Added a test with a function that returns a different value for every row. ########## 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: Fixed in 64d7b36. The builder throws `namedArgumentsNotSupported`, with a test. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
