viirya commented on code in PR #60551:
URL: https://github.com/apache/spark/pull/60551#discussion_r4606128987


##########
sql/core/src/main/scala/org/apache/spark/sql/columnar/ColumnarUserDefinedFunction.scala:
##########
@@ -0,0 +1,96 @@
+/*
+ * 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.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.
+ *
+ * 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("add_one", Seq(LongType), 
LongType, Some(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. The 
call is evaluated
+ * without leaving the columnar format when its arguments are columns of a 
columnar source, of

Review Comment:
   Fixed in af8e4337779. The scaladoc now states the condition per operator: 
the calls of one projection or filter are evaluated together, and one argument 
that is not a column of the declared type, or a row-based operator below, puts 
all of them behind a row-based projection.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/columnar/ColumnarUserDefinedFunction.scala:
##########
@@ -0,0 +1,96 @@
+/*
+ * 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.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.
+ *
+ * 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("add_one", Seq(LongType), 
LongType, Some(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. The 
call is evaluated
+ * without leaving the columnar format when its arguments are columns of a 
columnar source, of
+ * the types that the function declares. Any other argument, including one 
that is cast to the
+ * declared type, is computed first by a row-based projection, and its result 
is converted
+ * back to columns for the call.
+ *
+ * Calls with named arguments, and calls inside the lambda function of a 
higher-order function,

Review Comment:
   Fixed in af8e4337779. The list now has both: a call that reads both sides of 
a join is supported only in the condition of an inner join, which includes the 
joins that correlated EXISTS and IN subqueries become, and a conditional 
expression does not guard a call or the expressions that compute its arguments.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckAnalysis.scala:
##########
@@ -612,6 +612,15 @@ trait CheckAnalysis extends LookupCatalog with 
QueryErrorsBase with PlanToString
               errorClass = 
"UNSUPPORTED_FEATURE.LAMBDA_FUNCTION_WITH_PYTHON_UDF",
               messageParameters = Map("funcName" -> toSQLExpr(u)))
 
+          // A columnar UDF is evaluated by an operator of its own, over the 
columns of its
+          // child, so it cannot be evaluated for the elements that a lambda 
function iterates.
+          case hof: HigherOrderFunction
+              if hof.resolved && 
hof.functions.exists(_.exists(_.isInstanceOf[ColumnarUDF])) =>

Review Comment:
   Fixed in af8e4337779: the condition starts with 
`hof.containsPattern(COLUMNAR_UDF)`. The test now uses `checkError` and covers 
a nested lambda.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2873,6 +2877,7 @@ object PushPredicateThroughNonJoin extends 
Rule[LogicalPlan] with PredicateHelpe
     case _: ExecuteExternalUDF => true
     case _: BatchEvalPython => true
     case _: ArrowEvalPython => true
+    case _: EvalColumnarUDFs => true

Review Comment:
   Added in af8e4337779, with the suggested query over Parquet. It asserts that 
the optimized plan has a `Filter` below the `EvalColumnarUDFs` node, not the 
function's row count.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/EvalColumnarUDFsExec.scala:
##########
@@ -0,0 +1,165 @@
+/*
+ * 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 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.execution.{SparkPlan, SparkStrategy, UnaryExecNode}
+import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics}
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnVector}
+
+/** 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 functions: 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 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 resultTypes: Array[DataType] = udfs.map(_.dataType).toArray
+    val numOutputRows = longMetric("numOutputRows")
+    val numOutputBatches = longMetric("numOutputBatches")
+    val evalTime = longMetric("evalTime")
+    val numInputColumns = child.output.length
+
+    child.executeColumnar().mapPartitionsInternal { batches =>
+      new Iterator[ColumnarBatch] {
+        // 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()))
+
+        override def hasNext: Boolean = {
+          val more = batches.hasNext
+          if (!more) closeResults()
+          more
+        }
+
+        override def next(): ColumnarBatch = {

Review Comment:
   Added in af8e4337779: with both batch sizes set to 7 and 100 rows in one 
partition, calls over a Parquet scan and over a row-based child return the 
right values over more than 10 batches, and under `limit(3)` the node outputs 
at most 2 batches. I did not add a vector that counts closes.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/columnar/udf/ColumnarUDFSuite.scala:
##########
@@ -0,0 +1,336 @@
+/*
+ * 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.{SparkRuntimeException, 
SparkUnsupportedOperationException}
+import org.apache.spark.sql.{AnalysisException, QueryTest, Row}
+import org.apache.spark.sql.columnar.{ColumnarScalarFunction, 
ColumnarUDFImplementation, ColumnarUserDefinedFunction}
+import org.apache.spark.sql.execution.{RowToColumnarExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
+import org.apache.spark.sql.execution.vectorized.OnHeapColumnVector
+import org.apache.spark.sql.functions.{col, count, lit, sum}
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{LongType, StringType}
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnVector}
+import org.apache.spark.unsafe.types.UTF8String
+
+/** Adds one to a bigint, and keeps nulls. */
+class AddOneFunction extends ColumnarScalarFunction {
+  override def eval(args: ColumnarBatch): ColumnVector = {
+    val n = args.numRows()
+    val in = args.column(0)
+    val out = new OnHeapColumnVector(n, LongType)
+    var i = 0
+    if (in.hasNull) {
+      while (i < n) {
+        if (in.isNullAt(i)) out.putNull(i) else out.putLong(i, in.getLong(i) + 
1)
+        i += 1
+      }
+    } else {
+      while (i < n) {
+        out.putLong(i, in.getLong(i) + 1)
+        i += 1
+      }
+    }
+    out
+  }
+}
+
+/** Adds two bigints, and returns null if either is null. */
+class AddFunction extends ColumnarScalarFunction {
+  override def eval(args: ColumnarBatch): ColumnVector = {
+    val n = args.numRows()
+    val a = args.column(0)
+    val b = args.column(1)
+    val out = new OnHeapColumnVector(n, LongType)
+    var i = 0
+    while (i < n) {
+      if (a.isNullAt(i) || b.isNullAt(i)) {
+        out.putNull(i)
+      } else {
+        out.putLong(i, a.getLong(i) + b.getLong(i))
+      }
+      i += 1
+    }
+    out
+  }
+}
+
+/** The upper case of a string, followed by an exclamation mark. */
+class ShoutFunction extends ColumnarScalarFunction {
+  override def eval(args: ColumnarBatch): ColumnVector = {
+    val n = args.numRows()
+    val in = args.column(0)
+    val out = new OnHeapColumnVector(n, StringType)
+    var i = 0
+    while (i < n) {
+      if (in.isNullAt(i)) {
+        out.putNull(i)
+      } else {
+        val upper = in.getUTF8String(i).toString.toUpperCase(Locale.ROOT)
+        val bytes = UTF8String.fromString(upper + "!").getBytes
+        out.putByteArray(i, bytes)
+      }
+      i += 1
+    }
+    out
+  }
+}
+
+/** 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
+  }
+}
+
+class ColumnarUDFSuite extends QueryTest with SharedSparkSession with 
AdaptiveSparkPlanHelper {
+  import testImplicits._
+
+  private val addOne =
+    ColumnarUserDefinedFunction("add_one", Seq(LongType), LongType, Some(new 
AddOneFunction))
+  private val add =
+    ColumnarUserDefinedFunction("add", Seq(LongType, LongType), LongType, 
Some(new AddFunction))
+  private val shout =
+    ColumnarUserDefinedFunction("shout", Seq(StringType), StringType, Some(new 
ShoutFunction))
+
+  private def evalNodes(plan: SparkPlan): Seq[EvalColumnarUDFsExec] = 
collect(plan) {
+    case e: EvalColumnarUDFsExec => e
+  }
+
+  /** 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_ON_CLAUSE",
+      parameters = Map("joinType" -> "LEFT OUTER"))
+  }
+
+  test("a call in a lambda function is not supported") {
+    withFunctions(addOne) {
+      val e = intercept[AnalysisException] {
+        sql("SELECT transform(array(1L, 2L), x -> add_one(x))")
+      }
+      assert(e.getCondition == 
"UNSUPPORTED_FEATURE.LAMBDA_FUNCTION_WITH_COLUMNAR_UDF")

Review Comment:
   Added in af8e4337779: the lambda test uses `checkError`, and there are tests 
for a function that returns null (actualType NULL), for a wrong number of 
arguments, and for a qualified FILE result type in `registerColumnar`. A struct 
result with differently named fields is not tested.
   



##########
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

Review Comment:
   Added in af8e4337779: an uncorrelated and a correlated scalar subquery, and 
correlated EXISTS and IN subqueries, checked against the expected rows.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/EvalColumnarUDFsExec.scala:
##########
@@ -0,0 +1,182 @@
+/*
+ * 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 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.execution.{SparkPlan, SparkStrategy, UnaryExecNode}
+import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics}
+import org.apache.spark.sql.types.DataType
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnVector}
+
+/** 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 functions: 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 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 resultTypes: Array[DataType] = udfs.map(_.dataType).toArray
+    val numOutputRows = longMetric("numOutputRows")
+    val numOutputBatches = longMetric("numOutputBatches")
+    val evalTime = longMetric("evalTime")
+    val numInputColumns = child.output.length
+
+    child.executeColumnar().mapPartitionsInternal { batches =>
+      new Iterator[ColumnarBatch] {
+        // 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()))
+
+        private def isInputColumn(batch: ColumnarBatch, vector: ColumnVector): 
Boolean = {
+          var i = 0
+          while (i < numInputColumns) {
+            if (batch.column(i) eq 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 + 
functions.length)
+          var i = 0
+          while (i < numInputColumns) {
+            columns(i) = batch.column(i)
+            i += 1
+          }
+          val start = System.nanoTime()
+          val newResults = new Array[ColumnVector](functions.length)
+          results = newResults
+          i = 0
+          while (i < functions.length) {
+            val args = new ColumnarBatch(argOrdinals(i).map(batch.column), 
numRows)
+            val result = functions(i).eval(args)
+            // 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 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
+            if (result == null ||
+                !DataType.equalsStructurally(result.dataType(), 
resultTypes(i), true)) {

Review Comment:
   Fixed in af8e4337779. The check now replaces every UDT in the declared type 
with its `sqlType`, recursively, before comparing it with the type of the 
returned vector, the same as the `ColumnVector` constructor does. The error 
message still reports the declared type. Added a test with a function that 
returns `ExamplePointUDT`.
   



-- 
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]

Reply via email to