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 6ed31e6b1a51 [SPARK-60325][SQL] Remove the holding of input batches 
from columnar Python UDFs
6ed31e6b1a51 is described below

commit 6ed31e6b1a5141ee0e884def286ded6185241f39
Author: Liang-Chi Hsieh <[email protected]>
AuthorDate: Tue Nov 10 22:59:27 2026 -0800

    [SPARK-60325][SQL] Remove the holding of input batches from columnar Python 
UDFs
    
    ### What changes were proposed in this pull request?
    
    With columnar input 
(`spark.sql.execution.arrow.pythonUDF.columnarInput.enabled`), 
`ColumnarArrowEvalPythonEvaluatorFactory` (SPARK-56350) could keep the 
pass-through columns of an input batch until its result came back from Python, 
many batches later. #59551 (SPARK-60294) disabled columnar input by default 
because a producer may overwrite or free its vectors before then. This PR 
removes that holding, so columnar input is correct for every producer:
    
    - The Arrow columnar path is removed. Columnar input always copies the 
pass-through columns into the `HybridRowQueue` and joins the results by row. If 
the UDF inputs are plain column references, those of Arrow-backed batches are 
still written to Python directly.
    - The results of Python can be sliced with `maxRecordsPerOutputBatch` and 
`maxBytesPerOutputBatch`, since they are no longer paired with input batches. 
This also makes the batch pairing of iterator UDFs a non-issue.
    - The batches rebuilt from the joined rows now support `NullType` and UDT 
columns, treat a non-positive `maxRecordsPerBatch` as no row limit, and also 
stop at `maxBytesPerBatch`.
    - Input batches without rows are released and skipped.
    - `spark.sql.execution.arrow.pythonUDF.columnarInput.enabled` stays `false` 
by default. Its documentation and the 4.4 entry of the migration guide are 
updated.
    
    ### Why are the changes needed?
    
    With columnar input enabled, Python UDFs failed with 
`IndexOutOfBoundsException`, or paired the pass-through values of a later batch 
with the results of an earlier one, when the source of the batches reused or 
released its vectors, e.g. the Arrow cache. `ColumnVector` does not promise 
that a vector stays valid after the next batch is requested. Writing the UDF 
inputs directly does not need that promise, only the pass-through columns did.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, with `spark.sql.execution.arrow.pythonUDF.columnarInput.enabled` set 
to `true`, since it stays disabled by default: the results are correct for 
sources that reuse or release their vectors, the pass-through columns are 
always converted to rows and back, and the results of Python follow 
`maxRecordsPerOutputBatch` and `maxBytesPerOutputBatch`.
    
    ### How was this patch tested?
    
    Added or changed tests in `ArrowColumnarPythonUDFSuite`, 
`ArrowCachedPythonUDFSuite` and `RowToColumnConverterSuite`:
    - a reader that refills the same vectors for every batch, with columnar 
input on and off, over 2 and 200 batches;
    - two stacked `ArrowEvalPythonExec`s, and 200 batches of the Arrow cache;
    - the limits on the results of Python and on the rebuilt batches, including 
a non-positive `maxRecordsPerBatch`;
    - input batches without rows, which are released and not sent to Python;
    - a limit that stops reading the results early;
    - `NullType` and UDT columns passed through over the Arrow cache, and in 
the converter.
    
    Ran `ArrowColumnarPythonUDFSuite`, `ArrowColumnarPythonUDFPipelinedSuite`, 
`ArrowCachedPythonUDFSuite`, `ArrowCachedBatchSerializerSuite`, 
`ColumnarBatchSuite`, `ColumnVectorSuite`, `RowToColumnConverterSuite` and 
`pyspark.sql.tests.arrow.test_arrow_python_udf_cached`.
    
    ### 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 #59582 from viirya/SPARK-60325.
    
    Authored-by: Liang-Chi Hsieh <[email protected]>
    Signed-off-by: Liang-Chi Hsieh <[email protected]>
    (cherry picked from commit 5abfe790eda72549c1d46e1cd14883b79e0750c7)
    Signed-off-by: Liang-Chi Hsieh <[email protected]>
---
 docs/sql-migration-guide.md                        |   2 +-
 .../tests/arrow/test_arrow_python_udf_cached.py    |   4 +-
 .../org/apache/spark/sql/internal/SQLConf.scala    |  21 +-
 .../org/apache/spark/sql/execution/Columnar.scala  |  10 +
 .../sql/execution/python/ArrowEvalPythonExec.scala |  21 +-
 .../ColumnarArrowEvalPythonEvaluatorFactory.scala  | 174 +++---------
 .../python/ColumnarArrowPythonRunner.scala         |   5 -
 .../sql/execution/RowToColumnConverterSuite.scala  |  33 +++
 .../execution/python/ArrowBackedDataSourceV2.scala |  62 +++--
 .../python/ArrowCachedPythonUDFSuite.scala         |  64 ++++-
 .../python/ArrowColumnarPythonUDFSuite.scala       | 294 ++++++++++++++++-----
 11 files changed, 425 insertions(+), 265 deletions(-)

diff --git a/docs/sql-migration-guide.md b/docs/sql-migration-guide.md
index 62db779f4abe..62d2fa8882a2 100644
--- a/docs/sql-migration-guide.md
+++ b/docs/sql-migration-guide.md
@@ -41,7 +41,7 @@ license: |
 - Since Spark 4.4, an auto-filled generated column of a Data Source V2 table 
reads a field of another column, such as `s.f`, from the value stored in that 
column. Previously, it read the value of the query before the store assignment 
cast, so it could silently store a value that does not match the stored column, 
and a later write of that row failed with `CHECK_CONSTRAINT_VIOLATION` 
(SPARK-60803). Rows that are already stored keep their values, and data derived 
from them may need to be re [...]
 - Since Spark 4.4, `spark.addArtifact` and `spark.addArtifacts` take a file 
whose name ends with `.sparkpkg` as a [native data source 
package](sql-native-data-sources.html), also when it is added with `file=True`, 
`pyfile=True` or `archive=True` in Python without Spark Connect, or with 
`file=True` from a Spark Connect client, and fail with 
`INVALID_NATIVE_DATA_SOURCE_PACKAGE` for such a file that is not a valid 
package, or whose version Spark does not support, or that has no library for  
[...]
 - Since Spark 4.4, `vector_avg` avoids intermediate subtraction overflow when 
updating running averages for `ARRAY<FLOAT>` inputs. Extreme finite inputs that 
previously produced infinity or `NaN` during updates may now produce a finite 
average. An infinite running average combined with a finite value or an 
infinity of the same sign now produces infinity with that sign instead of 
`NaN`. Opposite infinities and `NaN` inputs continue to produce `NaN`.
-- Since Spark 4.4, `spark.sql.execution.arrow.pythonUDF.columnarInput.enabled` 
is `false` by default: Arrow-based Python UDFs read rows from an Arrow-backed 
upstream operator, such as a Data Source V2 scan or the Arrow cache, as before 
Spark 4.2. With columnar input, they kept the columns that they pass through 
until the results of their batch came back from Python, and failed or returned 
wrong results when the operator reused or released the vectors of the batch in 
the meantime. To enab [...]
+- Since Spark 4.4, `spark.sql.execution.arrow.pythonUDF.columnarInput.enabled` 
is `false` by default: Arrow-based Python UDFs read rows from an Arrow-backed 
upstream operator, such as a Data Source V2 scan or the Arrow cache, as before 
Spark 4.2. With columnar input, they kept the columns that they pass through 
until the results of their batch came back from Python, and failed or returned 
wrong results when the operator reused or released the vectors of the batch in 
the meantime. To enab [...]
 - Since Spark 4.4, the conversion of columnar batches to rows releases each 
batch with `ColumnVector.closeIfFreeable` once its rows are consumed also when 
it is not whole-stage code-generated, e.g. when the query has more than 
`spark.sql.codegen.maxFields` fields or `spark.sql.codegen.wholeStage` is 
`false`, as the generated code has done since Spark 3.5.4 and 4.0. A 
`ColumnVector` that a Data Source V2 source reuses across batches, such as an 
`ArrowColumnVector` over a `VectorSchemaRoot [...]
 - Since Spark 4.4, `spark.sql.charVarchar.standardSemantics.enabled` (default 
`false`) is a preview feature that may change in future releases. When true, it 
enables first-class `CHAR(n)` and `VARCHAR(n)` semantics throughout schemas and 
query plans: `CHAR` -> `VARCHAR` -> `STRING` form a type-precedence family, 
explicit casts can return constrained types, least-common-type resolution for 
`COALESCE`/`CASE`/`UNION` can return `CHAR` or `VARCHAR`, and string 
expressions that transform thei [...]
 - Since Spark 4.4, when `spark.sql.charVarchar.standardSemantics.enabled` is 
true, `from_json` length-checks JSON object names used as `MAP<CHAR(n), _>` or 
`MAP<VARCHAR(n), _>` keys without padding or trimming them. A `CHAR(n)` key 
must already be exactly `n` characters, and a `VARCHAR(n)` key must already be 
at most `n` characters; duplicate names are kept, exactly as for STRING keys, 
and `spark.sql.mapKeyDedupPolicy` is not applied. A key that fails the check 
makes the enclosing map a  [...]
diff --git a/python/pyspark/sql/tests/arrow/test_arrow_python_udf_cached.py 
b/python/pyspark/sql/tests/arrow/test_arrow_python_udf_cached.py
index 196c172de54e..ee6d4eb3e6b2 100644
--- a/python/pyspark/sql/tests/arrow/test_arrow_python_udf_cached.py
+++ b/python/pyspark/sql/tests/arrow/test_arrow_python_udf_cached.py
@@ -134,8 +134,8 @@ class ArrowPythonUDFCachedInputTests(ReusedSQLTestCase):
             df.unpersist()
 
     def test_udf_on_cached_input_with_output_batch_slicing(self):
-        # The columnar path pairs each result batch with one input batch, so 
the 10-row result
-        # of the single cached batch must not be sliced under the configs 
below.
+        # The 10-row result of the single cached batch is sliced under the 
configs below, and
+        # must still line up with its rows, which are paired with the results 
by row.
         df = self.spark.range(0, 10, 1, 1).cache()
         try:
             for conf in [
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 18f2b8343f24..87f3fa297348 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
@@ -5629,8 +5629,7 @@ object SQLConf {
         "the columnar-based operator implemented by third-party libraries. A 
batch that " +
         "Arrow cannot slice, e.g. one with a fixed-width column of 2 GiB or 
more, is sent " +
         "as a whole. " +
-        "applyInPandasWithState, Arrow Python UDTFs and Arrow Python UDFs that 
take " +
-        "columnar input directly ignore this config.")
+        "applyInPandasWithState and Arrow Python UDTFs ignore this config.")
       .version("4.1.0")
       .internal()
       .intConf
@@ -5648,8 +5647,7 @@ object SQLConf {
         "happen, but if in extreme case that even one record is still larger 
than this value, " +
         "Spark will create a batch with one record. A batch that Arrow cannot 
slice, e.g. one " +
         "with a fixed-width column of 2 GiB or more, is sent as a whole. " +
-        "applyInPandasWithState, Arrow Python UDTFs and Arrow Python UDFs that 
" +
-        "take columnar input directly ignore this config.")
+        "applyInPandasWithState and Arrow Python UDTFs ignore this config.")
       .version("4.1.0")
       .internal()
       .bytesConf(ByteUnit.BYTE)
@@ -5703,15 +5701,12 @@ object SQLConf {
 
   val ARROW_PYSPARK_UDF_COLUMNAR_INPUT_ENABLED =
     buildConf("spark.sql.execution.arrow.pythonUDF.columnarInput.enabled")
-      .doc("When true, Arrow-based Python UDFs (pandas UDFs) can accept " +
-        "columnar input directly from upstream operators that produce " +
-        "Arrow-backed ColumnarBatch (e.g., DataSource V2 connectors), " +
-        "bypassing the ColumnarToRow and ArrowWriter conversion. " +
-        "This optimization reduces data transfer overhead between " +
-        "the JVM and Python worker processes. It keeps the columns that the 
UDFs pass " +
-        "through until the results of their batch come back from Python, so it 
requires " +
-        "an upstream operator whose batches stay valid until then, which a 
columnar " +
-        "reader does not promise.")
+      .doc("When true, Arrow-based Python UDFs (pandas UDFs) accept columnar 
input " +
+        "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.")
       .version("4.2.0")
       .withBindingPolicy(ConfigBindingPolicy.SESSION)
       .booleanConf
diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/Columnar.scala 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/Columnar.scala
index 121011e3becd..346c8e24076f 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/Columnar.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/Columnar.scala
@@ -309,6 +309,9 @@ private object RowToColumnConverter {
       case st: StructType => new StructConverter(st.fields.map(
         (f) => getConverterForType(f.dataType, f.nullable)))
       case dt: DecimalType => new DecimalConverter(dt)
+      case NullType => NullConverter
+      // Rows and column vectors both hold a UDT in the form of its SQL type.
+      case udt: UserDefinedType[_] => getConverterForType(udt.sqlType, 
nullable)
       case mt: MapType => MapConverter(getConverterForType(mt.keyType, 
nullable = false),
         getConverterForType(mt.valueType, mt.valueContainsNull))
       case unknown => throw ExecutionErrors.unsupportedDataTypeError(unknown)
@@ -316,6 +319,8 @@ private object RowToColumnConverter {
 
     if (nullable) {
       dataType match {
+        // The converter of its SQL type handles the nulls.
+        case _: UserDefinedType[_] => core
         case CalendarIntervalType | VariantType => new 
StructNullableTypeConverter(core)
         case _: AnyTimestampNanoType =>
           new StructNullableTypeConverter(core)
@@ -327,6 +332,11 @@ private object RowToColumnConverter {
     }
   }
 
+  // A column vector of NullType is all null and stores nothing.
+  private object NullConverter extends TypeConverter {
+    override def append(row: SpecializedGetters, column: Int, cv: 
WritableColumnVector): Unit = {}
+  }
+
   private object BinaryConverter extends TypeConverter {
     override def append(row: SpecializedGetters, column: Int, cv: 
WritableColumnVector): Unit = {
       val bytes = row.getBinary(column)
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 19b2b6a7ed3f..2a7df7844b0c 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
@@ -113,15 +113,17 @@ case class ArrowEvalPythonExec(
     }
   }
 
-  // When the child supports columnar output (e.g., Arrow-backed DSv2 
connectors),
-  // accept columnar input to avoid the ColumnarToRow -> ArrowWriter 
round-trip.
-  // The Arrow FieldVectors are extracted directly from ArrowColumnVector and
-  // serialized to IPC, bypassing the row-based ArrowWriter conversion.
-  // This node then outputs only columnar batches, so the planner inserts a
-  // ColumnarToRowExec above it for a row-based parent, which releases each
-  // batch once its rows are consumed. 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.
+  // When the child supports columnar output (e.g., Arrow-backed DSv2 
connectors)
+  // and columnar input is enabled, accept columnar input: the UDF inputs of a
+  // 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, and 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.
+  // 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
 
@@ -143,6 +145,7 @@ case class ArrowEvalPythonExec(
       output,
       output.toStructType,
       conf.arrowMaxRecordsPerBatch,
+      conf.arrowMaxBytesPerBatch,
       evalType,
       conf.sessionLocalTimeZone,
       conf.arrowUseLargeVarTypes,
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 ef8a9ac38143..5ecb4b113472 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
@@ -17,7 +17,6 @@
 package org.apache.spark.sql.execution.python
 
 import java.io.File
-import java.util.ArrayDeque
 
 import scala.collection.mutable.ArrayBuffer
 import scala.jdk.CollectionConverters._
@@ -25,7 +24,6 @@ import scala.jdk.CollectionConverters._
 import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, 
SparkEnv, TaskContext}
 import org.apache.spark.api.python.ChainedPythonFunctions
 import org.apache.spark.internal.config.Python.PYTHON_UDF_PIPELINED_EXECUTION
-import org.apache.spark.sql.catalyst.InternalRow
 import org.apache.spark.sql.catalyst.expressions._
 import org.apache.spark.sql.errors.QueryExecutionErrors
 import org.apache.spark.sql.execution.RowToColumnConverter
@@ -34,46 +32,39 @@ import 
org.apache.spark.sql.execution.python.EvalPythonExec.ArgumentMetadata
 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.{ArrowColumnVector, ColumnarBatch, 
ColumnVector}
+import org.apache.spark.sql.vectorized.ColumnarBatch
 import org.apache.spark.util.Utils
 
 /**
  * Evaluator factory for Arrow Python UDFs: ColumnarBatch in, ColumnarBatch 
out.
  *
- * Three execution paths based on input characteristics:
+ * Two execution paths based on the UDF inputs:
  *
- * 1. '''Arrow columnar path''' (UDF inputs are simple column refs AND
- *    columns are [[ArrowColumnVector]]): Arrow FieldVectors are extracted
- *    directly and serialized to IPC. Pass-through columns are kept as
- *    [[ColumnVector]] references, which is only correct if the batches stay
- *    valid until their results come back from Python: a columnar reader may
- *    reuse or release the vectors of a batch once it is asked for the next
- *    one. So `spark.sql.execution.arrow.pythonUDF.columnarInput.enabled`
- *    is disabled by default. Output is produced by columnar combining:
- *    passThruCols ++ resultCols -> ColumnarBatch, so the consumer of the
- *    output releases the pass-through columns with closeIfFreeable on the
- *    task thread. With `spark.python.udf.pipelined.enabled`, the Python
- *    writer reads the next input batches on its own thread meanwhile, so
- *    the upstream operator must allow its vectors to be released while it
- *    returns the next batches.
+ * 1. '''Row queue columnar path''' (UDF inputs are simple column refs):
+ *    The UDF inputs of Arrow-backed batches are serialized to IPC directly,
+ *    and those of other batches row by row.
  *
- * 2. '''Non-Arrow columnar path''' (UDF inputs are simple column refs
- *    BUT columns are NOT [[ArrowColumnVector]]): Non-Arrow columnar
- *    readers (Parquet vectorized, InMemoryTableScan) reuse ColumnVector
- *    objects across batches. Uses [[HybridRowQueue]] for pass-through
- *    buffering and converts joined rows back to [[ColumnarBatch]].
- *
- * 3. '''Row fallback path''' (UDF inputs contain complex expressions):
+ * 2. '''Row fallback path''' (UDF inputs contain complex expressions):
  *    Rows are extracted via [[MutableProjection]] and sent using
- *    [[BasicPythonArrowInput]]. Uses [[HybridRowQueue]] for pass-through
- *    and converts joined rows back to [[ColumnarBatch]].
+ *    [[BasicPythonArrowInput]].
  *
- * Paths 2 and 3 copy what they need from an input batch, so they release
- * it with closeIfFreeable once it has been written to Python.
+ * The results of a batch come back from Python after the writer has asked
+ * for the next batches, and a producer may overwrite or free the vectors of
+ * a batch once the next one is requested, e.g. Parquet vectorized readers
+ * reuse `WritableColumnVector`s across batches, the Arrow cache releases
+ * the vectors of a batch when the next one is read, and the Python output
+ * of a stacked [[ArrowEvalPythonExec]] is loaded into the same vectors for
+ * every batch. So both paths copy the pass-through columns into a
+ * [[HybridRowQueue]], release a batch with closeIfFreeable once it has been
+ * written to Python, join the results by row and convert the joined rows
+ * back to [[ColumnarBatch]]. Input batches without rows are released and
+ * skipped, so that the UDFs are not called with empty input, as on the row
+ * path.
  *
  * 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 path 3.
+ *   into simple column references. This would eliminate the row fallback
+ *   path.
  */
 private[python] class ColumnarArrowEvalPythonEvaluatorFactory(
     childOutput: Seq[Attribute],
@@ -81,6 +72,7 @@ private[python] class ColumnarArrowEvalPythonEvaluatorFactory(
     output: Seq[Attribute],
     outputSchema: StructType,
     batchSize: Int,
+    maxBytesPerBatch: Long,
     evalType: Int,
     sessionLocalTimeZone: String,
     largeVarTypes: Boolean,
@@ -153,25 +145,13 @@ private[python] class 
ColumnarArrowEvalPythonEvaluatorFactory(
           case udt: UserDefinedType[_] => udt.sqlType
         })
 
-      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) {
-        // Path 1: Arrow columnar -- full optimization.
-        evalArrowColumnar(peekIter, context, pyFuncs, argMetas,
-          udfInputSchema, outputTypes, inputColumnIndices.get)
-      } else {
-        // Path 2 & 3: non-Arrow or complex expressions.
-        evalWithRowQueue(peekIter, context, pyFuncs, argMetas,
-          allInputs.toSeq, udfInputSchema, outputTypes,
-          inputColumnIndices)
-      }
+      evalWithRowQueue(nonEmptyIter, context, pyFuncs, argMetas,
+        allInputs.toSeq, udfInputSchema, outputTypes, 
resolveColumnIndices(allInputs.toSeq))
     }
 
     private def resolveColumnIndices(
@@ -186,54 +166,6 @@ private[python] class 
ColumnarArrowEvalPythonEvaluatorFactory(
     }
 
     /**
-     * Path 1: Arrow columnar. Keeps references to the pass-through
-     * ColumnVectors, which requires the input batches to stay valid until
-     * their results come back from Python, and combines them with the UDF
-     * result columns into ColumnarBatch.
-     */
-    private def evalArrowColumnar(
-        inputIter: Iterator[ColumnarBatch],
-        context: TaskContext,
-        pyFuncs: Seq[(ChainedPythonFunctions, Long)],
-        argMetas: Array[Array[ArgumentMetadata]],
-        udfInputSchema: StructType,
-        outputTypes: Seq[DataType],
-        columnIndices: Array[Int]): Iterator[ColumnarBatch] = {
-
-      val passThruQueue =
-        new ArrayDeque[(Array[ColumnVector], Int)]()
-
-      val bufferedIter = inputIter.map { batch =>
-        val passThruCols = childOutput.indices.map(
-          i => batch.column(i)).toArray
-        passThruQueue.add((passThruCols, batch.numRows()))
-        batch
-      }
-
-      val pyRunner = new ColumnarArrowPythonWithNamedArgumentRunner(
-        pyFuncs, evalType, argMetas, udfInputSchema,
-        sessionLocalTimeZone, largeVarTypes, pythonRunnerConf,
-        pythonMetrics, jobArtifactUUID, sessionUUID,
-        columnIndices, udfs.map(_.elementwiseNestingDepth))
-
-      val resultIter = pyRunner.compute(
-        bufferedIter, context.partitionId(), context)
-
-      resultIter.map { resultBatch =>
-        validateOutputTypes(resultBatch, outputTypes)
-        val numRows = resultBatch.numRows()
-        val resultCols = (0 until resultBatch.numCols()).map(
-          i => resultBatch.column(i)).toArray
-        val (passThruCols, passThruRows) = passThruQueue.poll()
-        assert(passThruRows == numRows,
-          s"Batch size mismatch: pass-through has " +
-            s"$passThruRows rows but UDF result has $numRows rows.")
-        new ColumnarBatch(passThruCols ++ resultCols, numRows)
-      }
-    }
-
-    /**
-     * Paths 2 & 3: non-Arrow or complex expressions.
      * Uses HybridRowQueue for pass-through, joins rows, then
      * converts back to ColumnarBatch via RowToColumnConverter.
      */
@@ -262,7 +194,7 @@ private[python] class 
ColumnarArrowEvalPythonEvaluatorFactory(
         childOutput, childOutput)
 
       val resultIter = if (inputColumnIndices.isDefined) {
-        // Path 2: simple column refs, non-Arrow vectors.
+        // Simple column refs: the writer sends Arrow-backed batches directly.
         val bufferedIter = new WrittenBatchReleasingIterator(inputIter, { 
batch =>
           batch.rowIterator().asScala.foreach { row =>
             queue.add(unsafeProj(row).copy())
@@ -278,7 +210,7 @@ private[python] class 
ColumnarArrowEvalPythonEvaluatorFactory(
         pyRunner.compute(
           bufferedIter, context.partitionId(), context)
       } else {
-        // Path 3: complex expressions.
+        // Complex expressions.
         val projection = MutableProjection.create(
           allInputs, childOutput)
         projection.initialize(context.partitionId())
@@ -325,13 +257,18 @@ private[python] class 
ColumnarArrowEvalPythonEvaluatorFactory(
       }
     }
 
-    /** Convert Iterator[InternalRow] to Iterator[ColumnarBatch]. */
+    /**
+     * 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[InternalRow],
+        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(batchSize, outputSchema).toSeq
+        .allocateColumns(initialCapacity, outputSchema).toSeq
       val cb = new ColumnarBatch(vectors.toArray)
       context.addTaskCompletionListener[Unit] { _ => cb.close() }
 
@@ -341,8 +278,12 @@ private[python] class 
ColumnarArrowEvalPythonEvaluatorFactory(
           cb.setNumRows(0)
           vectors.foreach(_.reset())
           var count = 0
-          while (count < batchSize && rowIter.hasNext) {
-            converters.convert(rowIter.next(), vectors.toArray)
+          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)
@@ -387,32 +328,3 @@ private[python] class WrittenBatchReleasingIterator(
     batch
   }
 }
-
-/** Iterator wrapper that allows peeking at the first element. */
-private[python] class PeekableIterator[T](underlying: Iterator[T])
-    extends Iterator[T] {
-  private var peeked: Option[T] = None
-  private var peekedDone = false
-
-  def peek(): Option[T] = {
-    if (!peekedDone) {
-      peeked = if (underlying.hasNext) Some(underlying.next())
-               else None
-      peekedDone = true
-    }
-    peeked
-  }
-
-  override def hasNext: Boolean =
-    peeked.isDefined || underlying.hasNext
-
-  override def next(): T = {
-    if (peeked.isDefined) {
-      val v = peeked.get
-      peeked = None
-      v
-    } else {
-      underlying.next()
-    }
-  }
-}
diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ColumnarArrowPythonRunner.scala
 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ColumnarArrowPythonRunner.scala
index 81f78399784b..de19b43d32c1 100644
--- 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ColumnarArrowPythonRunner.scala
+++ 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/python/ColumnarArrowPythonRunner.scala
@@ -52,11 +52,6 @@ private[python] class 
ColumnarArrowPythonWithNamedArgumentRunner(
   with ColumnarArrowPythonInput
   with BasicPythonArrowOutput {
 
-  // `ColumnarArrowEvalPythonEvaluatorFactory.evalArrowColumnar` pairs each 
output batch with
-  // one input batch, so the batches returned from Python must not be sliced.
-  override protected def arrowMaxRecordsPerOutputBatch: Int = -1
-  override protected def arrowMaxBytesPerOutputBatch: Int = -1
-
   override protected def runnerConf: Map[String, String] = super.runnerConf ++ 
pythonRunnerConf
 
   // The input schema (and per-UDF nesting depth) travel in evalConf, exactly 
like
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/RowToColumnConverterSuite.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/RowToColumnConverterSuite.scala
index dfcbc01b5f89..711aa4663e6d 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/RowToColumnConverterSuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/RowToColumnConverterSuite.scala
@@ -21,10 +21,18 @@ import org.apache.spark.SparkFunSuite
 import org.apache.spark.sql.catalyst.InternalRow
 import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, ArrayData, 
GenericArrayData}
 import org.apache.spark.sql.execution.vectorized.{OnHeapColumnVector, 
WritableColumnVector}
+import org.apache.spark.sql.test.ExamplePointUDT
 import org.apache.spark.sql.types._
 import org.apache.spark.unsafe.types.{TimestampNanosVal, UTF8String}
 import org.apache.spark.util.ArrayImplicits._
 
+private class StructBackedUDT extends UserDefinedType[InternalRow] {
+  override def sqlType: DataType = new StructType().add("x", 
IntegerType).add("y", IntegerType)
+  override def serialize(obj: InternalRow): Any = obj
+  override def deserialize(datum: Any): InternalRow = 
datum.asInstanceOf[InternalRow]
+  override def userClass: Class[InternalRow] = classOf[InternalRow]
+}
+
 class RowToColumnConverterSuite extends SparkFunSuite {
   def convertRows(rows: Seq[InternalRow], schema: StructType): 
Seq[WritableColumnVector] = {
     val converter = new RowToColumnConverter(schema)
@@ -228,6 +236,31 @@ class RowToColumnConverterSuite extends SparkFunSuite {
     assert(vectors.head.getLong(2) === 86399999999999L)
   }
 
+  test("SPARK-60325: null type column") {
+    Seq(
+      StructType(Seq(StructField("n", NullType))),
+      StructType(Seq(StructField("n", NullType, nullable = false)))).foreach { 
schema =>
+      val vectors = convertRows(Seq.fill(10)(InternalRow(null)), schema)
+      (0 until 10).foreach(i => assert(vectors.head.isNullAt(i)))
+    }
+  }
+
+  test("SPARK-60325: user-defined type columns hold their SQL type") {
+    // A null of a struct-backed type must be appended as a struct.
+    val arrayBacked = new ExamplePointUDT
+    val arrayRows = Seq(InternalRow(new GenericArrayData(Array(1.0, 2.0))), 
InternalRow(null))
+    val arrayVectors = convertRows(arrayRows, StructType(Seq(StructField("p", 
arrayBacked))))
+    assert(arrayVectors.head.getArray(0).toDoubleArray() === Array(1.0, 2.0))
+    assert(arrayVectors.head.isNullAt(1))
+
+    val structBacked = new StructBackedUDT
+    val structRows = Seq(InternalRow(InternalRow(1, 2)), InternalRow(null))
+    val structVectors = convertRows(structRows, 
StructType(Seq(StructField("s", structBacked))))
+    assert(structVectors.head.getStruct(0).getInt(0) === 1)
+    assert(structVectors.head.getStruct(0).getInt(1) === 2)
+    assert(structVectors.head.isNullAt(1))
+  }
+
   test("multiple columns") {
     val schema = StructType(
       Seq(StructField("s", ShortType), StructField("i", IntegerType), 
StructField("l", LongType)))
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowBackedDataSourceV2.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowBackedDataSourceV2.scala
index 69139c892ced..6afb78eac88f 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowBackedDataSourceV2.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowBackedDataSourceV2.scala
@@ -30,6 +30,7 @@ import org.apache.spark.sql.catalyst.InternalRow
 import org.apache.spark.sql.connector.catalog.{SupportsRead, Table, 
TableCapability, TableProvider}
 import org.apache.spark.sql.connector.expressions.Transform
 import org.apache.spark.sql.connector.read._
+import org.apache.spark.sql.execution.vectorized.ReusedArrowColumnVector
 import org.apache.spark.sql.types._
 import org.apache.spark.sql.util.ArrowUtils
 import org.apache.spark.sql.util.CaseInsensitiveStringMap
@@ -144,9 +145,12 @@ private class ArrowBackedScanBuilder(options: 
CaseInsensitiveStringMap)
     options.getInt("batchSize", ArrowBackedDataSourceV2.BATCH_SIZE)
   private val arrowIdColumn =
     options.getBoolean("arrowIdColumn", true)
+  private val emptyBatches =
+    options.getBoolean("emptyBatches", false)
 
   override def createReaderFactory(): PartitionReaderFactory = {
-    new ArrowBackedReaderFactory(columnar, reuseVectors, batchSize, 
arrowIdColumn)
+    new ArrowBackedReaderFactory(
+      columnar, reuseVectors, batchSize, arrowIdColumn, emptyBatches)
   }
 }
 
@@ -163,12 +167,15 @@ private case class ArrowPartition(start: Int, end: Int)
  *   the columnar optimization.
  * @param arrowIdColumn if false, the `id` column of the batches is not an
  *   [[ArrowColumnVector]], so that a batch is not entirely Arrow-backed.
+ * @param emptyBatches if true, the reader with fresh vectors also returns 
batches without rows,
+ *   first, in the middle and last.
  */
 private class ArrowBackedReaderFactory(
     columnar: Boolean,
     reuseVectors: Boolean,
     batchSize: Int,
-    arrowIdColumn: Boolean)
+    arrowIdColumn: Boolean,
+    emptyBatches: Boolean)
   extends PartitionReaderFactory {
 
   override def supportColumnarReads(
@@ -198,7 +205,7 @@ private class ArrowBackedReaderFactory(
     if (reuseVectors) {
       new ReusingArrowPartitionReader(start, end, batchSize)
     } else {
-      new ArrowBackedPartitionReader(start, end, batchSize, arrowIdColumn)
+      new ArrowBackedPartitionReader(start, end, batchSize, arrowIdColumn, 
emptyBatches)
     }
   }
 }
@@ -206,7 +213,8 @@ private class ArrowBackedReaderFactory(
 /**
  * Reads the same rows as [[ArrowBackedPartitionReader]], with short values in 
`data`, but refills
  * the same vectors for every batch and closes them once the reader is closed, 
as columnar readers
- * may: a batch is only valid until the next one.
+ * may: a batch is only valid until the next one. Its columns are 
[[ReusedArrowColumnVector]]s,
+ * whose closeIfFreeable is a no-op.
  */
 private class ReusingArrowPartitionReader(start: Int, end: Int, batchSize: Int)
     extends PartitionReader[ColumnarBatch] {
@@ -218,7 +226,7 @@ private class ReusingArrowPartitionReader(start: Int, end: 
Int, batchSize: Int)
       errorOnDuplicatedFieldNames = true, largeVarTypes = false),
     allocator)
   private val batch = new ColumnarBatch(
-    root.getFieldVectors.asScala.map(new ArrowColumnVector(_): 
ColumnVector).toArray)
+    root.getFieldVectors.asScala.map(new ReusedArrowColumnVector(_): 
ColumnVector).toArray)
 
   override def next(): Boolean = {
     if (current >= end) return false
@@ -259,28 +267,34 @@ private class ReusingArrowPartitionReader(start: Int, 
end: Int, batchSize: Int)
  * - value (DOUBLE): id * 0.1
  * - data (STRING): 100 random characters
  *
- * Every batch has vectors of its own, which are not reused vectors: the 
consumer may
- * hold them past the next batch, even past the close of the reader, and 
releases them with
- * closeIfFreeable. The ones it does not release are closed when the task 
completes. Their
- * release is counted in [[ArrowBackedDataSourceV2]].
+ * Every batch has vectors of its own, which its consumer releases with 
closeIfFreeable. The ones
+ * it does not release are closed when the task completes. Their release is 
counted in
+ * [[ArrowBackedDataSourceV2]].
  *
  * If `arrowIdColumn` is false, the `id` column is a [[ColumnVector]] over its 
Arrow vector that is
- * not an [[ArrowColumnVector]].
+ * not an [[ArrowColumnVector]]. If `emptyBatches` is true, the reader also 
returns batches without
+ * rows, before the first batch, after half of the batches and after the last 
one.
  */
 private class ArrowBackedPartitionReader(
     start: Int,
     end: Int,
     batchSize: Int,
-    arrowIdColumn: Boolean = true)
+    arrowIdColumn: Boolean = true,
+    emptyBatches: Boolean = false)
   extends PartitionReader[ColumnarBatch] {
 
   private var current = start
+  // The positions before which the reader returns a batch without rows.
+  private val emptyBatchPositions = if (emptyBatches) {
+    scala.collection.mutable.Set(start, start + (end - start) / batchSize / 2 
* batchSize, end)
+  } else {
+    scala.collection.mutable.Set.empty[Int]
+  }
   private var currentBatch: ColumnarBatch = _
 
   // Single allocator for the entire partition reader lifetime.
-  // Arrow vectors from earlier batches may still be referenced by
-  // downstream operators (e.g., pass-through column queue), so we
-  // must NOT close the allocator until the task completes.
+  // The vectors of the returned batches are closed when the task
+  // completes, so we must NOT close the allocator until then.
   private val allocator: BufferAllocator =
     ArrowUtils.rootAllocator.newChildAllocator(
       s"arrow-test-reader-$start", 0, Long.MaxValue)
@@ -290,9 +304,9 @@ private class ArrowBackedPartitionReader(
     new java.util.ArrayList[ColumnarBatch]()
   private var numReleased = 0
 
-  // The consumer may still hold the returned batches, even past the close of 
the reader, so they
-  // are closed when the task completes. A pipelined Python writer that reads 
them is stopped by a
-  // pre-completion listener, which runs before this one.
+  // A consumer that stops early does not release the batches, so they are 
closed when the task
+  // completes. A pipelined Python writer that reads them is stopped by a 
pre-completion listener,
+  // which runs before this one.
   TaskContext.get().addTaskCompletionListener[Unit] { _ =>
     allBatches.synchronized {
       allBatches.forEach(_.close())
@@ -343,9 +357,13 @@ private class ArrowBackedPartitionReader(
   }
 
   override def next(): Boolean = {
-    if (current >= end) return false
-
-    val count = math.min(batchSize, end - current)
+    val count = if (emptyBatchPositions.remove(current)) {
+      0
+    } else if (current >= end) {
+      return false
+    } else {
+      math.min(batchSize, end - current)
+    }
 
     // Create Arrow vectors
     val idVector = createIntVector(allocator, "id", count)
@@ -354,7 +372,7 @@ private class ArrowBackedPartitionReader(
     val dataVector = createLongStringVector(
       allocator, "data", count)
 
-    // Wrap in ArrowColumnVector
+    // Wrap in ArrowColumnVectors
     val columns: Array[ColumnVector] = Array(
       if (arrowIdColumn) {
         new ReleaseCountingArrowColumnVector(idVector)
@@ -378,7 +396,7 @@ private class ArrowBackedPartitionReader(
 
   override def get(): ColumnarBatch = currentBatch
 
-  // The consumer may still hold the returned batches, which are closed when 
the task completes.
+  // The returned batches are closed when the task completes.
   override def close(): Unit = {
     currentBatch = null
   }
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowCachedPythonUDFSuite.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowCachedPythonUDFSuite.scala
index a06abd498567..48e2e20a5ef3 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowCachedPythonUDFSuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/python/ArrowCachedPythonUDFSuite.scala
@@ -21,7 +21,7 @@ import org.apache.spark.SparkConf
 import org.apache.spark.sql.IntegratedUDFTestUtils
 import org.apache.spark.sql.execution.columnar.{ArrowCachedBatchSerializer, 
InMemoryRelation}
 import org.apache.spark.sql.internal.{SQLConf, StaticSQLConf}
-import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.test.{ExamplePoint, SharedSparkSession}
 import org.apache.spark.sql.types.StringType
 
 /**
@@ -49,11 +49,13 @@ class ArrowCachedPythonUDFSuite extends SharedSparkSession {
     }
   }
 
-  test("Arrow Python UDFs over the Arrow cache with the default 
configuration") {
+  test("Arrow Python UDFs over the Arrow cache, with and without columnar 
input") {
     assume(shouldTestPandasUDFs)
     // The scan of the Arrow cache also returns rows, so no ColumnarToRowExec 
is added below
     // ArrowEvalPythonExec, whose child still supports columnar: it must still 
read rows when
-    // columnar input is disabled, as it is by default.
+    // columnar input is disabled, as it is by default. With columnar input, 
the cache closes the
+    // root of a batch when it returns the next one, so the pass-through 
columns of its 200
+    // batches must be copied before then.
     withSQLConf(SQLConf.ARROW_EXECUTION_MAX_RECORDS_PER_BATCH.key -> "1000") {
       val pandasUDF = TestScalarPandasUDF(
         name = "cached_str_udf", returnType = Some(StringType))
@@ -62,20 +64,60 @@ class ArrowCachedPythonUDFSuite extends SharedSparkSession {
       val cached = spark.range(0, 200000, 1, 1).selectExpr("id", "CAST(id AS 
STRING) AS s")
         .cache()
       try {
-        // The test UDF casts its input to string, which is removed on a 
string column.
-        val result = cached.selectExpr("id", "s", "cached_str_udf(s) AS u")
+        Seq(false, true).foreach { columnarInput =>
+          withSQLConf(
+              SQLConf.ARROW_PYSPARK_UDF_COLUMNAR_INPUT_ENABLED.key -> 
columnarInput.toString) {
+            // The test UDF casts its input to string, which is removed on a 
string column.
+            val result = cached.selectExpr("id", "s", "cached_str_udf(s) AS u")
+            val arrowExec = result.queryExecution.executedPlan.collect {
+              case exec: ArrowEvalPythonExec => exec
+            }
+            assert(arrowExec.nonEmpty && arrowExec.head.child.supportsColumnar 
&&
+              arrowExec.head.supportsColumnar == columnarInput)
+
+            val rows = result.collect()
+            assert(rows.map(_.getLong(0)).toSeq == (0L until 200000L))
+            rows.foreach { row =>
+              val id = row.getLong(0)
+              assert(row.getString(1) == id.toString, s"pass-through mismatch 
for id $id")
+              assert(row.getString(2) == id.toString, s"UDF result mismatch 
for id $id")
+            }
+          }
+        }
+      } finally {
+        cached.unpersist()
+      }
+    }
+  }
+
+  test("SPARK-60325: Columnar input passes through null type and user-defined 
type columns") {
+    assume(shouldTestPandasUDFs)
+    withSQLConf(SQLConf.ARROW_PYSPARK_UDF_COLUMNAR_INPUT_ENABLED.key -> 
"true") {
+      val pandasUDF = TestScalarPandasUDF(
+        name = "cached_types_udf", returnType = Some(StringType))
+      registerTestUDF(pandasUDF, spark)
+
+      val session = spark
+      import session.implicits._
+      val numRows = 1000
+      val points = (0 until numRows).map(i => (i.toString, new ExamplePoint(i, 
i + 1.0)))
+      val cached = spark.sparkContext.parallelize(points, 4).toDF("s", "p")
+        .selectExpr("s", "p", "NULL AS n")
+        .cache()
+      try {
+        val result = cached.selectExpr("s", "p", "n", "cached_types_udf(s) AS 
u")
         val arrowExec = result.queryExecution.executedPlan.collect {
           case exec: ArrowEvalPythonExec => exec
         }
-        assert(arrowExec.nonEmpty && arrowExec.head.child.supportsColumnar &&
-          !arrowExec.head.supportsColumnar)
+        assert(arrowExec.nonEmpty && arrowExec.head.supportsColumnar)
 
         val rows = result.collect()
-        assert(rows.map(_.getLong(0)).toSeq == (0L until 200000L))
+        assert(rows.map(_.getString(0).toInt).toSet == (0 until numRows).toSet)
         rows.foreach { row =>
-          val id = row.getLong(0)
-          assert(row.getString(1) == id.toString, s"pass-through mismatch for 
id $id")
-          assert(row.getString(2) == id.toString, s"UDF result mismatch for id 
$id")
+          val id = row.getString(0).toInt
+          assert(row.getAs[ExamplePoint](1) == new ExamplePoint(id, id + 1.0))
+          assert(row.isNullAt(2))
+          assert(row.getString(3) == id.toString)
         }
       } finally {
         cached.unpersist()
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 badfa6a694bd..36a36e0c3a5d 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
@@ -18,13 +18,14 @@
 package org.apache.spark.sql.execution.python
 
 import org.apache.spark.SparkConf
-import org.apache.spark.sql.IntegratedUDFTestUtils
+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, 
WholeStageCodegenExec}
-import org.apache.spark.sql.execution.vectorized.OnHeapColumnVector
+import org.apache.spark.sql.execution.{ColumnarToRowExec, SparkPlan, 
SQLExecution, WholeStageCodegenExec}
 import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.sql.test.SharedSparkSession
-import org.apache.spark.sql.types.StringType
+import org.apache.spark.sql.types.{StringType, StructType}
 
 /**
  * End-to-end tests for the Arrow columnar Python UDF input path.
@@ -49,7 +50,8 @@ class ArrowColumnarPythonUDFSuite extends SharedSparkSession {
       numPartitions: Int = 1,
       reuseVectors: Boolean = false,
       batchSize: Int = ArrowBackedDataSourceV2.BATCH_SIZE,
-      arrowIdColumn: Boolean = true) = {
+      arrowIdColumn: Boolean = true,
+      emptyBatches: Boolean = false) = {
     spark.read
       .format(arrowSource)
       .option("numRows", numRows.toString)
@@ -57,19 +59,23 @@ class ArrowColumnarPythonUDFSuite extends 
SharedSparkSession {
       .option("reuseVectors", reuseVectors.toString)
       .option("batchSize", batchSize.toString)
       .option("arrowIdColumn", arrowIdColumn.toString)
+      .option("emptyBatches", emptyBatches.toString)
       .load()
   }
 
-  /**
-   * Whether `exec` takes the Arrow columnar path, which outputs its input 
columns as they are,
-   * while the other paths output on-heap vectors.
-   */
-  private def takesArrowColumnarPath(exec: ArrowEvalPythonExec): Boolean = {
-    val columnClasses = exec.executeColumnar().mapPartitionsInternal { batches 
=>
-      batches.map(_.column(0).getClass.getName)
-    }.collect().toSet
-    assert(columnClasses.size == 1, s"Expected one path for all batches: 
$columnClasses")
-    columnClasses.head != classOf[OnHeapColumnVector].getName
+  private def singleArrowEvalPythonExec(plan: SparkPlan): ArrowEvalPythonExec 
= {
+    val execs = collectNodes[ArrowEvalPythonExec](plan)
+    assert(execs.length == 1, s"Expected one ArrowEvalPythonExec in 
plan:\n$plan")
+    execs.head
+  }
+
+  /** The numbers of rows of the output batches of `exec`, in order. */
+  private def outputBatchSizes(exec: ArrowEvalPythonExec): Seq[Int] = {
+    assert(exec.supportsColumnar)
+    // The evaluator is created in the tasks, which read the session 
configurations propagated.
+    SQLExecution.withSQLConfPropagated(spark) {
+      
exec.executeColumnar().mapPartitionsInternal(_.map(_.numRows())).collect().toSeq
+    }
   }
 
   private def collectNodes[T <: SparkPlan](
@@ -130,6 +136,187 @@ class ArrowColumnarPythonUDFSuite extends 
SharedSparkSession {
     }
   }
 
+  test("SPARK-60325: Arrow-backed source that reuses its vectors: correct 
results") {
+    assume(shouldTestPandasUDFs)
+    // The results of a batch come back from Python after the reader refills 
its vectors for the
+    // next batch, and closes them once it is exhausted. With columnar input, 
the pass-through
+    // columns are copied before that, 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)
+          assert(arrowExec.child.supportsColumnar == columnarInput)
+
+          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: The results of Python are sliced with columnar input") {
+    assume(shouldTestPandasUDFs)
+    // The results are joined with the pass-through columns by row, so that 
they can be sliced.
+    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")
+        val arrowExec = 
singleArrowEvalPythonExec(result.queryExecution.executedPlan)
+        assert(arrowExec.supportsColumnar)
+
+        // How the results are sliced is not visible in the output, so the 
limits of the runner
+        // are checked.
+        class LimitsRunner extends ColumnarArrowPythonWithNamedArgumentRunner(
+            Seq((ChainedPythonFunctions(Seq(arrowExec.udfs.head.func)), 0L)),
+            arrowExec.evalType, 
Array(Array.empty[EvalPythonExec.ArgumentMetadata]),
+            new StructType(), "UTC", false, Map.empty, Map.empty, None, None, 
Array.empty[Int]) {
+          def outputBatchLimits: (Int, Int) =
+            (arrowMaxRecordsPerOutputBatch, arrowMaxBytesPerOutputBatch)
+        }
+        val (maxRecords, maxBytes) = new LimitsRunner().outputBatchLimits
+        assert(maxRecords == 3 || maxBytes == 3)
+
+        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: The output batches of columnar input follow the limits of 
Arrow batches") {
+    assume(shouldTestPandasUDFs)
+    val pandasUDF = TestScalarPandasUDF(name = "arrow_limit_udf", returnType = 
Some(StringType))
+    registerTestUDF(pandasUDF, spark)
+
+    val numRows = 5000
+    def outputBatches(): (ArrowEvalPythonExec, DataFrame) = {
+      val result = readArrowSource(numRows = numRows, batchSize = 500)
+        .selectExpr("id", "name", "value", "data", "arrow_limit_udf(name) as 
udf_name")
+      (singleArrowEvalPythonExec(result.queryExecution.executedPlan), result)
+    }
+    def checkRows(result: DataFrame): Unit = {
+      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)}"))
+    }
+
+    withSQLConf(SQLConf.ARROW_EXECUTION_MAX_RECORDS_PER_BATCH.key -> "700") {
+      val (arrowExec, result) = outputBatches()
+      assert(outputBatchSizes(arrowExec) == Seq.fill(7)(700) :+ 100)
+      checkRows(result)
+    }
+
+    // No limit on the rows of a batch.
+    Seq("0", "-1").foreach { maxRecords =>
+      withSQLConf(SQLConf.ARROW_EXECUTION_MAX_RECORDS_PER_BATCH.key -> 
maxRecords) {
+        val (arrowExec, result) = outputBatches()
+        assert(outputBatchSizes(arrowExec) == Seq(numRows))
+        checkRows(result)
+      }
+    }
+
+    // Every row has more than 100 bytes, in the `data` column alone.
+    val maxBytes = 4096
+    withSQLConf(SQLConf.ARROW_EXECUTION_MAX_BYTES_PER_BATCH.key -> 
maxBytes.toString) {
+      val (arrowExec, result) = outputBatches()
+      val batchSizes = outputBatchSizes(arrowExec)
+      assert(batchSizes.sum == numRows)
+      assert(batchSizes.forall(size => size > 0 && size <= maxBytes / 100 + 
1), batchSizes)
+      checkRows(result)
+    }
+  }
+
+  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)
+
+      val numRows = 2000
+      val numBatches = 20
+      // Returns the data sent to Python for the batches of the reader, with 
and without the three
+      // batches without rows that it can also return, first, in the middle 
and last.
+      def dataSent(input: String, emptyBatches: Boolean): Long = {
+        val result = readArrowSource(numRows = numRows, batchSize = numRows / 
numBatches,
+            emptyBatches = emptyBatches)
+          .selectExpr("id", "name", "value", "data", s"arrow_empty_udf($input) 
as udf_name")
+        val arrowExec = 
singleArrowEvalPythonExec(result.queryExecution.executedPlan)
+        val numEmpty = if (emptyBatches) 3 else 0
+
+        ArrowBackedDataSourceV2.resetBatchCounters()
+        val rows = result.collect()
+        assert(rows.map(_.getInt(0)).toSeq == (0 until numRows))
+        assert(ArrowBackedDataSourceV2.returnedBatches.get == numBatches + 
numEmpty)
+        assert(ArrowBackedDataSourceV2.releasedBatches.get == numBatches + 
numEmpty)
+        arrowExec.metrics("pythonDataSent").value
+      }
+
+      // The UDF inputs are column references, or an expression on the row 
fallback path.
+      Seq("name", "concat(name, '_')").foreach { input =>
+        assert(dataSent(input, emptyBatches = true) == dataSent(input, 
emptyBatches = false))
+      }
+    }
+  }
+
+  test("SPARK-60325: Stacked Python UDFs over an Arrow-backed source") {
+    assume(shouldTestPythonUDFs && shouldTestPandasUDFs)
+    withSQLConf(SQLConf.ARROW_PYSPARK_EXECUTION_ENABLED.key -> "true") {
+      // UDFs of different eval types are not chained, so they are evaluated 
by two stacked
+      // ArrowEvalPythonExecs.
+      val innerUDF = TestPythonUDF(name = "arrow_inner_udf", returnType = 
Some(StringType),
+        pythonEvalType = PythonEvalType.SQL_ARROW_BATCHED_UDF)
+      val outerUDF = TestScalarPandasUDF(name = "arrow_outer_udf", returnType 
= Some(StringType))
+      registerTestUDF(innerUDF, spark)
+      registerTestUDF(outerUDF, spark)
+
+      val numRows = 2000
+      val result = readArrowSource(numRows = numRows, batchSize = 100)
+        .selectExpr("id", "name", "value", "data", 
"arrow_outer_udf(arrow_inner_udf(name)) as u")
+      val plan = result.queryExecution.executedPlan
+      val execs = collectNodes[ArrowEvalPythonExec](plan)
+      assert(execs.length == 2, s"Expected two ArrowEvalPythonExecs in 
plan:\n$plan")
+      val outerExec = 
execs.find(_.child.isInstanceOf[ArrowEvalPythonExec]).getOrElse(
+        fail(s"Expected stacked ArrowEvalPythonExecs in plan:\n$plan"))
+      // The results of Python are loaded into the same vectors for every 
batch, so the outer one
+      // must copy the columns that it passes through.
+      assert(outerExec.supportsColumnar && outerExec.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).length == 100, s"data mismatch for id $id")
+        assert(row.getString(4) == s"row_$id", s"UDF result mismatch for id 
$id")
+      }
+    }
+  }
+
   test("SPARK-60306: ColumnarToRow releases each batch once its rows are 
consumed") {
     Seq(true, false).foreach { codegen =>
       withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString) {
@@ -160,11 +347,10 @@ class ArrowColumnarPythonUDFSuite extends 
SharedSparkSession {
 
     val numRows = 20000
     val numBatches = 20
-    // On a string column, the cast of the test UDF is removed, so the batches 
of the Arrow-backed
-    // source take the Arrow columnar path, whose output batches carry the 
input columns to the
-    // ColumnarToRowExec above ArrowEvalPythonExec, which releases them. If 
the `id` column is not
-    // an ArrowColumnVector, they take the row queue path, and on an 
expression, the row fallback
-    // path. Both release each batch once it has been written to Python.
+    // On a string column, the cast of the test UDF is removed, so the UDF 
inputs are column
+    // references. If the `id` column is not an ArrowColumnVector, the batch 
is written to Python
+    // row by row, and on an expression, the row fallback path is taken. All 
of them release each
+    // batch once it has been written to Python.
     for {
       codegen <- Seq(true, false)
       (input, suffix, arrowIdColumn) <- Seq(
@@ -172,8 +358,8 @@ class ArrowColumnarPythonUDFSuite extends 
SharedSparkSession {
     } withSQLConf(
         SQLConf.ARROW_PYSPARK_EXECUTION_ENABLED.key -> "true",
         SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString) {
-        val result = readArrowSource(
-            numRows = numRows, batchSize = numRows / numBatches, arrowIdColumn 
= arrowIdColumn)
+        val result = readArrowSource(numRows = numRows, batchSize = numRows / 
numBatches,
+            arrowIdColumn = arrowIdColumn)
           .selectExpr("id", "name", "value", "data", 
s"arrow_release_udf($input) as udf_out")
         val plan = result.queryExecution.executedPlan
         val arrowExec = collectNodes[ArrowEvalPythonExec](plan)
@@ -182,9 +368,6 @@ class ArrowColumnarPythonUDFSuite extends 
SharedSparkSession {
           == suffix.isEmpty, s"Unexpected UDF inputs:\n$plan")
         assert(collectNodes[ColumnarToRowExec](plan).exists(
           _.find(_.isInstanceOf[ArrowEvalPythonExec]).isDefined), s"No 
ColumnarToRowExec:\n$plan")
-        val arrowColumnarPath = suffix.isEmpty && arrowIdColumn
-        assert(takesArrowColumnarPath(arrowExec.head) == arrowColumnarPath)
-
         ArrowBackedDataSourceV2.resetBatchCounters()
         val rows = result.collect()
         assert(rows.map(_.getInt(0)).toSeq == (0 until numRows))
@@ -195,18 +378,18 @@ class ArrowColumnarPythonUDFSuite extends 
SharedSparkSession {
           assert(row.getString(3).length == 100, s"data mismatch for id $id")
           assert(row.getString(4) == s"row_$id$suffix", s"UDF result mismatch 
for id $id")
         }
-        // Every batch is released before the task completes. The row queue 
and row fallback
-        // paths release a batch before they read the next one, while the 
Arrow columnar path
-        // holds the batches that it has written to Python until their results 
are consumed.
+        // A batch is released before the next one is read.
         assert(ArrowBackedDataSourceV2.returnedBatches.get == numBatches)
         assert(ArrowBackedDataSourceV2.releasedBatches.get == numBatches)
-        if (!arrowColumnarPath) {
-          assert(ArrowBackedDataSourceV2.maxUnreleasedBatches.get == 1)
-        }
+        assert(ArrowBackedDataSourceV2.maxUnreleasedBatches.get == 1)
 
-        // 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)
+        // A limit stops consuming the output batches early, possibly before 
the input batches
+        // that have been read are all released: the source closes them when 
the task completes,
+        // and closing its allocator then fails the task if any of their 
buffers is referenced.
+        val limited = result.limit(10)
+        
assert(collectNodes[ArrowEvalPythonExec](limited.queryExecution.executedPlan).nonEmpty)
+        assert(limited.collect().map(_.getString(4)).toSeq ==
+          (0 until 10).map(id => s"row_$id$suffix"))
       }
   }
 
@@ -233,43 +416,6 @@ class ArrowColumnarPythonUDFSuite extends 
SharedSparkSession {
     }
   }
 
-  test("Arrow-backed source that reuses its vectors: correct with the default 
configuration") {
-    assume(shouldTestPandasUDFs)
-    // The Arrow columnar path keeps the pass-through columns of a batch until 
its result comes
-    // back from Python, which is only correct if the batch stays valid until 
then. A reader may
-    // refill its vectors for the next batch, or release them once it is 
closed, as soon as it is
-    // exhausted, so columnar input is disabled by default.
-    withSQLConf(
-        SQLConf.ARROW_PYSPARK_EXECUTION_ENABLED.key -> "true",
-        SQLConf.ARROW_PYSPARK_UDF_COLUMNAR_INPUT_ENABLED.key ->
-          SQLConf.ARROW_PYSPARK_UDF_COLUMNAR_INPUT_ENABLED.defaultValueString) 
{
-      val pandasUDF = TestScalarPandasUDF(
-        name = "arrow_reuse_udf", returnType = Some(StringType))
-      registerTestUDF(pandasUDF, spark)
-
-      // Spark writes batches to Python before the results of the earlier ones 
come back. With
-      // two batches, the reader is closed once it is exhausted, before their 
results come back.
-      // With many, the reader 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 that the
-      // batches would take the Arrow columnar path if columnar input were 
enabled.
-      Seq(200, 200000).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 = 
collectNodes[ArrowEvalPythonExec](result.queryExecution.executedPlan)
-        assert(arrowExec.nonEmpty && !arrowExec.head.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("Arrow-backed source: multiple UDF columns") {
     assume(shouldTestPandasUDFs)
     withSQLConf(SQLConf.ARROW_PYSPARK_EXECUTION_ENABLED.key -> "true") {
@@ -346,3 +492,9 @@ class ArrowColumnarPythonUDFSuite extends 
SharedSparkSession {
     }
   }
 }
+
+/** Runs the tests of [[ArrowColumnarPythonUDFSuite]] with pipelined Python 
UDF execution. */
+class ArrowColumnarPythonUDFPipelinedSuite extends ArrowColumnarPythonUDFSuite 
{
+  override protected def sparkConf: SparkConf =
+    super.sparkConf.set(PYTHON_UDF_PIPELINED_EXECUTION.key, "true")
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to