This is an automated email from the ASF dual-hosted git repository.

viirya pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.2 by this push:
     new c9cb0e9afdd8 [SPARK-60294][4.2][SQL] Disable Arrow-backed columnar 
input to Python UDFs by default
c9cb0e9afdd8 is described below

commit c9cb0e9afdd8c45eb6d75e4b3bb6b02a3b9c3446
Author: Liang-Chi Hsieh <[email protected]>
AuthorDate: Tue Nov 10 18:51:39 2026 -0800

    [SPARK-60294][4.2][SQL] Disable Arrow-backed columnar input to Python UDFs 
by default
    
    ### What changes were proposed in this pull request?
    
    This PR backports #59551 (SPARK-60294) to branch-4.2.
    
    It disables `spark.sql.execution.arrow.pythonUDF.columnarInput.enabled` by 
default, and makes `ArrowEvalPythonExec.doExecute` check it too, through 
`supportsColumnar`, so that a child that also returns rows returns rows when 
columnar input is disabled. It also adds the `reuseVectors` and `batchSize` 
options to the test source `ArrowBackedDataSourceV2`.
    
    Differences from the original change, since branch-4.2 has no Arrow cache 
(`ArrowCachedBatchSerializer`):
    - `ArrowCachedPythonUDFSuite` and the change to 
`python/pyspark/sql/tests/arrow/test_arrow_python_udf_cached.py` are left out, 
as both test the Arrow cache.
    - The comment in `ArrowEvalPythonExec.doExecute` names an in-memory table 
scan instead of the scan of the Arrow cache as the example of a child that also 
returns rows.
    - The migration guide entry goes into the existing "Upgrading from Spark 
SQL 4.2.1 to 4.2.2" section, since 4.2.1 was released without this change, and 
does not mention the Arrow cache. The 4.3-to-4.4 entry is left out.
    
    ### Why are the changes needed?
    
    branch-4.2 still enables columnar input by default. With it enabled, the 
Arrow columnar path of `ColumnarArrowEvalPythonEvaluatorFactory` keeps the 
pass-through `ColumnVector`s of each input batch until the Python result of 
that batch comes back, which can be many batches later. A columnar reader may 
refill or release those vectors once it is asked for the next batch, so a 
scalar pandas or Arrow UDF on a column of such a source fails with 
`IndexOutOfBoundsException: index: 0, length:  [...]
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. By default, Python UDFs on the columns of an Arrow-backed source no 
longer fail or return wrong results: Spark converts the batches to rows before 
the UDFs, as in Spark 4.1. Setting 
`spark.sql.execution.arrow.pythonUDF.columnarInput.enabled` to `true` enables 
columnar input again. The migration guide says so for 4.2.2.
    
    ### How was this patch tested?
    
    The new test of the original change in `ArrowColumnarPythonUDFSuite` passes 
on branch-4.2 with JDK 17, as do the other tests of the suite, `sql/scalastyle` 
and `sql/Test/scalastyle`.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (Claude Opus 5.5)
    
    This pull request and its description were written by Isaac.
    
    Closes #60277 from viirya/SPARK-60294-4.2.
    
    Lead-authored-by: Liang-Chi Hsieh <[email protected]>
    Co-authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Liang-Chi Hsieh <[email protected]>
---
 docs/sql-migration-guide.md                        |  1 +
 .../org/apache/spark/sql/internal/SQLConf.scala    |  7 +-
 .../sql/execution/python/ArrowEvalPythonExec.scala |  5 +-
 .../ColumnarArrowEvalPythonEvaluatorFactory.scala  | 16 +++--
 .../execution/python/ArrowBackedDataSourceV2.scala | 74 ++++++++++++++++++++--
 .../python/ArrowColumnarPythonUDFSuite.scala       | 50 ++++++++++++++-
 6 files changed, 136 insertions(+), 17 deletions(-)

diff --git a/docs/sql-migration-guide.md b/docs/sql-migration-guide.md
index cc43967caaf1..a8381d0466c2 100644
--- a/docs/sql-migration-guide.md
+++ b/docs/sql-migration-guide.md
@@ -25,6 +25,7 @@ license: |
 ## Upgrading from Spark SQL 4.2.1 to 4.2.2
 
 - Since Spark 4.2.2, Data Source V2 file scans correctly evaluate 
deterministic Python UDF filter predicates that reference only partition 
columns. Previously, these predicates could be dropped, returning rows that did 
not satisfy the filter (SPARK-60486). Data derived from affected query results 
may need to be recomputed.
+- Since Spark 4.2.2, 
`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, as in Spark 4.1. 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 enable columnar 
input aga [...]
 
 ## Upgrading from Spark SQL 4.2.0 to 4.2.1
 
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 53b96da3bd27..ec9d9fb4bf36 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
@@ -4696,11 +4696,14 @@ object SQLConf {
         "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.")
+        "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.")
       .version("4.2.0")
       .withBindingPolicy(ConfigBindingPolicy.SESSION)
       .booleanConf
-      .createWithDefault(true)
+      .createWithDefault(false)
 
   val ARROW_TRANSFORM_WITH_STATE_IN_PYSPARK_MAX_STATE_RECORDS_PER_BATCH =
     
buildConf("spark.sql.execution.arrow.transformWithStateInPySpark.maxStateRecordsPerBatch")
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 4a09898a58c7..0f939e9bd2ad 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
@@ -100,7 +100,10 @@ case class ArrowEvalPythonExec(
   override def supportsRowBased: Boolean = true
 
   override protected def doExecute(): RDD[InternalRow] = {
-    if (child.supportsColumnar) {
+    // Checks the configuration too, through `supportsColumnar`: a child that 
also returns rows,
+    // such as an in-memory table scan, gets no ColumnarToRowExec when 
columnar input is
+    // disabled, and still supports columnar.
+    if (supportsColumnar) {
       // Columnar path: delegate to doExecuteColumnar, flatten to
       // UnsafeRow. ColumnarBatchRow from rowIterator() is NOT
       // UnsafeRow, and downstream operators (e.g., outer
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 4e699f975fec..99269d7451ab 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
@@ -44,9 +44,12 @@ import org.apache.spark.util.Utils
  * 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 (safe because Arrow vectors are
- *    independently allocated per batch). Output is produced by columnar
- *    combining: passThruCols ++ resultCols -> ColumnarBatch.
+ *    [[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.
  *
  * 2. '''Non-Arrow columnar path''' (UDF inputs are simple column refs
  *    BUT columns are NOT [[ArrowColumnVector]]): Non-Arrow columnar
@@ -174,9 +177,10 @@ private[python] class 
ColumnarArrowEvalPythonEvaluatorFactory(
     }
 
     /**
-     * Path 1: Arrow columnar. ColumnVector references are safe
-     * because Arrow vectors are independently allocated per batch.
-     * Combines pass-through + UDF result columns into ColumnarBatch.
+     * 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],
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 992182871ac9..da6a423a39bc 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
@@ -16,8 +16,11 @@
  */
 package org.apache.spark.sql.execution.python
 
+import java.nio.charset.StandardCharsets.UTF_8
 import java.util
 
+import scala.jdk.CollectionConverters._
+
 import org.apache.arrow.memory.BufferAllocator
 import org.apache.arrow.vector._
 
@@ -119,9 +122,13 @@ private class ArrowBackedScanBuilder(options: 
CaseInsensitiveStringMap)
 
   private val columnar =
     options.getBoolean("columnar", true)
+  private val reuseVectors =
+    options.getBoolean("reuseVectors", false)
+  private val batchSize =
+    options.getInt("batchSize", ArrowBackedDataSourceV2.BATCH_SIZE)
 
   override def createReaderFactory(): PartitionReaderFactory = {
-    new ArrowBackedReaderFactory(columnar)
+    new ArrowBackedReaderFactory(columnar, reuseVectors, batchSize)
   }
 }
 
@@ -137,8 +144,11 @@ private case class ArrowPartition(start: Int, end: Int)
  *   This allows benchmarking the same data source with and without
  *   the columnar optimization.
  */
-private class ArrowBackedReaderFactory(columnar: Boolean)
-    extends PartitionReaderFactory {
+private class ArrowBackedReaderFactory(
+    columnar: Boolean,
+    reuseVectors: Boolean,
+    batchSize: Int)
+  extends PartitionReaderFactory {
 
   override def supportColumnarReads(
       partition: InputPartition): Boolean = columnar
@@ -146,7 +156,7 @@ private class ArrowBackedReaderFactory(columnar: Boolean)
   override def createReader(
       partition: InputPartition): PartitionReader[InternalRow] = {
     val ArrowPartition(start, end) = partition
-    val inner = new ArrowBackedPartitionReader(start, end)
+    val inner = new ArrowBackedPartitionReader(start, end, batchSize)
     // Wrap columnar reader as row reader.
     new PartitionReader[InternalRow] {
       private var rowIter: java.util.Iterator[InternalRow] = _
@@ -164,7 +174,58 @@ private class ArrowBackedReaderFactory(columnar: Boolean)
   override def createColumnarReader(
       partition: InputPartition): PartitionReader[ColumnarBatch] = {
     val ArrowPartition(start, end) = partition
-    new ArrowBackedPartitionReader(start, end)
+    if (reuseVectors) {
+      new ReusingArrowPartitionReader(start, end, batchSize)
+    } else {
+      new ArrowBackedPartitionReader(start, end, batchSize)
+    }
+  }
+}
+
+/**
+ * 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.
+ */
+private class ReusingArrowPartitionReader(start: Int, end: Int, batchSize: Int)
+    extends PartitionReader[ColumnarBatch] {
+  private var current = start
+  private val allocator = ArrowUtils.rootAllocator.newChildAllocator(
+    s"reusing-arrow-test-reader-$start", 0, Long.MaxValue)
+  private val root = VectorSchemaRoot.create(
+    ArrowUtils.toArrowSchema(ArrowBackedDataSourceV2.SCHEMA, null,
+      errorOnDuplicatedFieldNames = true, largeVarTypes = false),
+    allocator)
+  private val batch = new ColumnarBatch(
+    root.getFieldVectors.asScala.map(new ArrowColumnVector(_): 
ColumnVector).toArray)
+
+  override def next(): Boolean = {
+    if (current >= end) return false
+    val count = math.min(batchSize, end - current)
+    val id = root.getVector("id").asInstanceOf[IntVector]
+    val name = root.getVector("name").asInstanceOf[VarCharVector]
+    val value = root.getVector("value").asInstanceOf[Float8Vector]
+    val data = root.getVector("data").asInstanceOf[VarCharVector]
+    // Overwrites the values of the previous batch in place.
+    root.getFieldVectors.forEach(_.reset())
+    (0 until count).foreach { i =>
+      val row = current + i
+      id.setSafe(i, row)
+      name.setSafe(i, s"row_$row".getBytes(UTF_8))
+      value.setSafe(i, row * 0.1)
+      data.setSafe(i, s"data_$row".getBytes(UTF_8))
+    }
+    root.setRowCount(count)
+    batch.setNumRows(count)
+    current += count
+    true
+  }
+
+  override def get(): ColumnarBatch = batch
+
+  override def close(): Unit = {
+    root.close()
+    allocator.close()
   }
 }
 
@@ -176,10 +237,9 @@ private class ArrowBackedReaderFactory(columnar: Boolean)
  * - name (STRING): "row_<id>"
  * - value (DOUBLE): id * 0.1
  */
-private class ArrowBackedPartitionReader(start: Int, end: Int)
+private class ArrowBackedPartitionReader(start: Int, end: Int, batchSize: Int)
     extends PartitionReader[ColumnarBatch] {
 
-  private val batchSize = ArrowBackedDataSourceV2.BATCH_SIZE
   private var current = start
   private var currentBatch: ColumnarBatch = _
 
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 faf8c77678f3..06f162a237c7 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
@@ -17,6 +17,7 @@
 
 package org.apache.spark.sql.execution.python
 
+import org.apache.spark.SparkConf
 import org.apache.spark.sql.IntegratedUDFTestUtils
 import org.apache.spark.sql.execution.SparkPlan
 import org.apache.spark.sql.internal.SQLConf
@@ -34,14 +35,24 @@ class ArrowColumnarPythonUDFSuite extends 
SharedSparkSession {
 
   import IntegratedUDFTestUtils._
 
+  // The tests of the columnar input path enable it, since it is disabled by 
default.
+  override protected def sparkConf: SparkConf =
+    super.sparkConf.set(SQLConf.ARROW_PYSPARK_UDF_COLUMNAR_INPUT_ENABLED.key, 
"true")
+
   private val arrowSource =
     "org.apache.spark.sql.execution.python.ArrowBackedDataSourceV2"
 
-  private def readArrowSource(numRows: Int = 100, numPartitions: Int = 1) = {
+  private def readArrowSource(
+      numRows: Int = 100,
+      numPartitions: Int = 1,
+      reuseVectors: Boolean = false,
+      batchSize: Int = ArrowBackedDataSourceV2.BATCH_SIZE) = {
     spark.read
       .format(arrowSource)
       .option("numRows", numRows.toString)
       .option("numPartitions", numPartitions.toString)
+      .option("reuseVectors", reuseVectors.toString)
+      .option("batchSize", batchSize.toString)
       .load()
   }
 
@@ -103,6 +114,43 @@ 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") {


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

Reply via email to