dongjoon-hyun commented on code in PR #60551: URL: https://github.com/apache/spark/pull/60551#discussion_r4630999440
########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/ExtractColumnarUDFs.scala: ########## @@ -0,0 +1,225 @@ +/* + * 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]() + 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 => 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 = { + val udfs = ExpressionSet(plan.expressions.flatMap(collectEvaluableUDFs)) Review Comment: **[37] One call that an operator holds twice is evaluated twice, and the first result is dropped.** [5] keeps two calls of a function that is not deterministic apart by their `resultId`. One call can still appear twice in one operator, when a DataFrame selects the same `Column` twice. `ExpressionSet` keeps every expression that is not deterministic, without removing duplicates (`ExpressionSet.scala` L97-L103), so `udfs` here holds the call twice. L170 puts both copies in `validUdfs`, the node evaluates the function twice, and at L201 the second pair replaces the first in `attributeMap`. With `CounterFunction` from `ColumnarUDFSuite`: ```scala val counter = ColumnarUserDefinedFunction.create( "counter", Seq(LongType), LongType, new CounterFunction).asNondeterministic() val c = counter(col("id")) spark.range(0, 10, 1, 1).select(c.as("a"), c.as("b")) ``` the node has two calls, which share one instance, so the first evaluation returns 1 to 10 and the second 11 to 20. Both `a` and `b` read the second result, 11 to 20, and the first one is computed and closed unused. A function with side effects also runs them twice for each row. Could `udfs` drop the duplicates, e.g. with `.distinct`, which still keeps calls with different `resultId`s apart, with a test for this case? ########## sql/core/src/test/scala/org/apache/spark/sql/execution/columnar/udf/ColumnarUDFSuite.scala: ########## @@ -0,0 +1,761 @@ +/* + * 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 java.util.concurrent.atomic.AtomicLong + +import org.apache.spark.{SPARK_DOC_ROOT, SparkException, SparkRuntimeException, SparkUnsupportedOperationException} +import org.apache.spark.sql.{AnalysisException, DataFrame, QueryTest, Row} +import org.apache.spark.sql.catalyst.analysis.StoredExpressionFunctions +import org.apache.spark.sql.catalyst.expressions.{BloomFilterMightContain, UserDefinedExpression} +import org.apache.spark.sql.catalyst.plans.NormalizePlan +import org.apache.spark.sql.catalyst.plans.logical.{EvalColumnarUDFs, Filter, Join, LogicalPlan} +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.datasources.MarkSingleTaskExecution +import org.apache.spark.sql.execution.vectorized.OnHeapColumnVector +import org.apache.spark.sql.functions.{array, col, count, lit, map, struct, sum} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.test.{ExamplePoint, ExamplePointUDT, SharedSparkSession} +import org.apache.spark.sql.types.{ArrayType, CharType, DataType, FileType, LongType, MapType, StringType, StructField, StructType, VarcharType} +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 + } +} + +/** Returns the number of values that it has returned so far, which differs for every value. */ +class CounterFunction extends ColumnarScalarFunction { + private val counter = new AtomicLong() + + override def eval(args: ColumnarBatch): ColumnVector = { + val n = args.numRows() + val out = new OnHeapColumnVector(n, LongType) + var i = 0 + while (i < n) { + out.putLong(i, counter.incrementAndGet()) + i += 1 + } + out + } +} + +/** Returns its argument column, which a function must not do. */ +class ReturnArgumentFunction extends ColumnarScalarFunction { + override def eval(args: ColumnarBatch): ColumnVector = args.column(0) +} + +/** Returns a child vector of its argument column, which a function must not do. */ +class ReturnFieldFunction extends ColumnarScalarFunction { + override def eval(args: ColumnarBatch): ColumnVector = args.column(0).getChild(0) +} + +/** Returns no vector. */ +class NullFunction extends ColumnarScalarFunction { + override def eval(args: ColumnarBatch): ColumnVector = null +} + +/** Fails. */ +class FailingFunction extends ColumnarScalarFunction { + override def eval(args: ColumnarBatch): ColumnVector = throw new ArithmeticException("boom") +} + +/** Returns the point (x, x) for a bigint x, as a value of a user-defined type. */ +class PointFunction extends ColumnarScalarFunction { + override def eval(args: ColumnarBatch): ColumnVector = { + val n = args.numRows() + val in = args.column(0) + val out = new OnHeapColumnVector(n, new ExamplePointUDT) + val data = out.arrayData() + data.reserve(2 * n) + var i = 0 + while (i < n) { + val x = in.getLong(i).toDouble + data.putDouble(2 * i, x) + data.putDouble(2 * i + 1, x) + out.putArray(i, 2 * i, 2) + i += 1 + } + out + } +} + +class ColumnarUDFSuite extends QueryTest with SharedSparkSession with AdaptiveSparkPlanHelper { + import testImplicits._ + + private val addOne = + ColumnarUserDefinedFunction.create("add_one", Seq(LongType), LongType, new AddOneFunction) + private val add = + ColumnarUserDefinedFunction.create("add", Seq(LongType, LongType), LongType, new AddFunction) + private val shout = + ColumnarUserDefinedFunction.create("shout", Seq(StringType), StringType, new ShoutFunction) + + private def evalNodes(plan: SparkPlan): Seq[EvalColumnarUDFsExec] = collect(plan) { + case e: EvalColumnarUDFsExec => e + } + + /** Registers the functions for SQL, and drops them afterwards. */ + private def withFunctions(udfs: ColumnarUserDefinedFunction*)(f: => Unit): Unit = { + withUserDefinedFunction(udfs.map(_.name -> true): _*) { + udfs.foreach(spark.udf.registerColumnar) + f + } + } + + 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") { + withFunctions(addOne) { + checkAnswer(sql("SELECT add_one(1), add_one(CAST(NULL AS INT))"), Row(2L, null)) + checkAnswer( + sql("SELECT sum(add_one(id)) FROM range(1000)"), Row((1 to 1000).map(_.toLong).sum)) + } + } + + test("a call over a columnar scan has no transition from rows") { + withTempPath { path => + spark.range(100).selectExpr("id", "cast(id as string) as s") + .write.parquet(path.getCanonicalPath) + val df = spark.read.parquet(path.getCanonicalPath).select(col("s"), addOne(col("id"))) + checkAnswer(df, (0 until 100).map(i => Row(i.toString, i + 1L))) + val plan = df.queryExecution.executedPlan + val eval = evalNodes(plan) + assert(eval.length == 1) + assert(collect(plan) { case r: RowToColumnarExec => r }.isEmpty) + } + } + + test("sibling calls share a node, and nested calls do not") { + val siblings = spark.range(5).select(addOne(col("id")), add(col("id"), col("id"))) + checkAnswer(siblings, (0 until 5).map(i => Row(i + 1L, 2L * i))) + val siblingNodes = evalNodes(siblings.queryExecution.executedPlan) + assert(siblingNodes.length == 1 && siblingNodes.head.udfs.length == 2) + + val nested = spark.range(5).select(addOne(addOne(col("id")))) + checkAnswer(nested, (0 until 5).map(i => Row(i + 2L))) + assert(evalNodes(nested.queryExecution.executedPlan).length == 2) + } + + test("arguments that are not columns") { + val df = spark.range(5).select(add(col("id") * 2, lit(10L)), addOne(col("id") * 2)) + checkAnswer(df, (0 until 5).map(i => Row(2L * i + 10, 2L * i + 1))) + } + + test("a call in a filter, and a filter below a call") { + val df = spark.range(10).filter(addOne(col("id")) > 5).select(col("id")) + checkAnswer(df, (5 until 10).map(i => Row(i.toLong))) + val pushed = spark.range(10).select(col("id"), addOne(col("id")).as("r")).filter("id < 3") + checkAnswer(pushed, (0 until 3).map(i => Row(i.toLong, i + 1L))) + } + + test("an argument that is cast is computed by a row-based projection") { + withTempPath { path => + spark.range(100).selectExpr("cast(id as int) as i").write.parquet(path.getCanonicalPath) + val df = spark.read.parquet(path.getCanonicalPath).select(addOne(col("i"))) + checkAnswer(df, (0 until 100).map(i => Row(i + 1L))) + val plan = df.queryExecution.executedPlan + assert(evalNodes(plan).length == 1) + assert(collect(plan) { case r: RowToColumnarExec => r }.length == 1) + } + } + + test("calls in an aggregate that read grouping keys, or no column") { + withFunctions(addOne) { + withTempView("t") { + spark.range(10).selectExpr("id % 3 AS k", "id AS v").createOrReplaceTempView("t") + checkAnswer( + sql("SELECT add_one(k), count(*) FROM t GROUP BY k"), + Seq(Row(1L, 4L), Row(2L, 3L), Row(3L, 3L))) + checkAnswer( + spark.table("t").groupBy("k").agg(addOne(col("k")), count("*")), + Seq(Row(0L, 1L, 4L), Row(1L, 2L, 3L), Row(2L, 3L, 3L))) + checkAnswer(sql("SELECT add_one(1), count(*) FROM t"), Row(2L, 10L)) + // The call is the grouping key. + checkAnswer( + sql("SELECT add_one(k), count(*) FROM t GROUP BY add_one(k)"), + Seq(Row(1L, 4L), Row(2L, 3L), Row(3L, 3L))) + checkAnswer( + sql("SELECT add_one(k) + 1, sum(add_one(v)) FROM t GROUP BY add_one(k)"), + Seq(Row(2L, 22L), Row(3L, 15L), Row(4L, 18L))) + } + } + } + + test("calls over aggregate and window functions") { + withFunctions(addOne, add) { + withTempView("t") { + spark.range(10).selectExpr("id % 3 AS k", "id AS v").createOrReplaceTempView("t") + checkAnswer(sql("SELECT add_one(max(id)) FROM range(10)"), Row(10L)) + checkAnswer( + sql("SELECT k, add_one(sum(v)) FROM t GROUP BY k"), + Seq(Row(0L, 19L), Row(1L, 13L), Row(2L, 16L))) + checkAnswer( + sql("SELECT k, add(k, sum(add_one(v))) + 1 FROM t GROUP BY k"), + Seq(Row(0L, 23L), Row(1L, 17L), Row(2L, 21L))) + checkAnswer( + spark.table("t").groupBy("k").agg(addOne(sum("v"))), + Seq(Row(0L, 19L), Row(1L, 13L), Row(2L, 16L))) + checkAnswer( + sql("SELECT k, sum(v) FROM t GROUP BY k HAVING add_one(sum(v)) > 13"), + Seq(Row(0L, 18L), Row(2L, 15L))) + checkAnswer( + sql("SELECT DISTINCT add_one(sum(v) OVER (PARTITION BY k)) FROM t"), + Seq(Row(19L), Row(13L), Row(16L))) + } + } + } + + test("a call in a join condition that reads both sides") { + val a = spark.range(5).toDF("x") + val b = spark.range(5).toDF("y") + val condition = add(a("x"), b("y")) === 1 + checkAnswer(a.join(b, condition), Seq(Row(0L, 1L), Row(1L, 0L))) + checkAnswer( + a.join(b, condition && a("x") < b("y")), Seq(Row(0L, 1L))) + // A call that reads one side stays in the join. + checkAnswer( + a.join(b, addOne(a("x")) === b("y"), "left_outer"), + Seq(Row(0L, 1L), Row(1L, 2L), Row(2L, 3L), Row(3L, 4L), Row(4L, null))) + checkError( + exception = intercept[AnalysisException] { + a.join(b, condition, "left_outer").collect() + }, + condition = "UNSUPPORTED_FEATURE.COLUMNAR_UDF_IN_JOIN_CONDITION", + parameters = Map("joinType" -> "LEFT OUTER")) + } + + test("a call in a correlated subquery that reads both sides") { + withFunctions(add) { + withTempView("a", "b") { + spark.range(5).toDF("x").createOrReplaceTempView("a") + spark.range(5).toDF("y").createOrReplaceTempView("b") + val exists = "EXISTS (SELECT 1 FROM b WHERE add(a.x, b.y) = 1)" + // The subquery becomes a semi join, or an existence join below a disjunction. + Seq(s"SELECT * FROM a WHERE $exists" -> "LEFT SEMI", + s"SELECT * FROM a WHERE a.x > 3 OR $exists" -> "EXISTENCE").foreach { + case (query, joinType) => + checkError( + exception = intercept[AnalysisException](sql(query).collect()), + condition = "UNSUPPORTED_FEATURE.COLUMNAR_UDF_IN_JOIN_CONDITION", + parameters = Map("joinType" -> joinType)) + } + // A call that reads one side is evaluated below the join. + checkAnswer( + sql("SELECT * FROM a WHERE EXISTS (SELECT 1 FROM b WHERE add(b.y, b.y) = a.x)"), + Seq(Row(0L), Row(2L), Row(4L))) + } + } + } + + test("a call in an equality between the sides of a join is a join key") { + withFunctions(addOne) { + withTempView("a", "b") { + spark.range(5).toDF("x").createOrReplaceTempView("a") + spark.range(5).toDF("y").createOrReplaceTempView("b") + val df = sql("SELECT * FROM a, b WHERE add_one(a.x) = b.y") + checkAnswer(df, (0 until 4).map(i => Row(i.toLong, i + 1L))) + val joins = df.queryExecution.optimizedPlan.collect { case j: Join => j } + assert(joins.length == 1 && joins.head.condition.isDefined) + // In a join of three relations, which the optimizer can reorder. + val threeWay = sql( + "SELECT a.x, b.y, c.x FROM a, b, a c WHERE add_one(a.x) = b.y AND b.y = c.x") + checkAnswer(threeWay, (0 until 4).map(i => Row(i.toLong, i + 1L, i + 1L))) + assert(threeWay.queryExecution.optimizedPlan.collect { case j: Join => j } + .forall(_.condition.isDefined)) + } + } + } + + test("a filter over the result of a call does not evaluate the call again") { + val df = spark.range(10).select(addOne(col("id")).as("r")).filter(col("r") > 5) + checkAnswer(df, (6 to 10).map(i => Row(i.toLong))) + assert(evalNodes(df.queryExecution.executedPlan).length == 1) + // Over a file scan, with the file source of both DSv1 and DSv2. + withTempPath { path => + spark.range(10).write.parquet(path.getCanonicalPath) + Seq("parquet", "").foreach { useV1SourceList => + withSQLConf(SQLConf.USE_V1_SOURCE_LIST.key -> useV1SourceList) { + val scan = spark.read.parquet(path.getCanonicalPath) + .select(addOne(col("id")).as("r")).filter(col("r") > 5) + checkAnswer(scan, (6 to 10).map(i => Row(i.toLong))) + assert(evalNodes(scan.queryExecution.executedPlan).length == 1) + } + } + } + } + + test("a call in a filter over a partition column") { + withTempPath { path => + spark.range(20).selectExpr("id", "id % 4 as p") + .write.partitionBy("p").parquet(path.getCanonicalPath) + // With the file source of both DSv1 and DSv2. + Seq("parquet", "").foreach { useV1SourceList => + withSQLConf(SQLConf.USE_V1_SOURCE_LIST.key -> useV1SourceList) { + val df = spark.read.parquet(path.getCanonicalPath) + .filter(addOne(col("p")) === 2 && col("id") > 1) + checkAnswer(df, Seq(5, 9, 13, 17).map(i => Row(i.toLong, 1L))) + assert(evalNodes(df.queryExecution.executedPlan).length == 1) + } + } + } + } + + test("a call in the creation side of a runtime bloom filter") { + withFunctions(addOne) { + withSQLConf( + SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1", + SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key -> "1") { + withTempPath { path => + val big = s"${path.getCanonicalPath}/big" + val small = s"${path.getCanonicalPath}/small" + spark.range(1000).selectExpr("id % 100 as k").write.parquet(big) + spark.range(100).selectExpr("id as k", "id as v").write.parquet(small) + withTempView("big", "small") { + spark.read.parquet(big).createOrReplaceTempView("big") + spark.read.parquet(small).createOrReplaceTempView("small") + def query(filter: String): DataFrame = + sql(s"SELECT count(*) FROM big JOIN small ON big.k = small.k WHERE $filter") + def hasBloomFilter(df: DataFrame): Boolean = df.queryExecution.optimizedPlan.exists { + _.expressions.exists(_.exists(_.isInstanceOf[BloomFilterMightContain])) + } + // The subquery of a bloom filter is planned on its own, after the calls of the + // query are extracted, so a creation side with a call gets no bloom filter. + assert(hasBloomFilter(query("small.v + 1 = 5"))) + val df = query("add_one(small.v) = 5") + assert(!hasBloomFilter(df)) + checkAnswer(df, Row(10L)) + } + } + } + } + } + + test("a function that is not deterministic in grouping and sort keys") { + val counter = ColumnarUserDefinedFunction.create( + "counter", Seq(LongType), LongType, new CounterFunction).asNondeterministic() + val grouped = spark.range(0, 10, 1, 1).groupBy(counter(col("id"))).count() + checkAnswer(grouped, (1 to 10).map(i => Row(i.toLong, 1L))) + val sorted = spark.range(0, 10, 1, 1).orderBy(counter(col("id")).desc) + assert(sorted.collect().toSeq == (0 until 10).reverse) + } + + test("a call is a call of a user-defined function") { + val call = addOne(col("id")).expr + assert(call.isInstanceOf[UserDefinedExpression]) + // A CHECK constraint or a generated column cannot store it. + val found = StoredExpressionFunctions.findUserDefinedFunctionCall( + spark.range(1).select(addOne(col("id"))).queryExecution.analyzed.expressions.head) + assert(found.map(_._2) == Some("`add_one`")) + // Single-task execution leaves a query that runs user code alone. + val optimized = spark.range(1).select(addOne(col("id"))).queryExecution.optimizedPlan + assert(optimized.containsAnyPattern(MarkSingleTaskExecution.unsupportedPatterns: _*)) + } + + test("plans with equal calls are equal once their expression ids are normalized") { + def plan: LogicalPlan = spark.range(5).select(addOne(col("id"))).queryExecution.analyzed + assert(plan != plan) + assert(NormalizePlan.normalizeExprIds(plan) == NormalizePlan.normalizeExprIds(plan)) + } + + test("a call in a lambda function is not supported") { + withFunctions(addOne) { + // At the top level of a lambda function, and in a nested one. + Seq( + "transform(array(1L, 2L), x -> add_one(x))", + "transform(array(array(1L)), xs -> transform(xs, x -> add_one(x)))").foreach { expr => + checkError( + exception = intercept[AnalysisException](sql(s"SELECT $expr")), + condition = "UNSUPPORTED_FEATURE.LAMBDA_FUNCTION_WITH_COLUMNAR_UDF", + parameters = Map("funcName" -> "\"add_one(namedlambdavariable())\""), + queryContext = Array(ExpectedContext(fragment = expr, start = 7, stop = 6 + expr.length))) + } + } + } + + test("a call with named arguments is not supported") { + withFunctions(addOne) { + checkError( + exception = intercept[AnalysisException] { + sql("SELECT add_one(x => id) FROM range(3)") + }, + condition = "NAMED_PARAMETERS_NOT_SUPPORTED", + parameters = Map("functionName" -> "`add_one`"), + context = ExpectedContext("add_one(x => id)", 7, 22)) + } + } + + test("equal calls of a function that is not deterministic are evaluated separately") { + val counter = ColumnarUserDefinedFunction.create( + "counter", Seq(LongType), LongType, new CounterFunction).asNondeterministic() + val df = spark.range(0, 10, 1, 1).select(counter(col("id")), counter(col("id"))) + val rows = df.collect() + assert(rows.length == 10) + assert(rows.forall(r => r.getLong(0) != r.getLong(1))) + val node = evalNodes(df.queryExecution.executedPlan).head + assert(node.udfs.length == 2) + + // Equal calls of a deterministic function share a result. + val shared = spark.range(5).select(addOne(col("id")), addOne(col("id")) + 1) + checkAnswer(shared, (0 until 5).map(i => Row(i + 1L, i + 2L))) + assert(evalNodes(shared.queryExecution.executedPlan).head.udfs.length == 1) + } + + test("a call below a limit") { + val df = spark.range(100000).select(addOne(col("id"))).limit(3) + assert(df.collect().length == 3) + val sorted = spark.range(100).select(addOne(col("id")).as("r")).orderBy(col("r").desc).limit(2) + checkAnswer(sorted, Seq(Row(100L), Row(99L))) + } + + test("strings and nulls") { + val df = Seq(Some("a"), None, Some("bc")).toDF("s").select(shout(col("s"))) + checkAnswer(df, Seq(Row("A!"), Row(null), Row("BC!"))) + } + + test("a function that Spark cannot run fails when it is executed") { + val engineOnly = ColumnarUserDefinedFunction.create("engine_only", Seq(LongType), LongType) + .withEngineImplementation(ColumnarUDFImplementation.create( + "some-engine", Map("library" -> "/lib.so", "name" -> "f"))) + val df = spark.range(5).select(engineOnly(col("id"))) + // It is planned, with its implementations on the node, for an engine to replace. + val node = evalNodes(df.queryExecution.executedPlan).head + assert(node.udfs.head.engineImplementations.map(_.kind) == Seq("some-engine")) + checkError( + exception = intercept[SparkUnsupportedOperationException](df.collect()), + condition = "COLUMNAR_UDF_NOT_EXECUTABLE", + parameters = Map("name" -> "engine_only", "kinds" -> "[some-engine]")) + } + + test("a function that returns one of its arguments fails") { + val identity = ColumnarUserDefinedFunction.create( + "identity", Seq(LongType), LongType, new ReturnArgumentFunction) + withTempPath { path => + spark.range(10).write.parquet(path.getCanonicalPath) + // Over a columnar scan, and over a row-based child. + Seq(spark.read.parquet(path.getCanonicalPath), spark.range(10).toDF()).foreach { input => + checkError( + exception = intercept[SparkRuntimeException](input.select(identity(col("id"))).collect()), + condition = "COLUMNAR_UDF_RESULT_IS_ARGUMENT", + parameters = Map("name" -> "identity")) + } + } + } + + test("a function that returns a vector of another type fails") { + val wrongType = ColumnarUserDefinedFunction.create( + "wrong_type", Seq(StringType), LongType, new ShoutFunction) + val df = Seq("a").toDF("s").select(wrongType(col("s"))) + checkError( + exception = intercept[SparkRuntimeException](df.collect()), + condition = "COLUMNAR_UDF_RESULT_TYPE_MISMATCH", + parameters = Map( + "name" -> "wrong_type", "actualType" -> "\"STRING\"", "expectedType" -> "\"BIGINT\"")) + } + + test("a function that returns a field of one of its arguments fails") { + val structType = StructType(Seq(StructField("id", LongType))) + val field = ColumnarUserDefinedFunction.create( + "field", Seq(structType), LongType, new ReturnFieldFunction) + val df = spark.range(10).select(field(struct(col("id")))) + checkError( + exception = intercept[SparkRuntimeException](df.collect()), + condition = "COLUMNAR_UDF_RESULT_IS_ARGUMENT", + parameters = Map("name" -> "field")) + } + + test("a function that returns the elements or the keys of one of its arguments fails") { + val element = ColumnarUserDefinedFunction.create( + "element", Seq(ArrayType(LongType)), LongType, new ReturnFieldFunction) + val key = ColumnarUserDefinedFunction.create( + "key", Seq(MapType(LongType, LongType)), LongType, new ReturnFieldFunction) + withTempPath { path => + spark.range(10).select(array(col("id")).as("a"), map(col("id"), col("id")).as("m")) + .write.parquet(path.getCanonicalPath) + // Over a columnar scan, and over a row-based child. + Seq( + spark.read.parquet(path.getCanonicalPath), + spark.range(10).select(array(col("id")).as("a"), map(col("id"), col("id")).as("m")) + ).foreach { input => + checkError( + exception = intercept[SparkRuntimeException](input.select(element(col("a"))).collect()), + condition = "COLUMNAR_UDF_RESULT_IS_ARGUMENT", + parameters = Map("name" -> "element")) + checkError( + exception = intercept[SparkRuntimeException](input.select(key(col("m"))).collect()), + condition = "COLUMNAR_UDF_RESULT_IS_ARGUMENT", + parameters = Map("name" -> "key")) + } + } + } + + test("a function that returns no vector fails") { + val noVector = ColumnarUserDefinedFunction.create( + "no_vector", Seq(LongType), LongType, new NullFunction) + checkError( + exception = intercept[SparkRuntimeException] { + spark.range(5).select(noVector(col("id"))).collect() + }, + condition = "COLUMNAR_UDF_RESULT_TYPE_MISMATCH", + parameters = Map( + "name" -> "no_vector", "actualType" -> "NULL", "expectedType" -> "\"BIGINT\"")) + } + + test("a function that fails") { + val failing = ColumnarUserDefinedFunction.create( + "failing", Seq(LongType), LongType, new FailingFunction) + val e = intercept[SparkException] { + spark.range(5).select(failing(col("id"))).collect() + } + checkError( + exception = e, + condition = "FAILED_EXECUTE_UDF", + parameters = Map( + "functionName" -> "`failing`", + "signature" -> "bigint", + "result" -> "bigint", + "reason" -> "java.lang.ArithmeticException: boom")) + assert(e.getCause.isInstanceOf[ArithmeticException]) + } + + test("a result of a user-defined type") { + val point = ColumnarUserDefinedFunction.create( + "point", Seq(LongType), new ExamplePointUDT, new PointFunction) + val df = spark.range(3).select(point(col("id"))) + checkAnswer(df, (0 until 3).map(i => Row(new ExamplePoint(i.toDouble, i.toDouble)))) + } + + test("the nodes of a stage do not share an instance of a function") { + val counter = ColumnarUserDefinedFunction.create( + "counter", Seq(LongType), LongType, new CounterFunction).asNondeterministic() + // Nested calls are evaluated by two nodes. With an instance of its own, the outer one + // counts from one. + val df = spark.range(0, 5, 1, 1).select(counter(counter(col("id")))) + assert(evalNodes(df.queryExecution.executedPlan).length == 2) + checkAnswer(df, (1 to 5).map(i => Row(i.toLong))) + } + + test("several batches in a partition") { + withSQLConf( + SQLConf.COLUMN_BATCH_SIZE.key -> "7", + SQLConf.PARQUET_VECTORIZED_READER_BATCH_SIZE.key -> "7") { + withTempPath { path => + spark.range(0, 100, 1, 1).selectExpr("id", "concat('s', id) as s") + .write.parquet(path.getCanonicalPath) + // Over a columnar scan, and over a row-based child. + Seq( + spark.read.parquet(path.getCanonicalPath), + spark.range(0, 100, 1, 1).selectExpr("id", "concat('s', id) as s")).foreach { input => + val df = input.select(col("id"), addOne(col("id")), shout(col("s"))) + checkAnswer(df, (0 until 100).map(i => Row(i.toLong, i + 1L, s"S$i!"))) + val node = evalNodes(df.queryExecution.executedPlan).head + assert(node.metrics("numOutputBatches").value > 10) + } + // A limit stops the node after at most one batch more than it needs. + val limited = spark.read.parquet(path.getCanonicalPath).select(addOne(col("id"))).limit(3) + assert(limited.collect().length == 3) + val node = evalNodes(limited.queryExecution.executedPlan).head + assert(node.metrics("numOutputBatches").value <= 2) + } + } + } + + test("a filter over a plain column is pushed below the calls of the same filter") { + withTempPath { path => + spark.range(100).write.parquet(path.getCanonicalPath) + val df = spark.read.parquet(path.getCanonicalPath) + .filter(addOne(col("id")) > 5 && col("id") < 50) + checkAnswer(df, (5 until 50).map(i => Row(i.toLong))) + val below = df.queryExecution.optimizedPlan.collectFirst { + case e: EvalColumnarUDFs => e.child + }.get + assert(below.exists(_.isInstanceOf[Filter])) + } + } + + test("the logical node has the row bounds of its child") { + val plan = spark.range(3).select(addOne(col("id"))).queryExecution.optimizedPlan + val node = plan.collectFirst { case e: EvalColumnarUDFs => e }.get + assert(node.maxRows.contains(3L)) + assert(node.maxRowsPerPartition == node.child.maxRowsPerPartition) + } + + test("calls in subqueries") { + withFunctions(addOne) { + withTempView("t") { + spark.range(5).toDF("v").createOrReplaceTempView("t") + // An uncorrelated scalar subquery. + checkAnswer(sql("SELECT (SELECT add_one(max(id)) FROM range(10))"), Row(10L)) + // A correlated scalar subquery. + checkAnswer( + sql("SELECT id, (SELECT max(add_one(v)) FROM t WHERE t.v = r.id) FROM range(2) r"), + Seq(Row(0L, 1L), Row(1L, 2L))) + // Correlated EXISTS and IN subqueries, where the call reads one side. + checkAnswer( + sql("SELECT * FROM range(3) r WHERE EXISTS (SELECT 1 FROM t WHERE add_one(t.v) = r.id)"), + Seq(Row(1L), Row(2L))) + checkAnswer( + sql("SELECT * FROM range(3) r WHERE r.id IN (SELECT add_one(v) FROM t)"), + Seq(Row(1L), Row(2L))) + } + } + } + + test("a call with a wrong number of arguments") { + checkError( + exception = intercept[AnalysisException](addOne(col("id"), col("id"))), + condition = "WRONG_NUM_ARGS.WITHOUT_SUGGESTION", + parameters = Map( + "functionName" -> "`add_one`", + "expectedNum" -> "1", + "actualNum" -> "2", + "docroot" -> SPARK_DOC_ROOT)) + } + + test("a qualified FILE result type cannot be registered") { + withSQLConf(SQLConf.FILE_TYPE_ENABLED.key -> "true") { + val file = ColumnarUserDefinedFunction.create( + "file_udf", Seq(LongType), FileType.external, new AddOneFunction) + checkError( + exception = intercept[AnalysisException](spark.udf.registerColumnar(file)), + condition = "FILE_TYPE_IN_ROUTINE_SIGNATURE_UNSUPPORTED_QUALIFIER", + parameters = Map("routineName" -> "`file_udf`")) + } + } + + test("CHAR and VARCHAR in the types of a function") { + val result = ColumnarUserDefinedFunction.create( + "varchar_result", Seq(StringType), VarcharType(3), new ShoutFunction) + val argument = ColumnarUserDefinedFunction.create( + "char_argument", Seq(ArrayType(CharType(3))), LongType, new AddOneFunction) + Seq(result, argument).foreach { udf => + checkError( + exception = intercept[AnalysisException](udf(col("s"))), + condition = "UNSUPPORTED_CHAR_OR_VARCHAR_AS_STRING", + parameters = Map.empty) + } + withUserDefinedFunction("varchar_result" -> true) { + spark.udf.registerColumnar(result) + checkError( + exception = intercept[AnalysisException](sql("SELECT varchar_result('a')")), + condition = "UNSUPPORTED_CHAR_OR_VARCHAR_AS_STRING", + parameters = Map.empty, + context = ExpectedContext(fragment = "varchar_result('a')", start = 7, stop = 25)) + } + // With the legacy conf, they are replaced with STRING. + withSQLConf(SQLConf.LEGACY_CHAR_VARCHAR_AS_STRING.key -> "true") { + val df = spark.range(1).select(result(lit("abc")).as("r")) + assert(df.schema("r").dataType == StringType) + assert(evalNodes(df.queryExecution.executedPlan).head.udfs.head.inputTypes == Review Comment: **[41] Nit: the assertion of the legacy case holds without the change.** `result` is declared with `Seq(StringType)`, so its `inputTypes` are `Seq(StringType)` whether or not `builder` replaces CHAR and VARCHAR in the argument types. This assertion still passes if `builder` passes `inputTypes` as they are. `argument`, whose `ARRAY<CHAR(3)>` argument type is the one that this conf changes, is not checked under it. Could this case also check the argument types of a call of `argument`, e.g. that `argument(array(lit("a"))).expr` has the `inputTypes` `Seq(ArrayType(StringType))`? ########## 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) Review Comment: **[38] With first-class CHAR and VARCHAR, a function that returns a STRING vector for a VARCHAR result fails.** When `spark.sql.preserveCharVarcharTypeInfo` or `spark.sql.charVarchar.standardSemantics.enabled` is on, `failIfHasCharVarchar` returns the type as it is (`SparkCharVarcharUtils.scala` L47-L50), so the call keeps `VARCHAR(3)` as its type. `EvalColumnarUDFsExec` then compares the type of the returned vector with `DataType.equalsStructurally` (`EvalColumnarUDFsExec.scala` L201-L202), whose last case is `==` (`DataType.scala` L787), and `StringType.equals` also compares the length constraint (`StringType.scala` L89-L93). So a `STRING` vector does not match `VARCHAR(3)`. In this case the new test only checks `call.dataType` (`ColumnarUDFSuite.scala` L734-L737). If it ran the call: ```scala withSQLConf(SQLConf.PRESERVE_CHAR_VARCHAR_TYPE_INFO.key -> "true") { spark.range(1).select(result(lit("abc"))).collect() } ``` `ShoutFunction` returns an `OnHeapColumnVector` of `StringType`, and the query fails with `COLUMNAR_UDF_RESULT_TYPE_MISMATCH`, which says that the function returned `STRING` but its return type is `VARCHAR(3)`. To pass, a function has to build its vector with `VarcharType(3)`, and then the node does not check that the values fit in 3 characters. Could the check compare the types after replacing CHAR and VARCHAR with STRING, as `EvalColumnarUDFsExec.scala` L113-L115 does for a user-defined type, or could the docs say which vector type a CHAR or VARCHAR result needs? Either way, the test could run the call. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ColumnarUDF.scala: ########## @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.catalyst.expressions + +import org.apache.spark.sql.catalyst.trees.TreePattern.{COLUMNAR_UDF, TreePattern} +import org.apache.spark.sql.columnar.{ColumnarScalarFunction, ColumnarUDFImplementation} +import org.apache.spark.sql.types.{AbstractDataType, DataType} + +/** + * A call of a columnar user-defined function: a scalar function that is evaluated one batch at + * a time, by the `EvalColumnarUDFs` operator that `ExtractColumnarUDFs` plans for it. + * + * A function has any number of implementations. Spark can run `function`, in the JVM. The + * others, `engineImplementations`, are for engines that replace Spark's operators, and Spark + * only carries them. A function without `function` fails when Spark has to run it. + * + * @param name the name of the function + * @param function the implementation that Spark runs, if there is one + * @param engineImplementations the implementations for other engines + * @param inputTypes the types of the arguments, which the analyzer casts the arguments to + * @param dataType the type of the result + * @param children the arguments + * @param udfDeterministic whether the function returns the same result for the same arguments + * @param udfNullable whether the function can return null + * @param resultId the id of the call, which tells two calls of a function that is not + * deterministic apart + */ +case class ColumnarUDF( + name: String, + function: Option[ColumnarScalarFunction], + engineImplementations: Seq[ColumnarUDFImplementation], + inputTypes: Seq[AbstractDataType], + dataType: DataType, + children: Seq[Expression], + udfDeterministic: Boolean = true, + udfNullable: Boolean = true, + resultId: ExprId = NamedExpression.newExprId) + extends Expression with Unevaluable with ImplicitCastInputTypes with UserDefinedExpression { + + override lazy val deterministic: Boolean = udfDeterministic && children.forall(_.deterministic) + + override def nullable: Boolean = udfNullable + + // A call runs user code, so the optimizer does not move a filter below the projection that + // computes it, which would evaluate the call a second time. + override def expensive: Boolean = true + + override lazy val canonicalized: Expression = { + // `resultId` does not affect the result, so that equal calls of a deterministic function + // are evaluated once. + copy(resultId = ExprId(-1)).withNewChildren(children.map(_.canonicalized)) + } + + final override val nodePatterns: Seq[TreePattern] = Seq(COLUMNAR_UDF) + + override def prettyName: String = name + + override def toString: String = s"$name(${children.mkString(", ")})" Review Comment: **[43] Nit: `toString` leaves out `resultId`, unlike `PythonUDF`.** `PythonUDF.toString` ends with the `resultId` (`PythonUDF.scala` L304), so a plan shows which calls are evaluated separately. Here two calls of a function that is not deterministic both print as `counter(id)`, in `EvalColumnarUDFs` and in `EXPLAIN`. A plan then cannot tell two calls, as in the test "equal calls of a function that is not deterministic are evaluated separately", from one call that appears twice, as in [37]. Could it add the `resultId`, at least for a call of a function that is not deterministic? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/EvalColumnarUDFsExec.scala: ########## @@ -0,0 +1,225 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.execution.columnar.udf + +import scala.util.control.NonFatal + +import org.apache.spark.{SparkException, SparkRuntimeException, SparkUnsupportedOperationException, TaskContext} +import org.apache.spark.rdd.RDD +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet, BindReferences, BoundReference, ColumnarUDF, SortOrder} +import org.apache.spark.sql.catalyst.plans.logical.{EvalColumnarUDFs, LogicalPlan} +import org.apache.spark.sql.catalyst.plans.physical.Partitioning +import org.apache.spark.sql.catalyst.util.TypeUtils.toSQLType +import org.apache.spark.sql.columnar.ColumnarScalarFunction +import org.apache.spark.sql.errors.QueryExecutionErrors +import org.apache.spark.sql.execution.{SparkPlan, SparkStrategy, UnaryExecNode} +import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics} +import org.apache.spark.sql.execution.vectorized.WritableColumnVector +import org.apache.spark.sql.types.{DataType, StructType, UserDefinedType} +import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnVector} +import org.apache.spark.util.Utils + +/** Plans the evaluation of columnar user-defined functions. */ +object ColumnarUDFEvals extends SparkStrategy { + override def apply(plan: LogicalPlan): Seq[SparkPlan] = plan match { + case EvalColumnarUDFs(udfs, resultAttrs, child) => + EvalColumnarUDFsExec(udfs, resultAttrs, planLater(child)) :: Nil + case _ => Nil + } +} + +/** + * Evaluates calls of columnar user-defined functions, one batch at a time. The input and the + * output are columnar: an output batch is the columns of the input batch, as they are, followed + * by one column per call. The arguments of the calls are columns of the child. + * + * This node runs the implementation of each function that Spark can run, its + * [[ColumnarScalarFunction]]. An engine that replaces Spark's operators can replace this node + * with one that runs another implementation, from `ColumnarUDF.engineImplementations`. A + * function that Spark cannot run fails only when this node is executed, so that such an engine + * has replaced the node by then. + */ +case class EvalColumnarUDFsExec( + udfs: Seq[ColumnarUDF], + resultAttrs: Seq[Attribute], + child: SparkPlan) extends UnaryExecNode { + + override def output: Seq[Attribute] = child.output ++ resultAttrs + + override def producedAttributes: AttributeSet = AttributeSet(resultAttrs) + + override def outputPartitioning: Partitioning = child.outputPartitioning + + override def outputOrdering: Seq[SortOrder] = child.outputOrdering + + override def supportsColumnar: Boolean = true + + override lazy val metrics: Map[String, SQLMetric] = Map( + "numOutputRows" -> SQLMetrics.createMetric(sparkContext, "number of output rows"), + "numOutputBatches" -> SQLMetrics.createMetric(sparkContext, "number of output batches"), + "evalTime" -> SQLMetrics.createNanoTimingMetric(sparkContext, "time in functions")) + + override protected def doExecute(): RDD[InternalRow] = { + throw SparkException.internalError(s"$nodeName only supports columnar execution.") + } + + override protected def doExecuteColumnar(): RDD[ColumnarBatch] = { + val driverFunctions: Array[ColumnarScalarFunction] = udfs.map { udf => + udf.function.getOrElse { + throw new SparkUnsupportedOperationException( + errorClass = "COLUMNAR_UDF_NOT_EXECUTABLE", + messageParameters = Map( + "name" -> udf.name, + "kinds" -> udf.engineImplementations.map(_.kind).mkString("[", ", ", "]"))) + } + }.toArray + // The closures of the nodes of a stage are serialized together, so the nodes would share one + // instance of a function that several of them call, and an operator between them can read + // its child from another thread. The functions are serialized apart here, so that each + // partition of this node reads its own instances, which only this node calls. + val serializedFunctions: Array[Byte] = Utils.serialize(driverFunctions) + // The ordinals, in the input batch, of the arguments of each call. + val argOrdinals: Array[Array[Int]] = udfs.map { udf => + udf.children.map { arg => + BindReferences.bindReference(arg, child.output) match { + case b: BoundReference => b.ordinal + case other => throw SparkException.internalError( + s"The argument $other of ${udf.name} is not a column of the child.") + } + }.toArray + }.toArray + val names: Array[String] = udfs.map(_.name).toArray + val inputTypeStrings: Array[String] = + udfs.map(_.children.map(_.dataType.catalogString).mkString(", ")).toArray + val resultTypes: Array[DataType] = udfs.map(_.dataType).toArray + // A column vector has the SQL type of a user-defined type, so the type of a result is + // compared with the declared type after the same replacement. + val resultVectorTypes: Array[DataType] = resultTypes.map(_.transformRecursively { + case udt: UserDefinedType[_] => udt.sqlType + }) + val numOutputRows = longMetric("numOutputRows") + val numOutputBatches = longMetric("numOutputBatches") + val evalTime = longMetric("evalTime") + val numInputColumns = child.output.length + val numFunctions = udfs.length + + child.executeColumnar().mapPartitionsInternal { batches => + new Iterator[ColumnarBatch] { + private val functions = Utils.deserialize[Array[ColumnarScalarFunction]]( + serializedFunctions, Utils.getContextOrSparkClassLoader) + + // The results of the current batch, which this node owns. + private var results: Array[ColumnVector] = Array.empty + + private def closeResults(): Unit = { + results.foreach(r => if (r != null) r.close()) + results = Array.empty + } + + Option(TaskContext.get()).foreach(_.addTaskCompletionListener[Unit](_ => closeResults())) + + // Whether `vector` is `column` or 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 new SparkRuntimeException( Review Comment: **[44] Nit: the three errors of this node are built inline, not by `QueryExecutionErrors`.** `COLUMNAR_UDF_NOT_EXECUTABLE` (L85), `COLUMNAR_UDF_RESULT_IS_ARGUMENT` (here) and `COLUMNAR_UDF_RESULT_TYPE_MISMATCH` (L204) are created in this node with their message parameters. The join condition error of this PR is a method of `QueryCompilationErrors`, and the Python evaluation nodes raise theirs through `QueryExecutionErrors` methods, e.g. `arrowDataTypeMismatchError` (`ArrowEvalPythonExec.scala` L270). Could these three also be methods of `QueryExecutionErrors`? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/EvalColumnarUDFsExec.scala: ########## @@ -0,0 +1,225 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.execution.columnar.udf + +import scala.util.control.NonFatal + +import org.apache.spark.{SparkException, SparkRuntimeException, SparkUnsupportedOperationException, TaskContext} +import org.apache.spark.rdd.RDD +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet, BindReferences, BoundReference, ColumnarUDF, SortOrder} +import org.apache.spark.sql.catalyst.plans.logical.{EvalColumnarUDFs, LogicalPlan} +import org.apache.spark.sql.catalyst.plans.physical.Partitioning +import org.apache.spark.sql.catalyst.util.TypeUtils.toSQLType +import org.apache.spark.sql.columnar.ColumnarScalarFunction +import org.apache.spark.sql.errors.QueryExecutionErrors +import org.apache.spark.sql.execution.{SparkPlan, SparkStrategy, UnaryExecNode} +import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics} +import org.apache.spark.sql.execution.vectorized.WritableColumnVector +import org.apache.spark.sql.types.{DataType, StructType, UserDefinedType} +import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnVector} +import org.apache.spark.util.Utils + +/** Plans the evaluation of columnar user-defined functions. */ +object ColumnarUDFEvals extends SparkStrategy { + override def apply(plan: LogicalPlan): Seq[SparkPlan] = plan match { + case EvalColumnarUDFs(udfs, resultAttrs, child) => + EvalColumnarUDFsExec(udfs, resultAttrs, planLater(child)) :: Nil + case _ => Nil + } +} + +/** + * Evaluates calls of columnar user-defined functions, one batch at a time. The input and the + * output are columnar: an output batch is the columns of the input batch, as they are, followed + * by one column per call. The arguments of the calls are columns of the child. + * + * This node runs the implementation of each function that Spark can run, its + * [[ColumnarScalarFunction]]. An engine that replaces Spark's operators can replace this node + * with one that runs another implementation, from `ColumnarUDF.engineImplementations`. A + * function that Spark cannot run fails only when this node is executed, so that such an engine + * has replaced the node by then. + */ +case class EvalColumnarUDFsExec( + udfs: Seq[ColumnarUDF], + resultAttrs: Seq[Attribute], + child: SparkPlan) extends UnaryExecNode { + + override def output: Seq[Attribute] = child.output ++ resultAttrs + + override def producedAttributes: AttributeSet = AttributeSet(resultAttrs) + + override def outputPartitioning: Partitioning = child.outputPartitioning + + override def outputOrdering: Seq[SortOrder] = child.outputOrdering + + override def supportsColumnar: Boolean = true + + override lazy val metrics: Map[String, SQLMetric] = Map( + "numOutputRows" -> SQLMetrics.createMetric(sparkContext, "number of output rows"), + "numOutputBatches" -> SQLMetrics.createMetric(sparkContext, "number of output batches"), + "evalTime" -> SQLMetrics.createNanoTimingMetric(sparkContext, "time in functions")) + + override protected def doExecute(): RDD[InternalRow] = { + throw SparkException.internalError(s"$nodeName only supports columnar execution.") + } + + override protected def doExecuteColumnar(): RDD[ColumnarBatch] = { + val driverFunctions: Array[ColumnarScalarFunction] = udfs.map { udf => + udf.function.getOrElse { + throw new SparkUnsupportedOperationException( + errorClass = "COLUMNAR_UDF_NOT_EXECUTABLE", + messageParameters = Map( + "name" -> udf.name, + "kinds" -> udf.engineImplementations.map(_.kind).mkString("[", ", ", "]"))) + } + }.toArray + // The closures of the nodes of a stage are serialized together, so the nodes would share one + // instance of a function that several of them call, and an operator between them can read + // its child from another thread. The functions are serialized apart here, so that each + // partition of this node reads its own instances, which only this node calls. + val serializedFunctions: Array[Byte] = Utils.serialize(driverFunctions) + // The ordinals, in the input batch, of the arguments of each call. + val argOrdinals: Array[Array[Int]] = udfs.map { udf => + udf.children.map { arg => + BindReferences.bindReference(arg, child.output) match { + case b: BoundReference => b.ordinal + case other => throw SparkException.internalError( + s"The argument $other of ${udf.name} is not a column of the child.") + } + }.toArray + }.toArray + val names: Array[String] = udfs.map(_.name).toArray + val inputTypeStrings: Array[String] = + udfs.map(_.children.map(_.dataType.catalogString).mkString(", ")).toArray + val resultTypes: Array[DataType] = udfs.map(_.dataType).toArray + // A column vector has the SQL type of a user-defined type, so the type of a result is + // compared with the declared type after the same replacement. + val resultVectorTypes: Array[DataType] = resultTypes.map(_.transformRecursively { + case udt: UserDefinedType[_] => udt.sqlType + }) + val numOutputRows = longMetric("numOutputRows") + val numOutputBatches = longMetric("numOutputBatches") + val evalTime = longMetric("evalTime") + val numInputColumns = child.output.length + val numFunctions = udfs.length + + child.executeColumnar().mapPartitionsInternal { batches => + new Iterator[ColumnarBatch] { + private val functions = Utils.deserialize[Array[ColumnarScalarFunction]]( + serializedFunctions, Utils.getContextOrSparkClassLoader) + + // The results of the current batch, which this node owns. + private var results: Array[ColumnVector] = Array.empty + + private def closeResults(): Unit = { + results.foreach(r => if (r != null) r.close()) + results = Array.empty + } + + Option(TaskContext.get()).foreach(_.addTaskCompletionListener[Unit](_ => closeResults())) + + // Whether `vector` is `column` or 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 new SparkRuntimeException( + errorClass = "COLUMNAR_UDF_RESULT_IS_ARGUMENT", + messageParameters = Map("name" -> names(i))) + } + // Set before the check, so that a vector of the wrong type is closed as well. + newResults(i) = result Review Comment: **[39] The node does not check that a returned vector holds a value for every row.** The Javadoc of `eval` asks for a vector that holds at least `args.numRows()` values, but this loop checks only that the result is not an argument column (L194) and that its type matches (L201-L202). A shorter vector goes into the output batch as it is. For example, a function that returns `new OnHeapColumnVector(1, LongType)` for a batch of 4096 rows passes both checks, and the `ColumnarToRowExec` above then fails with an `ArrayIndexOutOfBoundsException` when it reads the second row. That error names neither the function nor `FAILED_EXECUTE_UDF`. With an `OffHeapColumnVector`, the read goes past the memory of the vector instead, so the query returns garbage or the executor JVM crashes. `ColumnVector` has no public capacity, but most results are `WritableColumnVector`s, whose `capacity` is protected. Could the node check the capacity of such a vector against `numRows`, e.g. through a new getter, and fail with an error that names the function? ########## sql/catalyst/src/main/java/org/apache/spark/sql/columnar/ColumnarScalarFunction.java: ########## @@ -0,0 +1,62 @@ +/* + * 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, such as two calls in one projection, share that instance. Review Comment: **[42] Nit: two calls in one projection share an instance only when one node evaluates them.** This sentence says that two calls in one projection share the instance. Nested calls in one projection, as in `SELECT f(x), f(f(y))`, are evaluated by two nodes, so the outer `f` gets an instance of its own. The test "the nodes of a stage do not share an instance of a function" relies on that. A function that keeps state could be written for the sharing that this sentence promises. Could it say that the calls that one node evaluates share the instance, and that a call whose argument is another call is evaluated by a node of its own? ########## sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/ExtractColumnarUDFs.scala: ########## @@ -0,0 +1,225 @@ +/* + * 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]() + 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 => Alias(other, "agg")() + } + if (!aggregateExpressions.exists(_.exprId == named.exprId)) { Review Comment: **[40] An aggregate function that appears twice gets two aliases, so equal calls over it are evaluated separately.** L125 creates a new `Alias` for each aggregate function or grouping expression that is not a `NamedExpression`. Its `exprId` is always new, so the check at L127 never finds an earlier one. Each occurrence then gets an alias of its own, and the calls over them read different attributes, so `extract` no longer sees them as equal. For example, with `add_one` registered: ```sql SELECT add_one(sum(v)), add_one(sum(v)) + 1 FROM t ``` the `Aggregate` outputs `sum(v)` twice, as two `agg` columns, and the `Project` above it has `add_one(agg#1)` and `add_one(agg#2)`. The node then evaluates `add_one` twice for each group, although equal calls of a deterministic function are meant to be evaluated once. Could L122-L130 reuse the alias of a semantically equal expression, e.g. by keeping the aliases in a map keyed by `e.canonicalized`? -- 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]
