viirya commented on code in PR #59582:
URL: https://github.com/apache/spark/pull/59582#discussion_r4507288770
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowColumnarPythonUDFSuite.scala:
##########
@@ -167,13 +360,14 @@ class ArrowColumnarPythonUDFSuite extends
SharedSparkSession {
// path. Both release each batch once it has been written to Python.
for {
codegen <- Seq(true, false)
- (input, suffix, arrowIdColumn) <- Seq(
- ("name", "", true), ("name", "", false), ("concat(name, '_')", "_",
true))
+ (input, suffix, arrowIdColumn, retainable) <- Seq(
+ ("name", "", true, true), ("name", "", false, true), ("name", "",
true, false),
Review Comment:
Done in 4f85ae623d5: the `retainable` case is gone, and the comment now
covers each remaining case.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowBackedDataSourceV2.scala:
##########
@@ -250,6 +277,58 @@ private class ReusingArrowPartitionReader(start: Int, end:
Int, batchSize: Int)
}
}
+/** Returns the batches of `first`, then those of `second`. */
+private class SwitchingArrowPartitionReader(
+ first: PartitionReader[ColumnarBatch],
+ second: PartitionReader[ColumnarBatch])
+ extends PartitionReader[ColumnarBatch] {
+ private var current = first
+
+ override def next(): Boolean = {
+ if (current.next()) return true
+ if (current eq second) return false
+ current = second
+ second.next()
+ }
+
+ override def get(): ColumnarBatch = current.get()
+
+ override def close(): Unit = {
+ first.close()
+ second.close()
+ }
+}
+
+/**
+ * Reads the batches of `fresh` and `reused` in step, which cover the same
rows, and returns the
+ * `id` column of the first with the other columns of the second: a batch
whose first column is
+ * retainable while the others are not.
+ */
+private class MixedArrowPartitionReader(
+ fresh: PartitionReader[ColumnarBatch],
+ reused: PartitionReader[ColumnarBatch])
+ extends PartitionReader[ColumnarBatch] {
+
+ override def next(): Boolean = {
+ val hasNext = fresh.next()
+ assert(reused.next() == hasNext)
Review Comment:
`MixedArrowPartitionReader` is removed in 4f85ae623d5.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowColumnarPythonUDFSuite.scala:
##########
@@ -346,3 +513,9 @@ class ArrowColumnarPythonUDFSuite extends
SharedSparkSession {
}
}
}
+
+/** Runs the tests of [[ArrowColumnarPythonUDFSuite]] with pipelined Python
UDF execution. */
+class ArrowColumnarPythonUDFPipelinedSuite extends ArrowColumnarPythonUDFSuite
{
Review Comment:
The path helpers that re-executed the query are removed in 4f85ae623d5. I
kept `ArrowColumnarPythonUDFPipelinedSuite`, which comes from SPARK-60306,
since the batches are written on another thread in that mode.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/ColumnarArrowEvalPythonEvaluatorFactory.scala:
##########
@@ -155,25 +165,42 @@ private[python] class
ColumnarArrowEvalPythonEvaluatorFactory(
val inputColumnIndices = resolveColumnIndices(allInputs.toSeq)
- // Peek at first batch to check if Arrow-backed.
- val peekIter = new PeekableIterator(inputIter)
- val isArrow = peekIter.peek().exists { batch =>
- batch.numCols() > 0 &&
- batch.column(0).isInstanceOf[ArrowColumnVector]
+ val nonEmptyIter = inputIter.filter { batch =>
+ if (batch.numRows() == 0) batch.closeIfFreeable()
+ batch.numRows() > 0
}
- if (inputColumnIndices.isDefined && isArrow) {
+ // Peek at the first batch to check whether its columns are Arrow vectors
+ // that may be held until the result of the batch comes back.
+ val peekIter = new PeekableIterator(nonEmptyIter)
+ val canHoldInput = peekIter.peek().exists(batch =>
canHold(passThruColumns(batch)))
Review Comment:
Fixed in 4f85ae623d5: `RowToColumnConverter` handles `NullType` and UDTs, a
non-positive `maxRecordsPerBatch` means no row limit with a bounded initial
capacity, and a rebuilt batch also stops at `maxBytesPerBatch`. The tests cover
`NullType` and UDT columns over the Arrow cache, and all these limits.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/ColumnarArrowEvalPythonEvaluatorFactory.scala:
##########
@@ -155,25 +165,42 @@ private[python] class
ColumnarArrowEvalPythonEvaluatorFactory(
val inputColumnIndices = resolveColumnIndices(allInputs.toSeq)
- // Peek at first batch to check if Arrow-backed.
- val peekIter = new PeekableIterator(inputIter)
- val isArrow = peekIter.peek().exists { batch =>
- batch.numCols() > 0 &&
- batch.column(0).isInstanceOf[ArrowColumnVector]
+ val nonEmptyIter = inputIter.filter { batch =>
+ if (batch.numRows() == 0) batch.closeIfFreeable()
+ batch.numRows() > 0
}
- if (inputColumnIndices.isDefined && isArrow) {
+ // Peek at the first batch to check whether its columns are Arrow vectors
+ // that may be held until the result of the batch comes back.
+ val peekIter = new PeekableIterator(nonEmptyIter)
+ val canHoldInput = peekIter.peek().exists(batch =>
canHold(passThruColumns(batch)))
+
+ if (inputColumnIndices.isDefined && canHoldInput) {
// Path 1: Arrow columnar -- full optimization.
evalArrowColumnar(peekIter, context, pyFuncs, argMetas,
udfInputSchema, outputTypes, inputColumnIndices.get)
} else {
- // Path 2 & 3: non-Arrow or complex expressions.
+ // Path 2 & 3: columns that cannot be held, or complex expressions.
evalWithRowQueue(peekIter, context, pyFuncs, argMetas,
allInputs.toSeq, udfInputSchema, outputTypes,
inputColumnIndices)
}
}
+ private def passThruColumns(batch: ColumnarBatch): Array[ColumnVector] =
+ childOutput.indices.map(i => batch.column(i)).toArray
+
+ /**
+ * Whether the pass-through columns of a batch may be held until its result
+ * comes back from Python: they are all [[ArrowColumnVector]]s whose
producer
+ * allows it with [[ColumnVector.isRetainable]].
+ */
+ private def canHold(columns: Array[ColumnVector]): Boolean =
+ columns.nonEmpty && columns.forall {
+ case v: ArrowColumnVector => v.isRetainable
+ case _ => false
Review Comment:
This no longer applies after 4f85ae623d5, which removes `isRetainable` and
the holding.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowColumnarPythonUDFSuite.scala:
##########
@@ -130,6 +151,178 @@ class ArrowColumnarPythonUDFSuite extends
SharedSparkSession {
}
}
+ test("SPARK-60325: Arrow-backed source that reuses its vectors: Arrow
columnar path not taken") {
+ assume(shouldTestPandasUDFs)
+ // The Arrow columnar path would keep the pass-through columns of a batch
until its result
+ // comes back from Python. The reader refills its vectors for the next
batch and closes them
+ // once it is closed, as soon as it is exhausted, so they are not
retainable, and the
+ // batches take the row queue path with columnar input, while the default
reads the scan as
+ // rows. With two batches, the reader is closed before their results come
back. With many,
+ // it refills its vectors with the next batches before then. The test UDF
casts its input to
+ // string: on a string column, the cast is removed, so the inputs are
column references.
+ Seq(true, false).foreach { columnarInput =>
+ withSQLConf(
+ SQLConf.ARROW_PYSPARK_EXECUTION_ENABLED.key -> "true",
+ SQLConf.ARROW_PYSPARK_UDF_COLUMNAR_INPUT_ENABLED.key ->
columnarInput.toString) {
+ val pandasUDF = TestScalarPandasUDF(
+ name = "arrow_reuse_udf", returnType = Some(StringType))
+ registerTestUDF(pandasUDF, spark)
+
+ Seq(200, 20000).foreach { numRows =>
+ val result = readArrowSource(numRows = numRows, reuseVectors = true,
batchSize = 100)
+ .selectExpr("id", "name", "value", "data", "arrow_reuse_udf(name)
as udf_name")
+ val arrowExec =
singleArrowEvalPythonExec(result.queryExecution.executedPlan)
+ if (columnarInput) {
+ assert(!takesArrowColumnarPath(arrowExec))
+ } else {
+ assert(!arrowExec.child.supportsColumnar)
+ }
+
+ val rows = result.collect()
+ assert(rows.map(_.getInt(0)).toSeq == (0 until numRows))
+ rows.foreach { row =>
+ val id = row.getInt(0)
+ assert(row.getString(1) == s"row_$id", s"name mismatch for id $id")
+ assert(row.getString(3) == s"data_$id", s"data mismatch for id
$id")
+ assert(row.getString(4) == s"row_$id", s"UDF result mismatch for
id $id")
+ }
+ }
+ }
+ }
+ }
+
+ test("SPARK-60325: Later batches that cannot all be held: the pass-through
columns are copied") {
+ assume(shouldTestPandasUDFs)
+ withSQLConf(SQLConf.ARROW_PYSPARK_EXECUTION_ENABLED.key -> "true") {
+ val pandasUDF = TestScalarPandasUDF(
+ name = "arrow_switch_udf", returnType = Some(StringType))
+ registerTestUDF(pandasUDF, spark)
+
+ // The first batches have fresh, retainable vectors, so the Arrow
columnar path is taken. It
+ // holds the pass-through columns of those as they are. The `id` column
of the later batches
+ // is fresh and retainable too, but the reader refills their other
columns for the next
+ // batch, so their pass-through columns are copied, and the batches are
released once they
+ // have been written to Python.
+ val numRows = 20000
+ val freshBatches = 2
+ val result = readArrowSource(
+ numRows = numRows, reuseVectors = true, freshBatches = freshBatches,
batchSize = 100)
+ .selectExpr("id", "name", "value", "data", "arrow_switch_udf(name) as
udf_name")
+ val arrowExec =
singleArrowEvalPythonExec(result.queryExecution.executedPlan)
+ assert(takesArrowColumnarPath(arrowExec))
+ val copied = outputColumnClasses(arrowExec, 0).map(_ ==
classOf[OnHeapColumnVector].getName)
+ val numBatches = numRows / 100
+ assert(copied == Seq.fill(freshBatches)(false) ++ Seq.fill(numBatches -
freshBatches)(true))
+
+ ArrowBackedDataSourceV2.resetBatchCounters()
+ val rows = result.collect()
+ assert(rows.map(_.getInt(0)).toSeq == (0 until numRows))
+ rows.foreach { row =>
+ val id = row.getInt(0)
+ assert(row.getString(1) == s"row_$id", s"name mismatch for id $id")
+ assert(row.getString(4) == s"row_$id", s"UDF result mismatch for id
$id")
+ }
+ // The consumer releases the held batches, and the copied ones are
released once written.
+ assert(ArrowBackedDataSourceV2.returnedBatches.get == numBatches)
+ assert(ArrowBackedDataSourceV2.releasedBatches.get == numBatches)
+ }
+ }
+
+ test("SPARK-60325: The Arrow columnar path does not slice the results of
Python") {
+ assume(shouldTestPandasUDFs)
+ // The Arrow columnar path pairs each result batch with one input batch,
so the runner turns
+ // off the slicing of the results that these configurations ask for.
+ Seq(
+ SQLConf.ARROW_EXECUTION_MAX_RECORDS_PER_OUTPUT_BATCH.key,
+ SQLConf.ARROW_EXECUTION_MAX_BYTES_PER_OUTPUT_BATCH.key).foreach { key =>
+ withSQLConf(SQLConf.ARROW_PYSPARK_EXECUTION_ENABLED.key -> "true", key
-> "3") {
+ val pandasUDF = TestScalarPandasUDF(
+ name = "arrow_slice_udf", returnType = Some(StringType))
+ registerTestUDF(pandasUDF, spark)
+
+ val numRows = 1000
+ val result = readArrowSource(numRows = numRows, batchSize = 100)
+ .selectExpr("id", "name", "value", "data", "arrow_slice_udf(name) as
udf_name")
+ assert(takesArrowColumnarPath(
+ singleArrowEvalPythonExec(result.queryExecution.executedPlan)))
+
+ 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)}"))
+ }
+ }
+ }
+
+ test("SPARK-60325: Input batches without rows are released and skipped") {
+ assume(shouldTestPandasUDFs)
+ withSQLConf(SQLConf.ARROW_PYSPARK_EXECUTION_ENABLED.key -> "true") {
+ val pandasUDF = TestScalarPandasUDF(
+ name = "arrow_empty_udf", returnType = Some(StringType))
+ registerTestUDF(pandasUDF, spark)
+
+ // The reader also returns three batches without rows, first, in the
middle and last. They
+ // are released and not written to Python, on the Arrow columnar path
and on the row queue
+ // path. The test UDF does not fail on empty input, so the output
batches are checked.
+ val numRows = 2000
+ val numBatches = 20
+ Seq(true, false).foreach { retainable =>
+ val result = readArrowSource(numRows = numRows, retainable =
retainable,
+ batchSize = numRows / numBatches, emptyBatches = true)
+ .selectExpr("id", "name", "value", "data", "arrow_empty_udf(name) as
udf_name")
+ val arrowExec =
singleArrowEvalPythonExec(result.queryExecution.executedPlan)
+ assert(takesArrowColumnarPath(arrowExec) == retainable)
+
+ val batchSizes = arrowExec.executeColumnar().mapPartitionsInternal {
batches =>
+ batches.map(_.numRows())
+ }.collect().toSeq
+ assert(batchSizes.nonEmpty && batchSizes.forall(_ > 0), s"Batch sizes:
$batchSizes")
Review Comment:
Done in 4f85ae623d5: the test now checks that `pythonDataSent` is the same
with and without the batches without rows, on both paths for the UDF inputs.
Removing the filter fails it.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowColumnarPythonUDFSuite.scala:
##########
@@ -205,8 +404,13 @@ class ArrowColumnarPythonUDFSuite extends
SharedSparkSession {
}
// A limit stops consuming the output batches early, and the generated
code of
- // ColumnarToRowExec closes the current one.
- assert(result.limit(10).selectExpr("count(*)").head().getLong(0) == 10)
+ // ColumnarToRowExec closes the current one. The Arrow columnar path
may still hold the
+ // batches that it has written to Python, which the source frees when
the task
+ // completes: closing its allocator fails the task if any of them is
left.
+ val limited = result.limit(10)
+
assert(collectNodes[ArrowEvalPythonExec](limited.queryExecution.executedPlan).nonEmpty)
Review Comment:
After 4f85ae623d5 no batches are held across the next one, so there is
nothing to leak on an early stop. I restored the check that `master` has.
--
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]