spark-test commented on code in PR #60551:
URL: https://github.com/apache/spark/pull/60551#discussion_r4594444877
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/SparkOptimizer.scala:
##########
@@ -120,6 +121,7 @@ class SparkOptimizer(
ExtractGroupingPythonUDFFromAggregate,
ExtractPythonUDFs,
ExtractPythonUDTFs,
+ ExtractColumnarUDFs,
Review Comment:
**Non-blocking (P2):** `ExtractColumnarUDFs` runs in this batch, after rules
that evaluate expressions themselves or plan a subquery without the optimizer.
Those rules keep only Python UDFs out of what they evaluate (and, in lookup
joins, external UDFs), because, as their comments say, they run before the
extractors. Reading the code, with `t` written by
`partitionBy("p").saveAsTable("t")`, `SELECT * FROM t WHERE add_one(p) > 1`
reaches `PruneFileSourcePartitions`, which keeps `add_one(p) > 1` as a
partition filter and evaluates it for each partition through
`ExternalCatalogUtils.prunePartitionsByFilter`. The query then fails during
optimization with INTERNAL_ERROR `Cannot evaluate expression`, where a Scala
UDF prunes partitions and a Python UDF is kept out of pruning.
`PruneHiveTablePartitions`, `FileScanBuilder.pushFilters` and
`PushDownUtils.isPushablePartitionFilter` do the same. When a join gets a
runtime bloom filter, `InjectRuntimeFilter` treats a creation-side filter or k
ey with a columnar call as simple, and the bloom-filter subquery it builds is
planned without extraction, so the query fails at execution. An external lookup
join keeps a call over lookup columns in a lookup stage, where this rule cannot
reach it. With the internal
`spark.sql.optimizer.dynamicPartitionPruning.reuseBroadcastOnly=false`, the DPP
build plan is also planned without extraction, as it already is for a Python
UDF. A function that has only engine implementations fails the same way, before
any engine can replace `EvalColumnarUDFsExec`.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60551#discussion_r4591907194),
[2](https://github.com/apache/spark/pull/60551#pullrequestreview-5928139680).
See **Shared repair plan 1** in the review body.
##########
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 = {
Review Comment:
**Non-blocking (P2):** `extractFromJoinCondition` and the test `A call that
reads one side stays in the join` assume that a predicate over a columnar call
can become an inner-join condition. `PredicateHelper.canEvaluateWithinJoin`
(predicates.scala:225-229), however, accepts `PythonUDF` and returns `false`
for every other `Unevaluable`. `PushPredicateThroughJoin` and `ReorderJoin`
form inner-join conditions with it, so by the review's reading
`l.join(r).where(addOne(l("x")) === r("y"))`, `SELECT * FROM l, r WHERE
add_one(l.x) = r.y` and `a JOIN b ON add_one(a.x) = b.y JOIN c ON b.z = c.z`
all leave the predicate in a Filter over a join without a condition. The join
runs as a cartesian product, the function is evaluated once per joined row
(1,000,000 rows for two 1000-row sides), and with
`spark.sql.crossJoin.enabled=false` the query fails. The same predicate becomes
an equi-join key in a two-way ON clause, or with a Scala or Python UDF.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60551#discussion_r4591907194),
[2](https://github.com/apache/spark/pull/60551#pullrequestreview-5928139680).
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ColumnarUDF.scala:
##########
@@ -0,0 +1,73 @@
+/*
+ * 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 {
Review Comment:
**Non-blocking (P2):** `ColumnarUDF` is not a `UserDefinedExpression`,
although it already has the trait's only member, `name`, so every check that
recognizes user-defined functions through the trait treats a columnar call as a
built-in expression. Reading the code:
- `StoredExpressionFunctions.findUserDefinedFunctionCall` lets a CHECK
constraint or a generated column call a session's temporary columnar function,
on a catalog that supports them (only connector catalogs do). A write from
another session then resolves the name to another function or to none.
- `NondeterministicExpressionCollection` does not collect a nondeterministic
call. So `groupBy(counter(col("id")))` fails analysis with an INTERNAL_ERROR,
and `orderBy(counter(col("id")))` with `INVALID_NON_DETERMINISTIC_EXPRESSIONS`,
where a nondeterministic Scala UDF is pulled into a Project.
- `checkFileTypeInUserDefinedRoutines` skips the FILE return type of an
unregistered call.
- `InMemoryRelation.hasSafeExpressions`, `PartitionPruning` and
`RewriteWithExpression` trust the call's user-declared determinism and cost.
Suggested fix: mix `UserDefinedExpression` into `ColumnarUDF`.
**Verification:**
- **Regression:** CHECK constraints and generation expressions that call a
registered columnar function are rejected with the same conditions as a Scala
UDF, on a catalog that supports them.
- **Regression:** A nondeterministic columnar call used as a grouping key
and as a sort key runs and returns one value per row.
- **Regression:** An unregistered columnar function whose result type holds
a qualified FILE is rejected when a query uses it, while the FILE type is
enabled.
##########
sql/catalyst/src/main/java/org/apache/spark/sql/columnar/ColumnarScalarFunction.java:
##########
@@ -0,0 +1,55 @@
+/*
+ * 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, where each task gets its
own instance and
Review Comment:
**Non-blocking (P2):** This promise does not hold. `EvalColumnarUDFsExec`
captures `udf.function` in its partition closure, and all closures of a stage
are serialized as one object graph into the task binary. Every node of the
stage, nested calls included, therefore calls the one instance a task
deserializes. When an operator between two calls pulls its child on another
thread, both threads call that instance at once. By the review's reading, in
`SELECT shout(x) FROM (SELECT TRANSFORM(shout(s)) USING 'cat' AS (x STRING)
FROM t)` the script transformation's feed thread evaluates the inner call while
the task thread evaluates the outer one. A function that keeps a buffer in its
instance, as the benchmark's `BenchShout` does, would then write one call's
bytes into the other's values without any error. A Python UDF with
`spark.python.udf.pipelined.enabled=true` between two calls has the same effect.
**Recommended change:** In EvalColumnarUDFsExec, give each partition
iterator its own copy of the functions it calls, for example by serializing the
functions array once when the node executes and deserializing it inside
mapPartitionsInternal, so that two nodes of one stage never share an instance,
while the calls within one node keep sharing that node's copy. State in the
ColumnarScalarFunction Javadoc that each operator of a task that evaluates the
function gets its own instance, which one thread calls, and that calls of the
function within that operator share it. Add a test that calls, inside and
outside a TRANSFORM in one stage, a function that fails when a thread other
than the first one calls its instance, and a function that keeps a reusable
buffer in its instance.
**Why this works:** Each iterator owns the instance it calls, and one thread
at a time pulls an iterator, so no two threads call one instance, even when an
operator between two calls pulls its child on a thread of its own.
**Scope:** Confine each function instance to one operator's partition
iterator, and state the rule in the ColumnarScalarFunction Javadoc.
**Compatibility:** The calls of a function within one node, and the batches
of one partition, keep sharing one instance, which the test of equal
nondeterministic calls relies on.
**Risks:** Each partition of each node deserializes its functions once more,
a small fixed cost per partition that also repeats any work an implementation
does when it is deserialized.
**Constraints:** The copy is made on the executor inside the partition
iterator, not on the driver, so that each task and each node gets its own. The
calls of one function within a node keep sharing that node's copy, which the
Javadoc must say.
**Success:** Two evaluation nodes of one stage call different instances of
the same function. A function that keeps a reusable buffer in its instance
returns correct values on both sides of a TRANSFORM in one stage. The
ColumnarScalarFunction Javadoc states which calls share an instance and that
one thread calls it.
**Verification:**
- **Regression:** Inside and outside a TRANSFORM in one stage, a function
that fails when a thread other than the first one calls its instance runs
without failing, and a function that keeps a reusable buffer in its instance
returns the same values as when each call runs alone.
- **Behavior:** Nested calls of one function in two nodes of a stage use
distinct instances, while equal calls of a nondeterministic function within one
node still return different values.
- **Inspection:** The ColumnarScalarFunction Javadoc describes the instance
per operator and its single calling thread.
##########
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:
**Nit (P3):** The planner decides this per operator, not per call.
`ExtractColumnarUDFs` evaluates all calls of an operator over one child in one
node, and once any of them has an argument that is not a column, the node reads
a row-based `Project(child.output ++ argAliases, child)` for all of them. Take
`spark.read.parquet(p).select(addOne(col("id")), addOne(col("i")))` with `i
INT`. The implicit cast of `i` also puts `add_one(id)` behind
`ColumnarToRowExec`, `ProjectExec` and `RowToColumnarExec`, although its
argument is a BIGINT column of the scan. A `where(col("s") === "x")` on the
scan leaves a row-based `FilterExec` below the node, with the same transitions.
A reader of this sentence would expect columnar evaluation in both cases.
Suggested fix: state the per-operator condition, including sibling calls and
filters below the call.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60551#discussion_r4591907209),
[2](https://github.com/apache/spark/pull/60551#pullrequestreview-5928139680).
See **Shared repair plan 2** in the review body.
##########
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:
**Nit (P3):** No test covers this skip, or the extraction of calls inside an
uncorrelated subquery, which happens when `OptimizeSubqueries` runs the
optimizer on it. No suite query calls a columnar function in a scalar, IN or
EXISTS subquery, correlated or not, so a regression in either path would leave
the suite green. Suggested fix: add tests such as `SELECT (SELECT
add_one(max(id)) FROM range(10))`, `SELECT * FROM range(3) r WHERE EXISTS
(SELECT 1 FROM t WHERE add_one(t.v) = r.id)`, and a correlated scalar subquery,
and compare their results with a Scala UDF's.
**Verification:**
- **Behavior:** Columnar calls in uncorrelated and correlated scalar
subqueries and in correlated EXISTS and IN subqueries return the same results
as the equivalent Scala UDF.
##########
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:
**Nit (P3):** This assertion checks only the error condition, not the
`funcName` parameter that the other new errors pin with `checkError`. Several
new checks have no test at all:
- the null-result branch of the result type check, and its comparison that
ignores field names and nullability (EvalColumnarUDFsExec.scala:141-149);
- the builder's `WRONG_NUM_ARGS` check
(ColumnarUserDefinedFunction.scala:84-87);
- the FILE return-type check of `registerColumnar`
(UDFRegistration.scala:62), which `FileTypeRestrictionsSuite` tests for every
other registration API.
Deleting any of those checks would leave the suite green. Suggested fix: use
`checkError` here, and add tests for a null result, a struct result whose
fields are named differently, wrong argument counts, and `registerColumnar`
with a qualified FILE return type.
**Verification:**
- **Behavior:** A function that returns null fails with
COLUMNAR_UDF_RESULT_TYPE_MISMATCH and actualType NULL, and one that returns a
struct vector whose fields are named differently but typed the same is accepted.
- **Behavior:** Calls with the wrong number of arguments fail with
WRONG_NUM_ARGS, registerColumnar rejects a qualified FILE return type, and the
lambda error names the call.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ColumnarUDF.scala:
##########
@@ -0,0 +1,73 @@
+/*
+ * 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 {
+
+ override lazy val deterministic: Boolean = udfDeterministic &&
children.forall(_.deterministic)
Review Comment:
**Non-blocking (P2):** `ColumnarUDF` does not override `expensive`, so
filter push-down treats a call over plain columns as cheap. Reading the
optimizer, `spark.range(100).select(col("id"),
addOne(col("id")).as("r")).filter(col("r") > 5)` becomes `Project([id,
add_one(id) AS r], Filter(add_one(id) > 5, Range))`. `ExtractColumnarUDFs`
shares a result only within one operator, so the Filter and the Project each
get an `EvalColumnarUDFs`: the function runs on all 100 rows and again on the
95 that pass, each time with its own `RowToColumnarExec` and
`ColumnarToRowExec`. `ScalaUDF` and `PythonUDF` return `expensive = true`, so
that `avoidDoubleFilterEval` keeps such a filter above the projection or splits
the projection around it. `PhysicalOperation`'s guard against collecting a
filter that reads a projected UDF result also names only `PythonUDF`. Suggested
fix: override `expensive` to return `true` here, and make that guard recognize
a columnar call.
**Verification:**
- **Regression:** A filter on the alias of a projected columnar call
evaluates the function once per input row, as a row-counting function shows,
with a single evaluation node in the plan.
- **Compatibility:** A filter that reads only plain columns next to a
projected columnar call is still pushed below the projection and into the scan.
##########
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())
Review Comment:
**Non-blocking (P2):** `closeResults` closes whatever `eval` returned,
without checking whether it is one of the argument columns, which are the
child's own vectors (line 137), or a field vector of one. Returning
`args.column(0)` when the column has no nulls, a natural fast path, is allowed
by the `ColumnarScalarFunction` contract, which forbids closing the arguments
but not returning them. Reading the code, at the second batch this close nulls
the arrays of the child's `OnHeapColumnVector`, which `RowToColumnarExec` and
`VectorizedParquetRecordReader` reset and refill, so the task fails with a
NullPointerException. With `spark.sql.columnVector.offheap.enabled=true`,
`OffHeapColumnVector` frees its memory and the next write goes near address 0,
which crashes the executor JVM along with the other tasks running there.
**Recommended change:** In closeResults, skip a result that is one of the
input batch's columns, or a field vector of a struct column reached through
getChild, since the child owns it, and close every other result as now. State
in the ColumnarScalarFunction Javadoc that a function may return one of its
argument columns, or a field of one, unchanged, which Spark then leaves to its
producer, and that any other vector it returns must not be shared with the
arguments or kept by the function. Add multi-batch tests with a function that
returns its argument when it has no nulls, over a row-based child and over a
Parquet scan, with on-heap and off-heap column vectors.
**Why this works:** Ownership follows the producer: vectors that come from
the child stay the child's, and only vectors the function created become the
node's to close, so a pass-through result is read in the output batch and left
for the child to reuse.
**Scope:** Leave argument vectors that a function returns to the child, and
state the rule in the eval contract.
**Risks:** A function that returns a vector built over an argument's memory
without being that vector or one of its fields is still closed and can still
release the child's memory; only the Javadoc rule guards that case.
**Constraints:** The comparison is by reference, against the columns of the
batch the result was computed from, before the next batch is requested.
**Success:** A function that returns its argument column unchanged gives
correct results over many batches from RowToColumnarExec and from the
vectorized Parquet reader, with on-heap and off-heap vectors. The node still
closes each result vector that the function creates once per batch. The
ColumnarScalarFunction Javadoc states which returned vectors Spark closes.
**Verification:**
- **Regression:** A function that returns its argument when it has no nulls,
over a row-based child and over a Parquet scan that each span several batches
per partition, returns the input values with on-heap and with off-heap column
vectors.
- **Behavior:** A function that returns new vectors has each of them closed
by the node once per batch, as a close-counting vector whose closeIfFreeable is
a no-op shows, since ColumnarToRowExec also closes the freeable vectors of each
batch it consumes.
- **Inspection:** The ColumnarScalarFunction Javadoc says that a returned
argument column is not closed by Spark and that other returned vectors must not
be shared with the arguments.
##########
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:
**Nit (P3):** No test reaches this case. `a call in a filter, and a filter
below a call` filters `id < 3` above a Project, which the main optimizer pushes
below the Project before `ExtractColumnarUDFs` runs, and it asserts only the
answers, so removing the case leaves the suite green. A filter that combines a
call with a plain conjunct over a scan would exercise it, such as
`spark.read.parquet(p).filter(addOne(col("id")) > 5 && col("id") < 50)`. After
extraction, `id < 50` is pushed below the node into the scan's data filters,
and the function sees fewer rows. Suggested fix: add that test, and assert the
plan or the function's row count.
**Verification:**
- **Regression:** A filter that combines a columnar call with a conjunct
over a plain column pushes that conjunct below the evaluation node and into the
scan, and the function's row count shows only the passing rows.
##########
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:
**Nit (P3):** Two behaviors that users run into are missing from this list.
A call that reads both sides of the condition of a join that is not an inner
join fails with `UNSUPPORTED_FEATURE.COLUMNAR_UDF_IN_ON_CLAUSE`, including the
semi and anti joins that correlated EXISTS and IN subqueries become. And a
conditional expression does not guard a call. The call is taken out of every
branch of a CASE, IF, COALESCE, AND or OR, and its computed arguments are
evaluated for every row below the node. So, reading the code, with ANSI mode on
`CASE WHEN s RLIKE '^[0-9]+$' THEN add_one(CAST(s AS BIGINT)) END` would fail
with `CAST_INVALID_INPUT` on a non-numeric `s`, where a Scala UDF returns NULL.
The `ColumnarScalarFunction` Javadoc mentions untaken branches, but only for
the function itself, and PySpark documents the same limitation for Python UDFs.
Suggested fix: add both to this list.
See **Shared repair plan 2** in the review body.
##########
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:
**Nit (P3):** This guard walks the lambda bodies of every resolved
higher-order function. Every query that uses `transform`, `filter`, `aggregate`
and the like therefore pays one more traversal during analysis, even when it
never calls a columnar function, and with nested higher-order functions the
inner lambdas are walked again at each level. The PR's own `COLUMNAR_UDF` tree
pattern answers the question from cached bits. Prefixing the condition with
`hof.containsPattern(COLUMNAR_UDF)` keeps the same errors and removes the extra
work for every other query.
**Verification:**
- **Behavior:** A columnar call inside a higher-order function's lambda, at
the top level and inside a nested lambda, still fails analysis with the lambda
error naming the call.
- **Inspection:** The guard consults the COLUMNAR_UDF pattern bits before it
traverses the lambda bodies.
##########
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:
**Nit (P3):** Each call of this method rebuilds the argument batch and
replaces and closes the previous results, and the node relies on a task
completion listener when a limit stops it. No suite query reaches a second
batch in any partition, though. The inputs hold at most 500 rows per partition,
against batches of 10000 rows from `RowToColumnarExec` and 4096 from the
Parquet reader. `a call below a limit` stops inside its first batch and checks
only the row count. None of these regressions would fail a test: reusing the
first batch's arguments, dropping a close, closing twice, or draining the child
under a limit. The same goes for the failure of a function that returns its
argument column, which needs a second batch. Suggested fix: lower
`spark.sql.inMemoryColumnarStorage.batchSize` and
`spark.sql.parquet.columnarReaderBatchSize` below the partition size, count
closes with a test vector whose `closeIfFreeable` is a no-op
(`ColumnarToRowExec` closes freeable vectors itself), and a
ssert the batch count under a limit.
**Verification:**
- **Behavior:** Calls over a row-based child and over a Parquet scan with
several batches per partition return correct values, and the node closes each
result vector once, as a close-counting vector whose closeIfFreeable is a no-op
shows.
- **Regression:** Under a limit, the node's batch count, or the function's
call count, stays within one batch per partition beyond what the limit needs.
--
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]