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

zhouyuan pushed a commit to branch branch-1.8
in repository https://gitbox.apache.org/repos/asf/gluten.git

commit ceca5b1feee4ebc017e5a5e9cf6c56861cdf1006
Author: YangJie <[email protected]>
AuthorDate: Sun Nov 22 16:47:22 2026 -0500

    [GLUTEN-13706][VL] Fix pandas UDFs on partitions with more than one batch 
(#13707)
---
 .../api/python/ColumnarArrowEvalPythonExec.scala   | 102 ++++++++++++------
 .../python/ArrowEvalPythonExecSuite.scala          |  17 +++
 .../python/ColumnarArrowEvalPythonExecSuite.scala  | 116 +++++++++++++++++++++
 3 files changed, 205 insertions(+), 30 deletions(-)

diff --git 
a/backends-velox/src/main/scala/org/apache/spark/api/python/ColumnarArrowEvalPythonExec.scala
 
b/backends-velox/src/main/scala/org/apache/spark/api/python/ColumnarArrowEvalPythonExec.scala
index 005c464d67..648f32b0c3 100644
--- 
a/backends-velox/src/main/scala/org/apache/spark/api/python/ColumnarArrowEvalPythonExec.scala
+++ 
b/backends-velox/src/main/scala/org/apache/spark/api/python/ColumnarArrowEvalPythonExec.scala
@@ -44,6 +44,7 @@ import java.io.{DataInputStream, DataOutputStream}
 import java.util.concurrent.atomic.AtomicBoolean
 
 import scala.annotation.nowarn
+import scala.collection.JavaConverters._
 import scala.collection.mutable
 import scala.collection.mutable.ArrayBuffer
 import scala.util.control.NonFatal
@@ -92,10 +93,15 @@ class ColumnarArrowPythonRunner(
       private var reader: ArrowStreamReader = _
       private var root: VectorSchemaRoot = _
       private var schema: StructType = _
-      private var vectors: Array[ColumnVector] = _
+      // The last batch read but not returned by next() yet, e.g. one that 
hasNext() read ahead.
+      private var unclaimed: ColumnarBatch = _
 
       context.addTaskCompletionListener[Unit] {
         _ =>
+          if (unclaimed != null) {
+            unclaimed.close()
+            unclaimed = null
+          }
           if (reader != null) {
             reader.close(false)
           }
@@ -106,6 +112,12 @@ class ColumnarArrowPythonRunner(
 
       private var batchLoaded = true
 
+      override def next(): ColumnarBatch = {
+        val batch = super.next()
+        unclaimed = null
+        batch
+      }
+
       override protected def read(): ColumnarBatch = {
         if (writer.exception.isDefined) {
           throw writer.exception.get
@@ -114,9 +126,14 @@ class ColumnarArrowPythonRunner(
           if (reader != null && batchLoaded) {
             batchLoaded = reader.loadNextBatch()
             if (batchLoaded) {
-              val batch = new ColumnarBatch(vectors)
-              batch.setNumRows(root.getRowCount)
-              batch
+              // The reader loads every batch into the vectors of `root`. Move 
the buffers to new
+              // vectors, so that each batch owns its data and closing it 
frees only that batch.
+              val numRows = root.getRowCount
+              val vectors = 
root.getFieldVectors.asScala.map(ArrowColumnVectors.adopt(_, allocator))
+              unclaimed = new ColumnarBatch(
+                ArrowColumnVectors.wrap(vectors.asJava).toArray[ColumnVector],
+                numRows)
+              unclaimed
             } else {
               reader.close(false)
               // Reach end of stream. Call `read()` again to read control data.
@@ -128,9 +145,6 @@ class ColumnarArrowPythonRunner(
                 reader = new ArrowStreamReader(stream, allocator)
                 root = reader.getVectorSchemaRoot()
                 schema = SparkArrowUtil.fromArrowSchema(root.getSchema())
-                vectors = ArrowColumnVectors
-                  .wrap(root.getFieldVectors)
-                  .toArray[ColumnVector]
                 read()
               case SpecialLengths.TIMING_DATA =>
                 handleTimingData()
@@ -317,6 +331,11 @@ case class ColumnarArrowEvalPythonExec(
   override def rowType(): Convention.RowType = Convention.RowType.None
 
   override protected def doValidateInternal(): ValidationResult = {
+    if (!ColumnarArrowEvalPythonExec.supportedEvalTypes.contains(evalType)) {
+      // The output batches are joined with the input batches one by one, but 
an iterator UDF
+      // may return its rows in batches of other sizes than its input.
+      return ValidationResult.failed(s"Python eval type $evalType is not 
supported")
+    }
     val (_, inputs) = 
udfs.map(ColumnarArrowEvalPythonExec.collectFunctions).unzip
     inputs.foreach {
       input =>
@@ -377,12 +396,19 @@ case class ColumnarArrowEvalPythonExec(
 
     columnarBatchIter.map {
       batch =>
-        val actualDataTypes = (0 until batch.numCols()).map(i => 
batch.column(i).dataType())
-        assert(
-          outputTypes == actualDataTypes,
-          "Invalid schema from arrow_udf: " +
-            s"expected ${outputTypes.mkString(", ")}, got 
${actualDataTypes.mkString(", ")}")
-        batch
+        try {
+          val actualDataTypes = (0 until batch.numCols()).map(i => 
batch.column(i).dataType())
+          assert(
+            outputTypes == actualDataTypes,
+            "Invalid schema from arrow_udf: " +
+              s"expected ${outputTypes.mkString(", ")}, got 
${actualDataTypes.mkString(", ")}")
+          batch
+        } catch {
+          case NonFatal(e) =>
+            // The batch hasn't reached its consumer, which would close it.
+            batch.close()
+            throw e
+        }
     }
   }
 
@@ -475,23 +501,35 @@ case class ColumnarArrowEvalPythonExec(
         val res =
           outputColumnarBatchIterator.zipWithIndex.map {
             case (outputCb, batchId) =>
-              val inputCb = inputCbCache(batchId)
-              val joinedVectors = (0 until inputCb.numCols).toArray.map(
-                i => inputCb.column(i)) ++ (0 until 
outputCb.numCols).toArray.map(
-                i => outputCb.column(i))
-              // Columns in outputCb has random 0 or 1 refCnt and will fail 
checks in ensureOffload,
-              // so we do a hard reset here.
-              (0 until joinedVectors.length).foreach(
-                i => {
-                  
adjustRefCnt(joinedVectors(i).asInstanceOf[RefCountedArrowColumnVector], 1)
-                })
-              val numRows = inputCb.numRows
-              numOutputBatches += 1
-              numOutputRows += numRows
-              val batch = new ColumnarBatch(joinedVectors, numRows)
-              ColumnarBatches.checkLoaded(batch)
-              procTime += (System.nanoTime() - start_time) / 1000000
-              batch
+              try {
+                val inputCb = inputCbCache(batchId)
+                require(
+                  outputCb.numRows == inputCb.numRows,
+                  s"Python UDF returned ${outputCb.numRows} rows for an input 
batch of " +
+                    s"${inputCb.numRows} rows")
+                val joinedVectors = (0 until inputCb.numCols).toArray.map(
+                  i => inputCb.column(i)) ++ (0 until 
outputCb.numCols).toArray.map(
+                  i => outputCb.column(i))
+                // The input columns hold the reference taken for inputCbCache 
and may still hold
+                // the producer's, so their count is 1 or 2. Offloading 
requires the same reference
+                // count on every column, so we do a hard reset here.
+                (0 until joinedVectors.length).foreach(
+                  i => {
+                    
adjustRefCnt(joinedVectors(i).asInstanceOf[RefCountedArrowColumnVector], 1)
+                  })
+                val numRows = inputCb.numRows
+                numOutputBatches += 1
+                numOutputRows += numRows
+                val batch = new ColumnarBatch(joinedVectors, numRows)
+                ColumnarBatches.checkLoaded(batch)
+                procTime += (System.nanoTime() - start_time) / 1000000
+                batch
+              } catch {
+                case NonFatal(e) =>
+                  // The output batch hasn't reached its consumer, which would 
close it.
+                  outputCb.close()
+                  throw e
+              }
           }
         Iterators
           .wrap(res)
@@ -526,6 +564,10 @@ case class ColumnarArrowEvalPythonExec(
 
 object ColumnarArrowEvalPythonExec {
 
+  // SQL_ARROW_BATCHED_UDF, SQL_SCALAR_PANDAS_UDF and SQL_SCALAR_ARROW_UDF, as 
numbers because
+  // older Spark profiles don't define all of them. Scalar iterator UDFs (204, 
251) fall back.
+  private val supportedEvalTypes = Set(101, 200, 250)
+
   def collectFunctions(udf: PythonUDF): ((ChainedPythonFunctions, Long), 
Seq[Expression]) = {
     udf.children match {
       case Seq(u: PythonUDF) =>
diff --git 
a/backends-velox/src/test/scala/org/apache/gluten/execution/python/ArrowEvalPythonExecSuite.scala
 
b/backends-velox/src/test/scala/org/apache/gluten/execution/python/ArrowEvalPythonExecSuite.scala
index 681ca75bcb..1a06be2111 100644
--- 
a/backends-velox/src/test/scala/org/apache/gluten/execution/python/ArrowEvalPythonExecSuite.scala
+++ 
b/backends-velox/src/test/scala/org/apache/gluten/execution/python/ArrowEvalPythonExecSuite.scala
@@ -166,6 +166,23 @@ class ArrowEvalPythonExecSuite extends 
WholeStageTransformerSuite {
     }
   }
 
+  test("arrow_udf test: several batches in one partition") {
+    withSQLConf(GlutenConfig.COLUMNAR_MAX_BATCH_SIZE.key -> "16") {
+      withTempPath {
+        f =>
+          (0 until 100).map(i => (i.toLong, s"v$i")).toDF("id", 
"s").coalesce(1).write.parquet(
+            f.getCanonicalPath)
+          val base = spark.read.parquet(f.getCanonicalPath)
+          assert(base.rdd.getNumPartitions == 1)
+          val df = base.withColumn("p_s", pyarrowTestUDFString(base("s")))
+          checkAnswer(df, (0 until 100).map(i => Row(i.toLong, s"v$i", 
s"v$i")))
+          val udfs = getExecutedPlan(df).collect { case p: 
ColumnarArrowEvalPythonExec => p }
+          assert(udfs.size == 1)
+          assert(udfs.head.metrics("numOutputBatches").value > 1)
+      }
+    }
+  }
+
   private def newTestArrowBatchedPythonUDF(
       name: String,
       returnType: Option[DataType] = None): UserDefinedPythonFunction = {
diff --git 
a/backends-velox/src/test/scala/org/apache/spark/sql/execution/python/ColumnarArrowEvalPythonExecSuite.scala
 
b/backends-velox/src/test/scala/org/apache/spark/sql/execution/python/ColumnarArrowEvalPythonExecSuite.scala
new file mode 100644
index 0000000000..289ca4a0cb
--- /dev/null
+++ 
b/backends-velox/src/test/scala/org/apache/spark/sql/execution/python/ColumnarArrowEvalPythonExecSuite.scala
@@ -0,0 +1,116 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.execution.python
+
+import org.apache.gluten.config.GlutenConfig
+import org.apache.gluten.execution.WholeStageTransformerSuite
+
+import org.apache.spark.api.python.{ColumnarArrowEvalPythonExec, 
PythonBroadcast, PythonEvalType, PythonUtils, SimplePythonFunction}
+import org.apache.spark.broadcast.Broadcast
+import org.apache.spark.sql.{IntegratedUDFTestUtils, Row}
+import org.apache.spark.sql.types.LongType
+
+import java.nio.file.Paths
+import java.util.Base64
+
+import scala.sys.process.Process
+
+// Under org.apache.spark because PythonEvalType and SimplePythonFunction are 
private[spark].
+class ColumnarArrowEvalPythonExecSuite extends WholeStageTransformerSuite {
+
+  import IntegratedUDFTestUtils.{pythonExec, pythonVer}
+  import testImplicits._
+
+  override protected val resourcePath: String = "/tpch-data-parquet"
+  override protected val fileFormat: String = "parquet"
+
+  test("scalar iterator UDFs fall back") {
+    val child = spark.range(1).queryExecution.sparkPlan
+    val exec =
+      ColumnarArrowEvalPythonExec(Nil, Nil, child, 
PythonEvalType.SQL_SCALAR_PANDAS_ITER_UDF)
+    assert(!exec.doValidate().ok())
+    assert(exec.copy(evalType = 
PythonEvalType.SQL_SCALAR_PANDAS_UDF).doValidate().ok())
+  }
+
+  private lazy val pysparkPath = {
+    val python = Paths.get(sparkHome, "python").toAbsolutePath
+    s"${python.resolve("lib").resolve(PythonUtils.PY4J_ZIP_NAME)}:$python"
+  }
+
+  /** A scalar iterator pandas UDF whose function `f(iterator)` has the given 
body. */
+  private def iteratorUdf(name: String, body: String): 
UserDefinedPythonFunction = {
+    val code =
+      s"""import base64
+         |import pandas as pd
+         |from pyspark.serializers import CloudPickleSerializer
+         |from pyspark.sql.types import LongType
+         |def f(iterator):
+         |$body
+         |print(base64.b64encode(CloudPickleSerializer().dumps((f, 
LongType()))).decode())
+         |""".stripMargin
+    val command = Base64.getDecoder.decode(
+      Process(Seq(pythonExec, "-c", code), None, "PYTHONPATH" -> 
pysparkPath).!!.trim)
+    val env = new java.util.HashMap[String, String]()
+    env.put("PYTHONPATH", pysparkPath)
+    new UserDefinedPythonFunction(
+      name,
+      new SimplePythonFunction(
+        command,
+        env,
+        new java.util.ArrayList[String](),
+        pythonExec,
+        pythonVer,
+        new java.util.ArrayList[Broadcast[PythonBroadcast]](),
+        null),
+      LongType,
+      PythonEvalType.SQL_SCALAR_PANDAS_ITER_UDF,
+      udfDeterministic = true
+    )
+  }
+
+  Seq(
+    "merges" ->
+      """    batches = list(iterator)
+        |    if batches:
+        |        yield pd.concat(batches, ignore_index=True)""".stripMargin,
+    "splits" ->
+      """    for batch in iterator:
+        |        for i in range(len(batch)):
+        |            yield batch.iloc[i:i + 1]""".stripMargin
+  ).foreach {
+    case (name, body) =>
+      test(s"scalar iterator UDF that $name batches returns every row") {
+        withSQLConf(
+          GlutenConfig.COLUMNAR_MAX_BATCH_SIZE.key -> "2",
+          // Spark 4.2's columnar input path also joins the UDF output with 
its input batch by
+          // batch, so it fails these UDFs. The key is unknown, and ignored, 
before Spark 4.2.
+          "spark.sql.execution.arrow.pythonUDF.columnarInput.enabled" -> 
"false"
+        ) {
+          withTempPath {
+            path =>
+              (1L to 
8L).toDF("id").coalesce(1).write.parquet(path.getCanonicalPath)
+              val input = spark.read.parquet(path.getCanonicalPath)
+              val df = input.withColumn("copied", iteratorUdf(name, 
body)(input("id")))
+              checkAnswer(df, (1L to 8L).map(i => Row(i, i)))
+              val plan = getExecutedPlan(df)
+              assert(!plan.exists(_.isInstanceOf[ColumnarArrowEvalPythonExec]))
+              assert(plan.exists(_.isInstanceOf[ArrowEvalPythonExec]))
+          }
+        }
+      }
+  }
+}


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

Reply via email to