dongjoon-hyun commented on code in PR #60551:
URL: https://github.com/apache/spark/pull/60551#discussion_r4634339899
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/dynamicpruning/PartitionPruning.scala:
##########
@@ -141,13 +141,14 @@ object PartitionPruning extends Rule[LogicalPlan] with
PredicateHelper with Join
/**
* Returns whether the filtering plan or keys have a UDF that only the
"Extract UDFs" batch,
- * which runs after this rule, plans for evaluation: a scalar Python UDF, a
Python UDTF or an
- * external UDF. That batch does not rewrite the plan of a
[[DynamicPruningSubquery]], so a
- * standalone DPP subquery, which evaluates the keys over the plan, would
fail on such a UDF.
+ * which runs after this rule, plans for evaluation: a scalar Python UDF, a
Python UDTF, an
+ * external UDF or a columnar UDF. That batch does not rewrite the plan of a
+ * [[DynamicPruningSubquery]], so a standalone DPP subquery, which evaluates
the keys over the
+ * plan, would fail on such a UDF.
*/
private def needsUDFExtraction(plan: LogicalPlan, keys: Seq[Expression]):
Boolean = {
(keys ++ plan.flatMap(_.expressions)).exists(_.exists {
- case _: PythonUDTF | _: ExternalUserDefinedFunction => true
+ case _: PythonUDTF | _: ExternalUserDefinedFunction | _: ColumnarUDF =>
true
Review Comment:
**[45] This hunk conflicts with master after SPARK-62052, so CI did not
build or test 1251f5aa426.**
SPARK-62052 (58f55ad0631) landed on master after this branch was last merged
with it. It changes this helper to `needsUDFExtraction(exprs:
Seq[Expression])`, and `getFilterableTableScan` now also calls it on the
pruning key, so that a key with a UDF that needs extraction gets no DPP filter.
The fork CI of 1251f5aa426 ([run
44579622414](https://github.com/viirya/spark-1/actions/runs/44579622414))
stopped at "Check changes" with `CONFLICT (content): Merge conflict in
.../PartitionPruning.scala`, and every build and test job was skipped. So the
changes for [37]-[44] have not run in CI yet.
When resolving it, could `ColumnarUDF` be added to the pattern of master's
new `needsUDFExtraction`, and to its Scaladoc? Taking master's side as it is
would drop columnar UDFs from both checks:
- A filtering side with a call would get a standalone DPP subquery again,
which fails because the call is not extracted there. This is what 9389e35888c
fixed, and what the test "no standalone DPP subquery for a filtering side with
a columnar UDF" covers.
- A pruning key with a call, as in `ON dpp_add_one(f.store_id) =
s.store_id`, would get a DPP filter that prunes no partition. The "Extract
Python UDFs" batch puts an `EvalColumnarUDFs` between that filter and the scan,
and the call is evaluated twice: once for the filter and once for the join key.
With `ColumnarUDF` in the shared pattern, both cases are covered. A test for
the pruning key could go next to "SPARK-62052: no DPP filter on a pruning key
with a Python UDF" in `DynamicPartitionPruningSuiteBase`.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/udf/EvalColumnarUDFsExec.scala:
##########
@@ -0,0 +1,237 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.columnar.udf
+
+import scala.util.control.NonFatal
+
+import org.apache.spark.{SparkException, 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.CharVarcharUtils
+import org.apache.spark.sql.columnar.ColumnarScalarFunction
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.{SparkPlan, SparkStrategy, UnaryExecNode}
+import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics}
+import org.apache.spark.sql.execution.vectorized.WritableColumnVector
+import org.apache.spark.sql.types.{DataType, StructType, UserDefinedType}
+import org.apache.spark.sql.vectorized.{ColumnarBatch, ColumnVector}
+import org.apache.spark.util.Utils
+
+/** Plans the evaluation of columnar user-defined functions. */
+object ColumnarUDFEvals extends SparkStrategy {
+ override def apply(plan: LogicalPlan): Seq[SparkPlan] = plan match {
+ case EvalColumnarUDFs(udfs, resultAttrs, child) =>
+ EvalColumnarUDFsExec(udfs, resultAttrs, planLater(child)) :: Nil
+ case _ => Nil
+ }
+}
+
+/**
+ * Evaluates calls of columnar user-defined functions, one batch at a time.
The input and the
+ * output are columnar: an output batch is the columns of the input batch, as
they are, followed
+ * by one column per call. The arguments of the calls are columns of the child.
+ *
+ * This node runs the implementation of each function that Spark can run, its
+ * [[ColumnarScalarFunction]]. An engine that replaces Spark's operators can
replace this node
+ * with one that runs another implementation, from
`ColumnarUDF.engineImplementations`. A
+ * function that Spark cannot run fails only when this node is executed, so
that such an engine
+ * has replaced the node by then.
+ */
+case class EvalColumnarUDFsExec(
+ udfs: Seq[ColumnarUDF],
+ resultAttrs: Seq[Attribute],
+ child: SparkPlan) extends UnaryExecNode {
+
+ override def output: Seq[Attribute] = child.output ++ resultAttrs
+
+ override def producedAttributes: AttributeSet = AttributeSet(resultAttrs)
+
+ override def outputPartitioning: Partitioning = child.outputPartitioning
+
+ override def outputOrdering: Seq[SortOrder] = child.outputOrdering
+
+ override def supportsColumnar: Boolean = true
+
+ override lazy val metrics: Map[String, SQLMetric] = Map(
+ "numOutputRows" -> SQLMetrics.createMetric(sparkContext, "number of output
rows"),
+ "numOutputBatches" -> SQLMetrics.createMetric(sparkContext, "number of
output batches"),
+ "evalTime" -> SQLMetrics.createNanoTimingMetric(sparkContext, "time in
functions"))
+
+ override protected def doExecute(): RDD[InternalRow] = {
+ throw SparkException.internalError(s"$nodeName only supports columnar
execution.")
+ }
+
+ override protected def doExecuteColumnar(): RDD[ColumnarBatch] = {
+ val driverFunctions: Array[ColumnarScalarFunction] = udfs.map { udf =>
+ udf.function.getOrElse {
+ throw QueryExecutionErrors.columnarUDFNotExecutableError(
+ udf.name, udf.engineImplementations.map(_.kind))
+ }
+ }.toArray
+ // The closures of the nodes of a stage are serialized together, so the
nodes would share one
+ // instance of a function that several of them call, and an operator
between them can read
+ // its child from another thread. The functions are serialized apart here,
so that each
+ // partition of this node reads its own instances, which only this node
calls.
+ val serializedFunctions: Array[Byte] = Utils.serialize(driverFunctions)
+ // The ordinals, in the input batch, of the arguments of each call.
+ val argOrdinals: Array[Array[Int]] = udfs.map { udf =>
+ udf.children.map { arg =>
+ BindReferences.bindReference(arg, child.output) match {
+ case b: BoundReference => b.ordinal
+ case other => throw SparkException.internalError(
+ s"The argument $other of ${udf.name} is not a column of the
child.")
+ }
+ }.toArray
+ }.toArray
+ val names: Array[String] = udfs.map(_.name).toArray
+ val inputTypeStrings: Array[String] =
+ udfs.map(_.children.map(_.dataType.catalogString).mkString(", ")).toArray
+ val resultTypes: Array[DataType] = udfs.map(_.dataType).toArray
+ // A column vector has the SQL type of a user-defined type, so the type of
a result is
+ // compared with the declared type after the same replacement. CHAR and
VARCHAR, which a
+ // declared type has when they are first-class types, are compared as
STRING, so that the
+ // vector of such a result can be of either type.
+ val resultVectorTypes: Array[DataType] =
resultTypes.map(EvalColumnarUDFsExec.vectorType)
+ val numOutputRows = longMetric("numOutputRows")
+ val numOutputBatches = longMetric("numOutputBatches")
+ val evalTime = longMetric("evalTime")
+ val numInputColumns = child.output.length
+ val numFunctions = udfs.length
+
+ child.executeColumnar().mapPartitionsInternal { batches =>
+ new Iterator[ColumnarBatch] {
+ private val functions =
Utils.deserialize[Array[ColumnarScalarFunction]](
+ serializedFunctions, Utils.getContextOrSparkClassLoader)
+
+ // The results of the current batch, which this node owns.
+ private var results: Array[ColumnVector] = Array.empty
+
+ private def closeResults(): Unit = {
+ results.foreach(r => if (r != null) r.close())
+ results = Array.empty
+ }
+
+ Option(TaskContext.get()).foreach(_.addTaskCompletionListener[Unit](_
=> closeResults()))
+
+ // Whether `vector` is `column` or a vector inside it. A writable
vector, which the
+ // vectorized readers and `RowToColumnarExec` produce, gives its
children for every
+ // type that has them: the fields of a struct, the elements of an
array, the keys and
+ // values of a map. Other vectors are only known to give the fields of
a struct.
+ private def isPartOf(column: ColumnVector, vector: ColumnVector):
Boolean = {
+ (column eq vector) || (column match {
+ case w: WritableColumnVector =>
+ (0 until w.getNumChildren).exists(i => isPartOf(w.getChild(i),
vector))
+ case _ => column.dataType() match {
+ case s: StructType =>
+ s.fields.indices.exists(i => isPartOf(column.getChild(i),
vector))
+ case _ => false
+ }
+ })
+ }
+
+ private def isInputColumn(batch: ColumnarBatch, vector: ColumnVector):
Boolean = {
+ var i = 0
+ while (i < numInputColumns) {
+ if (isPartOf(batch.column(i), vector)) return true
+ i += 1
+ }
+ false
+ }
+
+ override def hasNext: Boolean = {
+ val more = batches.hasNext
+ if (!more) closeResults()
+ more
+ }
+
+ override def next(): ColumnarBatch = {
+ closeResults()
+ val batch = batches.next()
+ val numRows = batch.numRows()
+ val columns = new Array[ColumnVector](numInputColumns + numFunctions)
+ var i = 0
+ while (i < numInputColumns) {
+ columns(i) = batch.column(i)
+ i += 1
+ }
+ val start = System.nanoTime()
+ val newResults = new Array[ColumnVector](numFunctions)
+ results = newResults
+ i = 0
+ while (i < numFunctions) {
+ val args = new ColumnarBatch(argOrdinals(i).map(batch.column),
numRows)
+ val result = try {
+ functions(i).eval(args)
+ } catch {
+ case NonFatal(e) =>
+ throw
QueryExecutionErrors.failedExecuteUserDefinedFunctionError(
+ names(i), inputTypeStrings(i), resultTypes(i).catalogString,
e)
+ }
+ // This node closes the results, and the child still owns its
columns: it can use
+ // them again for its next batch. So a result that is a column of
the child, or a
+ // vector inside one, is not kept as a result, and is rejected.
+ if (result != null && isInputColumn(batch, result)) {
+ throw
QueryExecutionErrors.columnarUDFResultIsArgumentError(names(i))
+ }
+ // Set before the checks, so that a vector that fails them is
closed as well.
+ newResults(i) = result
+ if (result == null || !EvalColumnarUDFsExec.hasType(result,
resultVectorTypes(i))) {
+ throw QueryExecutionErrors.columnarUDFResultTypeMismatchError(
+ names(i), Option(result).map(_.dataType()), resultTypes(i))
+ }
+ // A vector that is too short would be read past its end by the
operators above.
+ // Only a writable vector tells how many values it can hold.
+ result match {
+ case w: WritableColumnVector if w.getCapacity < numRows =>
Review Comment:
**[46] The check for a vector that is too short skips an
`ArrowColumnVector`.**
Thank you for adding this check for [39]. The reply there says that other
vectors, e.g. an `ArrowColumnVector`, do not tell how many values they hold.
But `ArrowColumnVector` is a `@DeveloperApi` with a public `getValueVector()`
(`ArrowColumnVector.java` L51). The Arrow `ValueVector` that it returns has
`getValueCapacity()`, the counterpart of the `capacity` checked here, and
`getValueCount()`. A JVM implementation that hands its batches to native code
through Arrow is likely to return such a vector.
For example, a function that returns `new ArrowColumnVector(v)` for a
`BigIntVector` `v` allocated with `allocateNew(1)`, for a batch of 4096 rows,
falls into `case _` here. The `ColumnarToRowExec` above then reads past the
Arrow buffers. With Arrow's default bounds checking, it fails with an
`IndexOutOfBoundsException` that names neither the function nor
`FAILED_EXECUTE_UDF`. With `arrow.enable_unsafe_memory_access=true`, it reads
other memory instead. Could this match also have a case like the one below,
with a test whose function returns an Arrow vector?
```scala
case a: ArrowColumnVector if a.getValueVector.getValueCapacity < numRows =>
throw QueryExecutionErrors.columnarUDFResultTooShortError(
names(i), a.getValueVector.getValueCapacity, numRows)
```
--
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]