This is an automated email from the ASF dual-hosted git repository.
viirya pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/branch-4.x by this push:
new f8df7646522e [SPARK-61516][SQL] Return rows directly from
ArrowEvalPythonExec with columnar input to a row-based parent
f8df7646522e is described below
commit f8df7646522eaaad43fb605060596e31265570c0
Author: Liang-Chi Hsieh <[email protected]>
AuthorDate: Thu Nov 12 22:13:45 2026 -0800
[SPARK-61516][SQL] Return rows directly from ArrowEvalPythonExec with
columnar input to a row-based parent
### What changes were proposed in this pull request?
With `spark.sql.execution.arrow.pythonUDF.columnarInput.enabled`,
`ArrowEvalPythonExec` over a columnar child only outputs columnar batches, so
the planner inserts a `ColumnarToRowExec` above it for a row-based parent. With
pass-through columns, `ColumnarArrowEvalPythonEvaluatorFactory` joins the
pass-through rows with the Python results as `UnsafeRow`s, converts them back
to `OnHeapColumnVector` batches with `RowToColumnConverter`, and the
`ColumnarToRowExec` above turns them into ro [...]
This PR makes `ArrowEvalPythonExec` with columnar input and pass-through
columns support row-based output as well:
- `supportsRowBased` is `true` when the evaluation has pass-through
columns, so a row-based parent calls `doExecute` with no `ColumnarToRowExec` in
between. With both `supportsColumnar` and `supportsRowBased`, the transition
rule still keeps the child columnar. Without pass-through columns, the output
is the result batches of Python, with no round trip to remove, so the
`ColumnarToRowExec` above is kept, which whole-stage codegen fuses into the
stage of the parent.
- In that mode, `doExecute` reads `child.executeColumnar()` and uses a new
`rowOutput` view of `ColumnarArrowEvalPythonEvaluatorFactory`. It shares the
whole input path with the columnar output: UDF inputs of Arrow-backed batches
are written to Python directly, and each input batch is released with
`closeIfFreeable` once it has been written. The joined rows are returned as
they are. (Without pass-through columns, e.g. when `doExecute` is called
directly, the rows of the result batches [...]
- A columnar parent, i.e. a stacked evaluation, still gets columnar batches
through `doExecuteColumnar`, unchanged.
- Whether columnar input is enabled is now fixed when the node is planned,
as a curried constructor field (like `codegenStageId` of
`WholeStageCodegenExec`) set by `PythonEvals` and carried over by `copy`,
`makeCopy` and `clone` through `otherCopyArgs`. So every copy of the node,
including one that a rule such as `ReuseExchangeAndSubquery` makes after the
transitions are inserted, reads the child in the format the planner prepared it
for, even if the configuration changes between plan [...]
This is the second follow-up promised in #59582 (SPARK-60325). The first
was SPARK-61445 (#60327).
### Why are the changes needed?
To skip the row -> column -> row round trip of the joined rows when an
Arrow Python UDF with columnar input feeds a row-based operator, which is the
common case. In a local benchmark (2M rows from an Arrow-backed DSv2 source, 4
pass-through columns, one scalar pandas UDF, `noop` write, 4 interleaved
rounds), the median time dropped from 768-795 ms with the `ColumnarToRowExec`
above to 680-704 ms, about 11% end to end, including the Python time.
### Does this PR introduce _any_ user-facing change?
No behavior change in results. With
`spark.sql.execution.arrow.pythonUDF.columnarInput.enabled` (disabled by
default), EXPLAIN no longer shows a `ColumnarToRow` above an `ArrowEvalPython`
that passes columns through to a row-based parent. The documentation of the
configuration is updated: the pass-through columns are converted back to
columnar batches only for a columnar downstream operator.
### How was this patch tested?
In `ArrowColumnarPythonUDFSuite` (and
`ArrowColumnarPythonUDFPipelinedSuite`):
- New `A row-based parent gets the joined rows of an evaluation with
columnar input directly`: with and without pass-through columns, on a single
and on stacked UDFs (the inner evaluation has a columnar parent). With
pass-through columns, it checks that the plan has no `ColumnarToRowExec` and
that the output rows are `UnsafeRow`s; without, that a `ColumnarToRowExec`
reads the output. It checks the results, that each input batch is released
before the next one is read, and a filter and [...]
- New `SPARK-61516: An evaluation rebuilt after the transitions runs as
built after the configuration changes`: with adaptive execution disabled, the
same scalar subquery twice in the UDF arguments makes
`ReuseExchangeAndSubquery` rebuild the evaluation after the transitions; the
plan is executed after columnar input is disabled. With the decision made per
node instance instead, it fails with the `ClassCastException` above.
- `SPARK-60306: A plan built with columnar input runs as built after the
configuration changes` now checks that there is no `ColumnarToRowExec` above
the evaluation. With the decision read from the configuration at execution time
instead, it fails with the `ClassCastException` above.
- `SPARK-60306: Arrow Python UDF over many batches releases each input
batch` now checks that there is no `ColumnarToRowExec` above the evaluation,
and the tests without pass-through columns that there is one.
Ran `ArrowColumnarPythonUDFSuite`, `ArrowColumnarPythonUDFPipelinedSuite`,
`ArrowCachedPythonUDFSuite`, `InProcessPythonUDFSuite`, `PythonUDFSuite`,
`ExtractPythonUDFsSuite`, `ColumnarRulesSuite`, `ArrowOutputProcessorSuite`,
`PythonArrowOutputSuite` and `ArrowCachedBatchSerializerSuite`.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Isaac (Claude Opus 5.5)
This pull request and its description were written by Isaac.
Closes #60381 from viirya/SPARK-arrow-eval-row-output.
Authored-by: Liang-Chi Hsieh <[email protected]>
Signed-off-by: Liang-Chi Hsieh <[email protected]>
(cherry picked from commit dfca8e9b9728e9280d40a99c0ea2a464b1e550a8)
Signed-off-by: Liang-Chi Hsieh <[email protected]>
skip-checks: true
---
.../org/apache/spark/sql/internal/SQLConf.scala | 5 +-
.../spark/sql/execution/SparkStrategies.scala | 4 +-
.../sql/execution/python/ArrowEvalPythonExec.scala | 50 ++++--
.../ColumnarArrowEvalPythonEvaluatorFactory.scala | 179 +++++++++++++--------
.../python/ArrowColumnarPythonUDFSuite.scala | 155 +++++++++++++++++-
5 files changed, 306 insertions(+), 87 deletions(-)
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
index cbbe717bb4a8..a52d11478409 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
@@ -5754,8 +5754,9 @@ object SQLConf {
"from upstream operators that produce ColumnarBatch. If the inputs of
the UDFs " +
"are plain column references, those of Arrow-backed batches are
written to " +
"Python directly, bypassing the ColumnarToRow and ArrowWriter
conversion. The " +
- "columns that the UDFs pass through are still converted to rows and
back, " +
- "which can cost more than leaving this disabled.")
+ "columns that the UDFs pass through are still copied as rows, and
converted back " +
+ "to columnar batches for a columnar downstream operator, which can
cost more " +
+ "than leaving this disabled.")
.version("4.2.0")
.withBindingPolicy(ConfigBindingPolicy.SESSION)
.booleanConf
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala
index 7c4382cf1d35..ba139316ed1f 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala
@@ -939,8 +939,8 @@ abstract class SparkStrategies extends
QueryPlanner[SparkPlan] {
ProjectExec(e.output, exec) :: Nil
}
case ArrowEvalPython(udfs, requiredChildOutput, resultAttrs, child,
evalType) =>
- ArrowEvalPythonExec(
- udfs, requiredChildOutput, resultAttrs, planLater(child), evalType)
:: Nil
+ ArrowEvalPythonExec(udfs, requiredChildOutput, resultAttrs,
planLater(child), evalType)(
+ conf.arrowPySparkUDFColumnarInputEnabled) :: Nil
case BatchEvalPython(udfs, requiredChildOutput, resultAttrs, child) =>
BatchEvalPythonExec(udfs, requiredChildOutput, resultAttrs,
planLater(child)) :: Nil
case BatchEvalPythonUDTF(udtf, requiredChildOutput, resultAttrs, child)
=>
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ArrowEvalPythonExec.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ArrowEvalPythonExec.scala
index 9277d6342b88..20a86eab1049 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ArrowEvalPythonExec.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ArrowEvalPythonExec.scala
@@ -86,7 +86,8 @@ case class ArrowEvalPythonExec(
requiredChildOutput: Seq[Attribute],
resultAttrs: Seq[Attribute],
child: SparkPlan,
- evalType: Int) extends EvalPythonExec with PythonSQLMetrics {
+ evalType: Int)(
+ val columnarInputEnabled: Boolean) extends EvalPythonExec with
PythonSQLMetrics {
if (!supportedPythonEvalTypes.contains(evalType)) {
throw SparkException.internalError(s"Unexpected eval type $evalType")
}
@@ -119,16 +120,38 @@ case class ArrowEvalPythonExec(
// batch whose columns are ArrowColumnVectors are serialized to IPC directly,
// bypassing the ColumnarToRow -> ArrowWriter round-trip. Each input batch is
// released once it has been written to Python. Without pass-through columns,
- // the result batches from Python are returned as they are; otherwise the
- // pass-through columns are copied as rows and joined with the results, which
- // are converted back to columnar batches. This node then outputs only
- // columnar batches, so the planner inserts a ColumnarToRowExec above it for
- // a row-based parent.
+ // the result batches from Python are the output batches, which a row-based
+ // parent reads through a ColumnarToRowExec, fused into its whole-stage
codegen
+ // stage. Otherwise the pass-through columns are copied as rows and joined
with
+ // the results, and this node also supports row-based output: a row-based
parent
+ // gets the joined rows as they are, with no ColumnarToRowExec in between,
and a
+ // columnar parent, i.e. a stacked evaluation, gets them converted back to
+ // columnar batches.
// Otherwise it reads rows from its child, even from one that also supports
- // columnar, such as the scan of the Arrow cache. Either way, the choice is
- // fixed when the plan is built.
- override def supportsColumnar: Boolean =
- child.supportsColumnar && conf.arrowPySparkUDFColumnarInputEnabled
+ // columnar, such as the scan of the Arrow cache.
+ // Whether columnar input is enabled is fixed when the node is planned, and
+ // carried over to its copies, so that any copy, including one that a rule
makes
+ // after the transitions are inserted, reads its child in the format the
planner
+ // prepared it for, even if the configuration changes before the plan is
executed.
+ override def supportsColumnar: Boolean = columnarInputEnabled &&
child.supportsColumnar
+
+ override def supportsRowBased: Boolean = !supportsColumnar ||
requiredChildOutput.nonEmpty
+
+ override protected def doExecute(): RDD[InternalRow] = {
+ if (supportsColumnar) {
+ val inputRDD = child.executeColumnar()
+ val rowEvaluatorFactory = columnarEvaluatorFactory.rowOutput
+ if (conf.usePartitionEvaluator) {
+ inputRDD.mapPartitionsWithEvaluator(rowEvaluatorFactory)
+ } else {
+ inputRDD.mapPartitionsWithIndexInternal { (index, iter) =>
+ rowEvaluatorFactory.createEvaluator().eval(index, iter)
+ }
+ }
+ } else {
+ super.doExecute()
+ }
+ }
override protected def doExecuteColumnar(): RDD[ColumnarBatch] = {
val inputRDD = child.executeColumnar()
@@ -175,10 +198,13 @@ case class ArrowEvalPythonExec(
override def withRequiredChildOutput(
requiredChildOutput: Seq[Attribute]): ArrowEvalPythonExec =
- copy(requiredChildOutput = requiredChildOutput)
+ copy(requiredChildOutput = requiredChildOutput)(columnarInputEnabled)
override protected def withNewChildInternal(newChild: SparkPlan): SparkPlan =
- copy(child = newChild)
+ copy(child = newChild)(columnarInputEnabled)
+
+ override protected def otherCopyArgs: Seq[AnyRef] =
+ Seq(columnarInputEnabled.asInstanceOf[java.lang.Boolean])
private def supportedPythonEvalTypes: Array[Int] =
Array(
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ColumnarArrowEvalPythonEvaluatorFactory.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ColumnarArrowEvalPythonEvaluatorFactory.scala
index 390b66b04320..e2822b1ac268 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ColumnarArrowEvalPythonEvaluatorFactory.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ColumnarArrowEvalPythonEvaluatorFactory.scala
@@ -20,6 +20,7 @@ import java.io.File
import scala.collection.mutable.ArrayBuffer
import scala.jdk.CollectionConverters._
+import scala.util.{Left, Right}
import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory,
SparkEnv, TaskContext}
import org.apache.spark.api.python.ChainedPythonFunctions
@@ -34,10 +35,11 @@ import
org.apache.spark.sql.execution.vectorized.OnHeapColumnVector
import org.apache.spark.sql.types.{DataType, StructField, StructType,
UserDefinedType}
import org.apache.spark.sql.types.DataType.equalsIgnoreCompatibleCollation
import org.apache.spark.sql.vectorized.ColumnarBatch
-import org.apache.spark.util.Utils
+import org.apache.spark.util.{CompletionIterator, Utils}
/**
- * Evaluator factory for Arrow Python UDFs: ColumnarBatch in, ColumnarBatch
out.
+ * Evaluator factory for Arrow Python UDFs: ColumnarBatch in, ColumnarBatch
out, or rows out
+ * through [[rowOutput]] for a row-based parent.
*
* Two execution paths based on the UDF inputs:
*
@@ -63,6 +65,13 @@ import org.apache.spark.util.Utils
* [[ColumnarBatch]]. Input batches without rows are released and skipped, so
* that the UDFs are not called with empty input, as on the row path.
*
+ * With [[rowOutput]], the input is handled in the same way, but the joined
+ * rows are returned as they are, so that a row-based parent gets them without
+ * the round trip through columnar batches. Without pass-through columns, it
+ * returns the rows of the result batches, each of which is released with
+ * closeIfFreeable once its rows have been returned, as
+ * [[org.apache.spark.sql.execution.ColumnarToRowExec]] does.
+ *
* TODO: Add a physical plan rule that inserts a ProjectExec before
* ArrowEvalPythonExec to pre-evaluate complex UDF input expressions
* into simple column references. This would eliminate the row fallback
@@ -88,12 +97,91 @@ private[python] class
ColumnarArrowEvalPythonEvaluatorFactory(
private val output = passThroughOutput ++ resultOutput
private val outputSchema = output.toStructType
- override def createEvaluator()
- : PartitionEvaluator[ColumnarBatch, ColumnarBatch] =
+ override def createEvaluator(): PartitionEvaluator[ColumnarBatch,
ColumnarBatch] =
new ColumnarArrowEvalPythonPartitionEvaluator
+ /** A factory of the same evaluation, which returns the output as unsafe
rows. */
+ def rowOutput: PartitionEvaluatorFactory[ColumnarBatch, InternalRow] =
+ new RowOutputEvaluatorFactory
+
+ private class RowOutputEvaluatorFactory
+ extends PartitionEvaluatorFactory[ColumnarBatch, InternalRow] {
+ override def createEvaluator(): PartitionEvaluator[ColumnarBatch,
InternalRow] =
+ new RowOutputPartitionEvaluator
+ }
+
private class ColumnarArrowEvalPythonPartitionEvaluator
- extends PartitionEvaluator[ColumnarBatch, ColumnarBatch] {
+ extends PartitionEvaluator[ColumnarBatch, ColumnarBatch] {
+ override def eval(
+ partitionIndex: Int,
+ iters: Iterator[ColumnarBatch]*): Iterator[ColumnarBatch] = {
+ new ColumnarArrowEvalPython().evaluate(iters.head) match {
+ case Left(resultBatches) => resultBatches
+ case Right(joinedRows) => rowsToColumnarBatches(joinedRows,
TaskContext.get())
+ }
+ }
+ }
+
+ private class RowOutputPartitionEvaluator
+ extends PartitionEvaluator[ColumnarBatch, InternalRow] {
+ override def eval(
+ partitionIndex: Int,
+ iters: Iterator[ColumnarBatch]*): Iterator[InternalRow] = {
+ new ColumnarArrowEvalPython().evaluate(iters.head) match {
+ case Left(resultBatches) =>
+ val toUnsafe = UnsafeProjection.create(resultOutput, resultOutput)
+ rowsOf(resultBatches).map(toUnsafe)
+ case Right(joinedRows) => joinedRows
+ }
+ }
+ }
+
+ /**
+ * Returns the rows of the batches, releasing each batch with
closeIfFreeable once all its
+ * rows have been returned, before the next batch is requested, as
ColumnarToRowExec does.
+ */
+ private def rowsOf(batches: Iterator[ColumnarBatch]): Iterator[InternalRow] =
+ batches.flatMap { batch =>
+ CompletionIterator[InternalRow, Iterator[InternalRow]](
+ batch.rowIterator().asScala, batch.closeIfFreeable())
+ }
+
+ /**
+ * Converts rows back to ColumnarBatches, which stop at `batchSize` rows,
unless it is not
+ * positive, or once their rows reach `maxBytesPerBatch`. Each has at least
one row.
+ */
+ private def rowsToColumnarBatches(
+ rowIter: Iterator[UnsafeRow],
+ context: TaskContext): Iterator[ColumnarBatch] = {
+ val converters = new RowToColumnConverter(outputSchema)
+ // The vectors grow as rows are appended, so that a large or no limit is
not allocated.
+ val initialCapacity = if (batchSize > 0) math.min(batchSize, 4096) else
4096
+ val vectors = OnHeapColumnVector
+ .allocateColumns(initialCapacity, outputSchema).toSeq
+ val cb = new ColumnarBatch(vectors.toArray)
+ context.addTaskCompletionListener[Unit] { _ => cb.close() }
+
+ new Iterator[ColumnarBatch] {
+ override def hasNext: Boolean = rowIter.hasNext
+ override def next(): ColumnarBatch = {
+ cb.setNumRows(0)
+ vectors.foreach(_.reset())
+ var count = 0
+ var bytes = 0L
+ while (rowIter.hasNext && (count == 0 ||
+ ((batchSize <= 0 || count < batchSize) && bytes <
maxBytesPerBatch))) {
+ val row = rowIter.next()
+ converters.convert(row, vectors.toArray)
+ bytes += row.getSizeInBytes
+ count += 1
+ }
+ cb.setNumRows(count)
+ cb
+ }
+ }
+ }
+
+ private class ColumnarArrowEvalPython {
private def collectFunctions(
udf: PythonUDF
@@ -112,11 +200,14 @@ private[python] class
ColumnarArrowEvalPythonEvaluatorFactory(
}
}
- override def eval(
- partitionIndex: Int,
- iters: Iterator[ColumnarBatch]*
- ): Iterator[ColumnarBatch] = {
- val inputIter = iters.head
+ /**
+ * Evaluates the UDFs over the input batches. Without pass-through
columns, returns the
+ * result batches from Python, otherwise the joined rows as unsafe rows,
each valid until
+ * the next one is requested.
+ */
+ def evaluate(
+ inputIter: Iterator[ColumnarBatch]
+ ): Either[Iterator[ColumnarBatch], Iterator[UnsafeRow]] = {
val context = TaskContext.get()
val (pyFuncs, inputs) = udfs.map(collectFunctions).unzip
@@ -162,18 +253,18 @@ private[python] class
ColumnarArrowEvalPythonEvaluatorFactory(
// consumer respecting the contract of ColumnVector does not rely on
beyond that.
// The result batches are as large as the ones Python returns, unless
// maxRecordsPerOutputBatch or maxBytesPerOutputBatch slices them, and
are not cut by
- // maxRecordsPerBatch or maxBytesPerBatch as the rows converted back
below are. So a
- // parent that takes columnar input, e.g. a stacked evaluation or the
Arrow cache, gets
- // them at that size, as it gets the batches of any other columnar
child. A stacked
- // evaluation does not split its input batches yet either.
- evalPython(nonEmptyIter, context, pyFuncs, argMetas, allInputs.toSeq,
udfInputSchema,
- inputColumnIndices, onInputRow = None).map { batch =>
+ // maxRecordsPerBatch or maxBytesPerBatch as the joined rows are when
they are converted
+ // back for a columnar parent. So a parent that takes columnar input,
i.e. a stacked
+ // evaluation, gets them at that size, as it gets the batches of any
other columnar
+ // child. A stacked evaluation does not split its input batches yet
either.
+ Left(evalPython(nonEmptyIter, context, pyFuncs, argMetas,
allInputs.toSeq,
+ udfInputSchema, inputColumnIndices, onInputRow = None).map { batch =>
validateOutputTypes(batch, outputTypes)
batch
- }
+ })
} else {
- evalWithRowQueue(nonEmptyIter, context, pyFuncs, argMetas,
- allInputs.toSeq, udfInputSchema, outputTypes, inputColumnIndices)
+ Right(evalWithRowQueue(nonEmptyIter, context, pyFuncs, argMetas,
+ allInputs.toSeq, udfInputSchema, outputTypes, inputColumnIndices))
}
}
@@ -241,8 +332,8 @@ private[python] class
ColumnarArrowEvalPythonEvaluatorFactory(
}
/**
- * Uses HybridRowQueue for pass-through, joins rows, then
- * converts back to ColumnarBatch via RowToColumnConverter.
+ * Uses HybridRowQueue for pass-through and joins the pass-through columns
of each input
+ * row with its results.
*/
private def evalWithRowQueue(
inputIter: Iterator[ColumnarBatch],
@@ -253,7 +344,7 @@ private[python] class
ColumnarArrowEvalPythonEvaluatorFactory(
udfInputSchema: StructType,
outputTypes: Seq[DataType],
inputColumnIndices: Option[Array[Int]]
- ): Iterator[ColumnarBatch] = {
+ ): Iterator[UnsafeRow] = {
// In pipelined mode the queue's add() runs in the writer thread and
remove() runs in
// the task thread; use lock-free mode to skip per-row synchronization.
@@ -275,15 +366,12 @@ private[python] class
ColumnarArrowEvalPythonEvaluatorFactory(
val joined = new JoinedRow
val resultProj = UnsafeProjection.create(output, output)
- val rowIter = resultIter.flatMap { batch =>
+ rowsOf(resultIter.map { batch =>
validateOutputTypes(batch, outputTypes)
- batch.rowIterator.asScala
- }.map { outputRow =>
+ batch
+ }).map { outputRow =>
resultProj(joined(queue.remove(), outputRow))
}
-
- // Convert joined rows back to ColumnarBatch.
- rowsToColumnarBatches(rowIter, context)
}
private def validateOutputTypes(
@@ -296,41 +384,6 @@ private[python] class
ColumnarArrowEvalPythonEvaluatorFactory(
"pandas_udf()", outputTypes, actual)
}
}
-
- /**
- * Converts rows back to ColumnarBatches, which stop at `batchSize` rows,
unless it is not
- * positive, or once their rows reach `maxBytesPerBatch`. Each has at
least one row.
- */
- private def rowsToColumnarBatches(
- rowIter: Iterator[UnsafeRow],
- context: TaskContext): Iterator[ColumnarBatch] = {
- val converters = new RowToColumnConverter(outputSchema)
- // The vectors grow as rows are appended, so that a large or no limit is
not allocated.
- val initialCapacity = if (batchSize > 0) math.min(batchSize, 4096) else
4096
- val vectors = OnHeapColumnVector
- .allocateColumns(initialCapacity, outputSchema).toSeq
- val cb = new ColumnarBatch(vectors.toArray)
- context.addTaskCompletionListener[Unit] { _ => cb.close() }
-
- new Iterator[ColumnarBatch] {
- override def hasNext: Boolean = rowIter.hasNext
- override def next(): ColumnarBatch = {
- cb.setNumRows(0)
- vectors.foreach(_.reset())
- var count = 0
- var bytes = 0L
- while (rowIter.hasNext && (count == 0 ||
- ((batchSize <= 0 || count < batchSize) && bytes <
maxBytesPerBatch))) {
- val row = rowIter.next()
- converters.convert(row, vectors.toArray)
- bytes += row.getSizeInBytes
- count += 1
- }
- cb.setNumRows(count)
- cb
- }
- }
- }
}
}
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowColumnarPythonUDFSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowColumnarPythonUDFSuite.scala
index 05946b745e57..8a3aee83a07e 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowColumnarPythonUDFSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowColumnarPythonUDFSuite.scala
@@ -20,9 +20,10 @@ package org.apache.spark.sql.execution.python
import org.apache.spark.SparkConf
import org.apache.spark.api.python.{ChainedPythonFunctions, PythonEvalType}
import org.apache.spark.internal.config.Python.PYTHON_UDF_PIPELINED_EXECUTION
-import org.apache.spark.sql.{DataFrame, IntegratedUDFTestUtils}
-import org.apache.spark.sql.catalyst.expressions.AttributeReference
-import org.apache.spark.sql.execution.{ColumnarToRowExec, SparkPlan,
SQLExecution, WholeStageCodegenExec}
+import org.apache.spark.sql.{DataFrame, IntegratedUDFTestUtils, Row}
+import org.apache.spark.sql.catalyst.expressions.{AttributeReference,
UnsafeRow}
+import org.apache.spark.sql.execution.{ColumnarToRowExec, ReusedSubqueryExec,
SparkPlan, SQLExecution,
+ WholeStageCodegenExec}
import org.apache.spark.sql.execution.vectorized.ReusedArrowColumnVector
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSparkSession
@@ -81,6 +82,11 @@ class ArrowColumnarPythonUDFSuite extends SharedSparkSession
{
}
}
+ /** Whether a ColumnarToRowExec converts the output of an
ArrowEvalPythonExec. */
+ private def hasColumnarToRowAbove(plan: SparkPlan): Boolean =
+ collectNodes[ColumnarToRowExec](plan).exists(
+ _.find(_.isInstanceOf[ArrowEvalPythonExec]).isDefined)
+
private def collectNodes[T <: SparkPlan](
plan: SparkPlan)(implicit tag: reflect.ClassTag[T]): Seq[T] = {
plan.collect {
@@ -369,8 +375,7 @@ class ArrowColumnarPythonUDFSuite extends
SharedSparkSession {
assert(arrowExec.nonEmpty && arrowExec.head.supportsColumnar)
assert(arrowExec.head.udfs.forall(_.children.forall(_.isInstanceOf[AttributeReference]))
== suffix.isEmpty, s"Unexpected UDF inputs:\n$plan")
- assert(collectNodes[ColumnarToRowExec](plan).exists(
- _.find(_.isInstanceOf[ArrowEvalPythonExec]).isDefined), s"No
ColumnarToRowExec:\n$plan")
+ assert(!hasColumnarToRowAbove(plan), s"Unexpected
ColumnarToRowExec:\n$plan")
ArrowBackedDataSourceV2.resetBatchCounters()
val rows = result.collect()
assert(rows.map(_.getInt(0)).toSeq == (0 until numRows))
@@ -404,14 +409,18 @@ class ArrowColumnarPythonUDFSuite extends
SharedSparkSession {
name = "arrow_replan_udf", returnType = Some(StringType))
registerTestUDF(pandasUDF, spark)
- // The physical plan is built with columnar input enabled, over the
columnar-only scan, and
- // first executed after columnar input is disabled.
+ // The physical plan is built with columnar input over the columnar-only
scan, and first
+ // executed after columnar input is disabled. The row-based parent calls
`doExecute` of the
+ // evaluation, which must still read the batches of the scan.
val numRows = 100
val result = readArrowSource(numRows = numRows)
.selectExpr("id", "name", "value", "data", "arrow_replan_udf(name) as
udf_name")
val plan = result.queryExecution.executedPlan
-
assert(collectNodes[ArrowEvalPythonExec](plan).exists(_.child.supportsColumnar))
+ val arrowExec = singleArrowEvalPythonExec(plan)
+ assert(arrowExec.supportsColumnar && arrowExec.supportsRowBased)
+ assert(!hasColumnarToRowAbove(plan), s"Unexpected
ColumnarToRowExec:\n$plan")
withSQLConf(SQLConf.ARROW_PYSPARK_UDF_COLUMNAR_INPUT_ENABLED.key ->
"false") {
+
assert(singleArrowEvalPythonExec(result.queryExecution.executedPlan).supportsColumnar)
val rows = result.collect()
assert(rows.map(_.getInt(0)).toSeq == (0 until numRows))
assert(rows.forall(row => row.getString(4) == s"row_${row.getInt(0)}"))
@@ -419,6 +428,132 @@ class ArrowColumnarPythonUDFSuite extends
SharedSparkSession {
}
}
+ test("SPARK-61516: An evaluation rebuilt after the transitions runs as built
after the " +
+ "configuration changes") {
+ assume(shouldTestPandasUDFs)
+ val pandasUDF = TestScalarPandasUDF(name = "arrow_rebuilt_udf", returnType
= Some(StringType))
+ registerTestUDF(pandasUDF, spark)
+
+ withTempView("t_max") {
+ spark.range(1).selectExpr("cast(id as string) as
s").createOrReplaceTempView("t_max")
+ // Without adaptive execution, the reuse of subqueries runs after the
transitions are
+ // inserted, and rebuilds the evaluation, whose UDF arguments have the
same scalar subquery
+ // twice, to reuse it. The rebuilt evaluation is executed after columnar
input is disabled,
+ // and must still read the batches of the columnar-only scan.
+ withSQLConf(
+ SQLConf.ARROW_PYSPARK_EXECUTION_ENABLED.key -> "true",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val numRows = 100
+ val subquery = "(SELECT max(s) FROM t_max)"
+ val result = readArrowSource(numRows = numRows).selectExpr("id",
"name", "value", "data",
+ s"arrow_rebuilt_udf(concat(name, $subquery)) as a",
+ s"arrow_rebuilt_udf(concat(data, $subquery)) as b")
+ val plan = result.queryExecution.executedPlan
+ val arrowExec = singleArrowEvalPythonExec(plan)
+ assert(arrowExec.subqueries.exists(_.isInstanceOf[ReusedSubqueryExec]),
+ s"Expected a reused subquery in the evaluation:\n$plan")
+ // Checked through the plan only, so that the executed evaluation is
not asked anything
+ // before the configuration changes.
+ assert(!arrowExec.child.exists(_.isInstanceOf[ColumnarToRowExec]))
+ assert(!hasColumnarToRowAbove(plan), s"Unexpected
ColumnarToRowExec:\n$plan")
+ withSQLConf(SQLConf.ARROW_PYSPARK_UDF_COLUMNAR_INPUT_ENABLED.key ->
"false") {
+ val rows = result.collect()
+ assert(rows.map(_.getInt(0)).toSeq == (0 until numRows))
+ rows.foreach { row =>
+ val id = row.getInt(0)
+ assert(row.getString(4) == s"row_${id}0", s"UDF result mismatch
for id $id")
+ assert(row.getString(5).length == 101, s"UDF result mismatch for
id $id")
+ }
+ }
+ }
+ }
+ }
+
+ test("A row-based parent gets the joined rows of an evaluation with columnar
input directly") {
+ assume(shouldTestPythonUDFs && shouldTestPandasUDFs)
+ val pandasUDF = TestScalarPandasUDF(name = "arrow_rows_udf", returnType =
Some(StringType))
+ val innerUDF = TestPythonUDF(name = "arrow_rows_inner_udf", returnType =
Some(StringType),
+ pythonEvalType = PythonEvalType.SQL_ARROW_BATCHED_UDF)
+ registerTestUDF(pandasUDF, spark)
+ registerTestUDF(innerUDF, spark)
+
+ val numRows = 2000
+ val numBatches = 20
+ val expected = (0 until numRows).map(id => s"row_$id")
+ def query(passThrough: Boolean, udf: String): DataFrame = {
+ val columns = if (passThrough) Seq("id", s"$udf as u") else Seq(s"$udf
as u")
+ readArrowSource(numRows = numRows, batchSize = numRows / numBatches,
pruneColumns = true)
+ .selectExpr(columns: _*)
+ }
+ def checkRows(passThrough: Boolean, rows: Array[Row], expected:
Seq[String]): Unit = {
+ if (passThrough) {
+ assert(rows.map(_.getString(1)).toSeq == expected)
+ } else {
+ assert(rows.map(_.getString(0)).toSeq == expected)
+ }
+ }
+
+ // UDFs of different eval types are evaluated by two stacked evaluations,
the inner one with
+ // a columnar parent. Without pass-through columns, the topmost evaluation
outputs the result
+ // batches of Python, which a ColumnarToRowExec reads in the stage of the
parent.
+ for {
+ passThrough <- Seq(true, false)
+ (udf, numEvals) <- Seq(
+ ("arrow_rows_udf(name)", 1),
("arrow_rows_udf(arrow_rows_inner_udf(name))", 2))
+ } withSQLConf(SQLConf.ARROW_PYSPARK_EXECUTION_ENABLED.key -> "true") {
+ withClue(s"passThrough=$passThrough, udf=$udf: ") {
+ val result = query(passThrough, udf)
+ val plan = result.queryExecution.executedPlan
+ val execs = collectNodes[ArrowEvalPythonExec](plan)
+ assert(execs.length == numEvals, s"Unexpected evaluations:\n$plan")
+ assert(execs.forall(_.supportsColumnar))
+ assert(execs.forall(_.requiredChildOutput.nonEmpty == passThrough))
+ // The topmost evaluation, with the row-based parent.
+ val topExec = execs.head
+ assert(topExec.supportsRowBased == passThrough)
+ assert(hasColumnarToRowAbove(plan) == !passThrough, s"Unexpected
plan:\n$plan")
+ if (passThrough) {
+ assert(collectNodes[ColumnarToRowExec](plan).isEmpty, s"Unexpected
plan:\n$plan")
+ // The evaluation returns unsafe rows, which a parent may expect.
+ val unsafe = SQLExecution.withSQLConfPropagated(spark) {
+
topExec.execute().mapPartitionsInternal(_.map(_.isInstanceOf[UnsafeRow])).collect()
+ }
+ assert(unsafe.length == numRows && unsafe.forall(identity))
+ }
+
+ ArrowBackedDataSourceV2.resetBatchCounters()
+ val rows = result.collect()
+ if (passThrough) assert(rows.map(_.getInt(0)).toSeq == (0 until
numRows))
+ checkRows(passThrough, rows, expected)
+ // A batch is released before the next one is read.
+ assert(ArrowBackedDataSourceV2.returnedBatches.get == numBatches)
+ assert(ArrowBackedDataSourceV2.releasedBatches.get == numBatches)
+ assert(ArrowBackedDataSourceV2.maxUnreleasedBatches.get == 1)
+
+ // A filter and a limit above, which stop reading the row output
early. A limit alone
+ // would be pushed below the evaluation. The filter is pushed below
the projection, so
+ // the evaluation under it passes the arguments of the UDF through to
the projection,
+ // which evaluates it again over the rows that the limit lets through.
+ val limited = result.where("u like 'row_1%'").limit(10)
+ val limitedPlan = limited.queryExecution.executedPlan
+ assert(collectNodes[ArrowEvalPythonExec](limitedPlan).exists { e =>
+ e.supportsColumnar && e.supportsRowBased &&
e.requiredChildOutput.nonEmpty
+ }, s"Unexpected plan:\n$limitedPlan")
+ assert(!hasColumnarToRowAbove(limitedPlan), s"Unexpected
plan:\n$limitedPlan")
+ checkRows(passThrough, limited.collect(),
expected.filter(_.startsWith("row_1")).take(10))
+ }
+ }
+
+ // The evaluators are also run through `mapPartitionsWithEvaluator`.
+ withSQLConf(
+ SQLConf.ARROW_PYSPARK_EXECUTION_ENABLED.key -> "true",
+ SQLConf.USE_PARTITION_EVALUATOR.key -> "true") {
+ Seq(true, false).foreach { passThrough =>
+ checkRows(passThrough, query(passThrough,
"arrow_rows_udf(name)").collect(), expected)
+ }
+ }
+ }
+
test("Without pass-through columns, the results of Python are the output
batches") {
assume(shouldTestPandasUDFs)
val pandasUDF = TestScalarPandasUDF(name = "arrow_direct_udf", returnType
= Some(StringType))
@@ -446,6 +581,9 @@ class ArrowColumnarPythonUDFSuite extends
SharedSparkSession {
assert(arrowExec.requiredChildOutput.isEmpty)
assert(arrowExec.output == arrowExec.resultAttrs)
assert(arrowExec.child.output.map(_.name) == Seq("name"))
+ // A row-based parent reads the result batches through a
ColumnarToRowExec.
+ assert(arrowExec.supportsColumnar && !arrowExec.supportsRowBased)
+ assert(hasColumnarToRowAbove(result.queryExecution.executedPlan))
// Each input batch has one result batch from Python, over the vectors
of its reader.
val batches = SQLExecution.withSQLConfPropagated(spark) {
@@ -522,6 +660,7 @@ class ArrowColumnarPythonUDFSuite extends
SharedSparkSession {
val outerExec =
execs.find(_.child.isInstanceOf[ArrowEvalPythonExec]).getOrElse(
fail(s"Expected stacked ArrowEvalPythonExecs in plan:\n$plan"))
assert(outerExec.udfs.head.children.forall(_.isInstanceOf[AttributeReference]))
+ assert(hasColumnarToRowAbove(plan), s"Expected a ColumnarToRowExec
above:\n$plan")
assert(result.collect().map(_.getString(0)).toSeq ==
(0 until numRows).map(id => s"row_$id"))
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]