You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by yi...@apache.org on 2026/10/14 07:34:01 UTC

(spark) branch master updated: [SPARK-60219][PYTHON] Migrate SQL_ARROW_BATCHED_UDF to the EvalTypeHandler pipeline

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

Yicong-Huang pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/master by this push:
     new 19ce8f5dec25 [SPARK-60219][PYTHON] Migrate SQL_ARROW_BATCHED_UDF to the EvalTypeHandler pipeline
19ce8f5dec25 is described below

commit 19ce8f5dec257eeac63bdaa69001041aa4b0165a
Author: Yicong Huang <17...@users.noreply.github.com>
AuthorDate: Wed Oct 14 07:33:48 2026 +0000

    [SPARK-60219][PYTHON] Migrate SQL_ARROW_BATCHED_UDF to the EvalTypeHandler pipeline
    
    ### What changes were proposed in this pull request?
    Move `SQL_ARROW_BATCHED_UDF` (Arrow-optimized `udf`) from `read_udfs` onto the `EvalTypeHandler` pipeline as two handlers, selected by `use_legacy_pandas_udf_conversion` through the variant registry:
    
    - `ArrowBatchedUDFArrowHandler` (`_arrow.py`, `False`): the Arrow conversion path.
    - `ArrowBatchedUDFLegacyPandasHandler` (`_pandas.py`, `True`): the legacy pandas conversion path.
    
    Each branch body moves into its handler unchanged. `read_udfs` drops both branches and removes `SQL_ARROW_BATCHED_UDF` from its serializer selection.
    
    ```
    BatchEvalTypeHandler
    ├─ ArrowBatchedUDFArrowHandler           SQL_ARROW_BATCHED_UDF, legacy pandas conversion = False
    └─ ArrowBatchedUDFLegacyPandasHandler    SQL_ARROW_BATCHED_UDF, legacy pandas conversion = True
    ```
    
    ### Why are the changes needed?
    Part of SPARK-59415: run all Arrow/pandas UDF eval types through one handler dispatch path.
    
    ### Does this PR introduce _any_ user-facing change?
    No.
    
    ### How was this patch tested?
    - New handler unit tests for both variants in `test_arrow_eval_type_handlers.py` / `test_pandas_eval_type_handlers.py`.
    - `test_arrow_python_udf.py` (default, legacy and non-legacy suites) and `test_arrow_python_udf_cached.py` pass locally.
    - `bench_eval_type.py` `_ArrowBatchedBenchMixin` scenarios, 7 runs each, median +- stdev:
    
    | conversion | scenario | udf | before | after |
    |---|---|---|---|---|
    | arrow | sm_batch_many_col | identity | 71.5 +- 0.3 ms | 71.2 +- 0.1 ms |
    | arrow | lg_batch_few_col | stringify | 73.8 +- 0.3 ms | 74.1 +- 0.7 ms |
    | arrow | pure_strings | identity | 183.3 +- 7.8 ms | 182.8 +- 1.2 ms |
    | arrow | mixed_types | stringify | 148.8 +- 1.8 ms | 146.6 +- 0.3 ms |
    | legacy | sm_batch_many_col | identity | 14.2 +- 0.1 ms | 14.4 +- 0.1 ms |
    | legacy | lg_batch_few_col | stringify | 16.8 +- 0.0 ms | 17.1 +- 0.1 ms |
    | legacy | pure_strings | identity | 39.6 +- 3.0 ms | 39.9 +- 0.3 ms |
    | legacy | mixed_types | stringify | 30.1 +- 0.0 ms | 30.5 +- 5.2 ms |
    
    ### Was this patch authored or co-authored using generative AI tooling?
    Generated-by: Opus 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #59433 from Yicong-Huang/arrow-batched-udf-variants.
    
    Authored-by: Yicong Huang <17...@users.noreply.github.com>
    Signed-off-by: Yicong-Huang <17...@users.noreply.github.com>
---
 python/pyspark/eval_handlers/_arrow.py             | 120 ++++++++++++-
 python/pyspark/eval_handlers/_pandas.py            | 110 +++++++++++-
 .../tests/test_arrow_eval_type_handlers.py         |  89 +++++++++-
 .../tests/test_pandas_eval_type_handlers.py        |  76 +++++++-
 python/pyspark/worker.py                           | 192 +--------------------
 5 files changed, 391 insertions(+), 196 deletions(-)

diff --git a/python/pyspark/eval_handlers/_arrow.py b/python/pyspark/eval_handlers/_arrow.py
index 2f2ccd93a55f..47eed960672b 100644
--- a/python/pyspark/eval_handlers/_arrow.py
+++ b/python/pyspark/eval_handlers/_arrow.py
@@ -31,25 +31,35 @@ import itertools
 from collections.abc import Iterator
 from typing import TYPE_CHECKING, Any
 
+from pyspark import _NoValue
 from pyspark.errors import PySparkRuntimeError
 from pyspark.eval_handlers._base import (
     BatchEvalTypeHandler,
     CoGroupedEvalTypeHandler,
     GroupedEvalTypeHandler,
 )
-from pyspark.eval_handlers.utils import extract_key_value_indexes, hashable_grouping_key
+from pyspark.eval_handlers.utils import (
+    extract_key_value_indexes,
+    hashable_grouping_key,
+    wrap_kwargs_support,
+)
 from pyspark.eval_handlers.verification import (
     verify_iter_result_row_count,
     verify_iterator_exhausted,
     verify_output_row_limit,
+    verify_result_row_count,
     verify_return_type,
     verify_scalar_result,
 )
-from pyspark.sql.conversion import ArrowBatchTransformer
+from pyspark.sql.conversion import (
+    ArrowBatchTransformer,
+    ArrowTableToRowsConversion,
+    LocalDataToArrowConversion,
+)
 from pyspark.sql.pandas.types import to_arrow_schema, to_arrow_type
 from pyspark.sql.pandas.utils import require_minimum_pyarrow_version
 from pyspark.sql.types import StructField, StructType
-from pyspark.util import PythonEvalType
+from pyspark.util import PythonEvalType, fail_on_stopiteration
 
 if TYPE_CHECKING:
     import pyarrow as pa
@@ -801,3 +811,107 @@ class ArrowScalarUDFHandler(BatchEvalTypeHandler["pa.RecordBatch"]):
             )
             verify_scalar_result(output_batch, batch.num_rows)
             yield output_batch
+
+
+class ArrowBatchedUDFArrowHandler(BatchEvalTypeHandler["pa.RecordBatch"]):
+    """SQL_ARROW_BATCHED_UDF (Arrow-optimized ``@udf``) with the Arrow conversion: convert each
+    input RecordBatch to Python values, invoke each UDF row by row, and convert the results
+    directly to Arrow arrays of the declared return types."""
+
+    eval_type = PythonEvalType.SQL_ARROW_BATCHED_UDF
+    variant_conf = "use_legacy_pandas_udf_conversion"
+    variant_value = False
+
+    def __init__(
+        self, udfs: list[tuple[Any, ...]], runner_conf: RunnerConf, eval_conf: EvalConf
+    ) -> None:
+        require_minimum_pyarrow_version()
+        super().__init__(udfs, runner_conf, eval_conf)
+
+        # --- UDF preparation ---
+        self._udf_infos = []
+        for udf_func, udf_args_offsets, udf_kwargs_offsets, udf_return_type in udfs:
+            wrapped_func, args_kwargs_offsets = wrap_kwargs_support(
+                udf_func, udf_args_offsets, udf_kwargs_offsets
+            )
+            zero_arg = len(args_kwargs_offsets) == 0
+            self._udf_infos.append(
+                (
+                    wrapped_func,
+                    args_kwargs_offsets or (0,),
+                    zero_arg,
+                    to_arrow_type(
+                        udf_return_type,
+                        timezone="UTC",
+                        prefers_large_types=runner_conf.use_large_var_types,
+                    ),
+                    LocalDataToArrowConversion._create_converter(
+                        udf_return_type,
+                        none_on_identity=True,
+                        int_to_decimal_coercion_enabled=runner_conf.int_to_decimal_coercion_enabled,
+                    ),
+                )
+            )
+        self._col_names = [f"_{i}" for i in range(len(udfs))]
+
+        # --- Input preparation ---
+        self._arrow_to_py_converters = [
+            ArrowTableToRowsConversion._create_converter(
+                f.dataType, none_on_identity=True, binary_as_bytes=runner_conf.binary_as_bytes
+            )
+            for f in eval_conf.input_type  # type: ignore[union-attr]
+        ]
+
+    def run(self, split_index: int, data: Iterator[pa.RecordBatch]) -> Iterator[pa.RecordBatch]:
+        import pyarrow as pa
+
+        runner_conf = self._runner_conf
+
+        @fail_on_stopiteration
+        def _evaluate_batch_udf(udf_func: Any, rows: list[tuple]) -> list[Any]:
+            if runner_conf.arrow_concurrency_level <= 0:
+                return [udf_func(*row) for row in rows]
+            from concurrent.futures import ThreadPoolExecutor
+
+            with ThreadPoolExecutor(max_workers=runner_conf.arrow_concurrency_level) as pool:
+                return list(pool.map(lambda row: udf_func(*row), rows))
+
+        for input_batch in data:
+            num_rows = input_batch.num_rows
+
+            # --- Input: Arrow -> Python columns ---
+            columns = [
+                (
+                    [conv(v) for v in ArrowTableToRowsConversion._to_pylist(col)]
+                    if conv is not None
+                    else ArrowTableToRowsConversion._to_pylist(col)
+                )
+                for col, conv in zip(input_batch.itercolumns(), self._arrow_to_py_converters)
+            ]
+            if not columns:
+                columns = [[_NoValue] * num_rows]
+
+            # --- Process: evaluate each UDF row-by-row ---
+            output_arrays = []
+            for udf_func, offsets, zero_arg, arrow_return_type, result_conv in self._udf_infos:
+                rows = (
+                    [() for _ in range(num_rows)]
+                    if zero_arg
+                    else list(zip(*[columns[o] for o in offsets]))
+                )
+                results = _evaluate_batch_udf(udf_func, rows)
+                verify_result_row_count(len(results), num_rows)
+
+                # --- Output: Python -> Arrow ---
+                converted = (
+                    [result_conv(r) for r in results] if result_conv is not None else results
+                )
+                try:
+                    arr = pa.array(converted, type=arrow_return_type)
+                except pa.lib.ArrowInvalid:
+                    arr = pa.array(converted).cast(
+                        target_type=arrow_return_type, safe=runner_conf.safecheck
+                    )
+                output_arrays.append(arr)
+
+            yield pa.RecordBatch.from_arrays(output_arrays, self._col_names)
diff --git a/python/pyspark/eval_handlers/_pandas.py b/python/pyspark/eval_handlers/_pandas.py
index c4fa685568c0..858836bcdf1a 100644
--- a/python/pyspark/eval_handlers/_pandas.py
+++ b/python/pyspark/eval_handlers/_pandas.py
@@ -31,13 +31,14 @@ from __future__ import annotations
 from collections.abc import Iterator
 from typing import TYPE_CHECKING, Any
 
+from pyspark import _NoValue
 from pyspark.errors import PySparkRuntimeError, PySparkTypeError, PySparkValueError
 from pyspark.eval_handlers._base import (
     BatchEvalTypeHandler,
     CoGroupedEvalTypeHandler,
     GroupedEvalTypeHandler,
 )
-from pyspark.eval_handlers.utils import extract_key_value_indexes
+from pyspark.eval_handlers.utils import extract_key_value_indexes, wrap_kwargs_support
 from pyspark.eval_handlers.verification import (
     verify_iter_result_row_count,
     verify_iterator_exhausted,
@@ -55,8 +56,8 @@ from pyspark.sql.pandas.utils import (
     require_minimum_pandas_version,
     require_minimum_pyarrow_version,
 )
-from pyspark.sql.types import StructField, StructType
-from pyspark.util import PythonEvalType
+from pyspark.sql.types import BinaryType, StringType, StructField, StructType
+from pyspark.util import PythonEvalType, fail_on_stopiteration
 
 if TYPE_CHECKING:
     import pyarrow as pa
@@ -718,3 +719,106 @@ class PandasWindowAggUDFHandler(GroupedEvalTypeHandler["pa.RecordBatch"]):
                 assign_cols_by_name=self._runner_conf.assign_cols_by_name,
                 int_to_decimal_coercion_enabled=self._runner_conf.int_to_decimal_coercion_enabled,
             )
+
+
+class ArrowBatchedUDFLegacyPandasHandler(BatchEvalTypeHandler["pa.RecordBatch"]):
+    """SQL_ARROW_BATCHED_UDF (Arrow-optimized ``@udf``) with the legacy pandas conversion:
+    convert each input RecordBatch to pandas Series, invoke each UDF row by row on their
+    values, and convert the results back to Arrow through pandas."""
+
+    eval_type = PythonEvalType.SQL_ARROW_BATCHED_UDF
+    variant_conf = "use_legacy_pandas_udf_conversion"
+    variant_value = True
+
+    def __init__(
+        self, udfs: list[tuple[Any, ...]], runner_conf: "RunnerConf", eval_conf: "EvalConf"
+    ) -> None:
+        require_minimum_pandas_version()
+        require_minimum_pyarrow_version()
+        super().__init__(udfs, runner_conf, eval_conf)
+
+        # --- UDF preparation ---
+        self._udf_infos = []
+        for udf_func, udf_args_offsets, udf_kwargs_offsets, udf_return_type in udfs:
+            wrapped_func, args_kwargs_offsets = wrap_kwargs_support(
+                udf_func, udf_args_offsets, udf_kwargs_offsets
+            )
+            zero_arg = len(args_kwargs_offsets) == 0
+            # Legacy coerces String/Binary for Arrow compatibility
+            coerce = (
+                str
+                if isinstance(udf_return_type, StringType)
+                else bytes
+                if isinstance(udf_return_type, BinaryType)
+                else None
+            )
+            self._udf_infos.append(
+                (
+                    wrapped_func,
+                    args_kwargs_offsets or (0,),
+                    zero_arg,
+                    udf_return_type,
+                    coerce,
+                )
+            )
+        col_names = [f"_{i}" for i in range(len(udfs))]
+        self._return_schema = StructType(
+            [StructField(name, info[3]) for name, info in zip(col_names, self._udf_infos)]
+        )
+
+    def run(self, split_index: int, data: "Iterator[pa.RecordBatch]") -> "Iterator[pa.RecordBatch]":
+        import pandas as pd
+
+        runner_conf = self._runner_conf
+
+        @fail_on_stopiteration
+        def _evaluate_batch_udf_legacy(udf_func: Any, rows: list[tuple]) -> list[Any]:
+            if runner_conf.arrow_concurrency_level <= 0:
+                return [udf_func(*row) for row in rows]
+            from concurrent.futures import ThreadPoolExecutor
+
+            with ThreadPoolExecutor(max_workers=runner_conf.arrow_concurrency_level) as pool:
+                return list(pool.map(lambda row: udf_func(*row), rows))
+
+        for input_batch in data:
+            # --- Input: Arrow -> pandas columns ---
+            pandas_columns = ArrowToPandasConversion.to_pandas(
+                input_batch,
+                timezone=runner_conf.timezone,
+                schema=self._eval_conf.input_type,  # type: ignore[arg-type]
+                struct_in_pandas="row",
+                ndarray_as_list=True,
+                prefer_int_ext_dtype=runner_conf.prefer_int_ext_dtype,
+                df_for_struct=False,
+            )
+            num_rows = len(pandas_columns[0]) if pandas_columns else input_batch.num_rows
+            if not pandas_columns:
+                pandas_columns = [pd.Series([_NoValue] * num_rows)]
+
+            # --- Process: evaluate each UDF row-by-row ---
+            result_series = []
+            for udf_func, offsets, zero_arg, _, coerce in self._udf_infos:
+                rows = (
+                    [() for _ in range(num_rows)]
+                    if zero_arg
+                    else list(
+                        zip(*[pandas_columns[o].tolist() for o in offsets])  # type: ignore[operator]
+                    )
+                )
+                results = _evaluate_batch_udf_legacy(udf_func, rows)
+                verify_result_row_count(len(results), num_rows)
+                if coerce:
+                    results = [coerce(v) if v is not None else v for v in results]
+                result_series.append(pd.Series(results))
+
+            # --- Output: pandas -> Arrow ---
+            yield PandasToArrowConversion.from_pandas(
+                result_series,
+                self._return_schema,
+                timezone=runner_conf.timezone,
+                safecheck=runner_conf.safecheck,
+                arrow_cast=True,
+                prefers_large_types=runner_conf.use_large_var_types,
+                assign_cols_by_name=runner_conf.assign_cols_by_name,
+                int_to_decimal_coercion_enabled=runner_conf.int_to_decimal_coercion_enabled,
+            )
diff --git a/python/pyspark/eval_handlers/tests/test_arrow_eval_type_handlers.py b/python/pyspark/eval_handlers/tests/test_arrow_eval_type_handlers.py
index 43338a372ebb..490f0cac683e 100644
--- a/python/pyspark/eval_handlers/tests/test_arrow_eval_type_handlers.py
+++ b/python/pyspark/eval_handlers/tests/test_arrow_eval_type_handlers.py
@@ -30,7 +30,7 @@ from pyspark.errors import PySparkRuntimeError
 from pyspark.eval_handlers._base import get_eval_type_handler
 from pyspark.eval_handlers.utils import hashable_grouping_key
 from pyspark.sql.pandas.serializers import ArrowStreamCoGroupSerializer, ArrowStreamSerializer
-from pyspark.sql.types import DoubleType, LongType, StructField, StructType
+from pyspark.sql.types import DoubleType, LongType, StringType, StructField, StructType
 from pyspark.testing.utils import PySparkBaseTestCase, have_pyarrow, pyarrow_requirement_message
 from pyspark.util import PythonEvalType
 
@@ -41,6 +41,7 @@ if have_pyarrow:
     import pyarrow as pa
 
     from pyspark.eval_handlers._arrow import (
+        ArrowBatchedUDFArrowHandler,
         ArrowCoGroupedMapUDFHandler,
         ArrowGroupedAggIncrementalFinalUDFHandler,
         ArrowGroupedAggIncrementalPartialUDFHandler,
@@ -172,6 +173,92 @@ class ArrowEvalTypeHandlerRegistrationTests(PySparkBaseTestCase):
         ):
             self.assertIs(get_eval_type_handler(eval_type, RunnerConf({})), handler_cls)
 
+    def test_arrow_batched_udf_arrow_variant_is_registered(self):
+        # SQL_ARROW_BATCHED_UDF picks its variant by the legacy pandas conversion conf; the
+        # Arrow variant serves the default and the explicit "false".
+        legacy_conf = "spark.sql.legacy.execution.pythonUDF.pandas.conversion.enabled"
+        for conf in ({}, {legacy_conf: "false"}):
+            with self.subTest(conf=conf):
+                self.assertIs(
+                    get_eval_type_handler(PythonEvalType.SQL_ARROW_BATCHED_UDF, RunnerConf(conf)),
+                    ArrowBatchedUDFArrowHandler,
+                )
+
+
+@unittest.skipIf(not have_pyarrow, pyarrow_requirement_message)
+class ArrowBatchedUDFArrowHandlerTests(ArrowEvalTypeHandlerTestCase):
+    _INPUT_TYPE = StructType([StructField("a", LongType()), StructField("b", LongType())])
+
+    def _handler(self, *udfs, runner_conf=None, input_type=None):
+        """Build the handler from ``(func, args_offsets, kwargs_offsets, return_type)`` tuples."""
+        return ArrowBatchedUDFArrowHandler(
+            udfs=list(udfs),
+            runner_conf=runner_conf or RunnerConf({}),
+            eval_conf=EvalConf({"input_type": (input_type or self._INPUT_TYPE).json()}),
+        )
+
+    def test_serializer(self):
+        handler = self._handler((lambda a: a, [0], {}, LongType()))
+        self.assertIsInstance(handler.serializer, ArrowStreamSerializer)
+
+    def test_invokes_udf_per_row(self):
+        handler = self._handler(
+            (lambda a: a + 1, [0], {}, LongType()),
+            (lambda a, b: a * b, [0, 1], {}, LongType()),
+        )
+        out = list(
+            handler.run(0, iter([self._batch(a=[1, 2], b=[10, 20]), self._batch(a=[3], b=[4])]))
+        )
+        self.assertEqual([b.schema.names for b in out], [["_0", "_1"], ["_0", "_1"]])
+        self.assertEqual(
+            [b.to_pydict() for b in out],
+            [{"_0": [2, 3], "_1": [10, 40]}, {"_0": [4], "_1": [12]}],
+        )
+
+    def test_passes_arg_by_keyword_offset(self):
+        handler = self._handler((lambda x, y: x - y, [0], {"y": 1}, LongType()))
+        out = list(handler.run(0, iter([self._batch(a=[10, 20], b=[3, 5])])))
+        self.assertEqual(out[0].column(0).to_pylist(), [7, 15])
+
+    def test_zero_arg_udf(self):
+        handler = self._handler((lambda: 7, [], {}, LongType()), input_type=StructType())
+        empty = pa.RecordBatch.from_pydict({"a": [1, 2, 3]}).select([])
+        out = list(handler.run(0, iter([empty])))
+        self.assertEqual(out[0].column(0).to_pylist(), [7, 7, 7])
+
+    def test_none_result_is_null(self):
+        handler = self._handler((lambda a: None if a == 2 else a, [0], {}, LongType()))
+        out = list(handler.run(0, iter([self._batch(a=[1, 2, 3], b=[0, 0, 0])])))
+        self.assertEqual(out[0].column(0).to_pylist(), [1, None, 3])
+
+    def test_converts_result_to_return_type(self):
+        # Results are converted directly to the declared Arrow type, without the legacy
+        # str coercion: an int result for a StringType UDF is cast to its string form.
+        handler = self._handler((lambda a: a, [0], {}, StringType()))
+        out = list(handler.run(0, iter([self._batch(a=[1, 2], b=[0, 0])])))
+        self.assertEqual(out[0].schema.field(0).type, pa.string())
+        self.assertEqual(out[0].column(0).to_pylist(), ["1", "2"])
+
+    def test_forwards_use_large_var_types_to_output_conversion(self):
+        conf = RunnerConf({"spark.sql.execution.arrow.useLargeVarTypes": "true"})
+        handler = self._handler((lambda a: str(a), [0], {}, StringType()), runner_conf=conf)
+        out = list(handler.run(0, iter([self._batch(a=[1], b=[0])])))
+        self.assertTrue(pa.types.is_large_string(out[0].schema.field(0).type))
+
+    def test_concurrency_level(self):
+        conf = RunnerConf({"spark.sql.execution.pythonUDF.arrow.concurrency.level": "4"})
+        handler = self._handler((lambda a: a * 2, [0], {}, LongType()), runner_conf=conf)
+        out = list(handler.run(0, iter([self._batch(a=list(range(10)), b=[0] * 10)])))
+        self.assertEqual(out[0].column(0).to_pylist(), [v * 2 for v in range(10)])
+
+    def test_stop_iteration_raises_runtime_error(self):
+        def stop(a):
+            raise StopIteration()
+
+        handler = self._handler((stop, [0], {}, LongType()))
+        with self.assertRaises(PySparkRuntimeError):
+            list(handler.run(0, iter([self._batch(a=[1], b=[0])])))
+
 
 @unittest.skipIf(not have_pyarrow, pyarrow_requirement_message)
 class ArrowScalarUDFHandlerTests(ArrowEvalTypeHandlerTestCase):
diff --git a/python/pyspark/eval_handlers/tests/test_pandas_eval_type_handlers.py b/python/pyspark/eval_handlers/tests/test_pandas_eval_type_handlers.py
index 68682061f2b5..55e416239c5d 100644
--- a/python/pyspark/eval_handlers/tests/test_pandas_eval_type_handlers.py
+++ b/python/pyspark/eval_handlers/tests/test_pandas_eval_type_handlers.py
@@ -31,7 +31,7 @@ from unittest.mock import patch
 
 from pyspark.errors import PySparkRuntimeError, PySparkTypeError, PySparkValueError
 from pyspark.eval_handlers._base import get_eval_type_handler
-from pyspark.sql.types import LongType, StringType, StructField, StructType
+from pyspark.sql.types import BinaryType, LongType, StringType, StructField, StructType
 from pyspark.testing.utils import (
     PySparkBaseTestCase,
     have_pandas,
@@ -42,13 +42,14 @@ from pyspark.testing.utils import (
 from pyspark.util import PythonEvalType
 
 with patch.dict(os.environ, {"SPARK_PYTHON_RUNTIME": "PYTHON_WORKER"}):
-    from pyspark.worker_util import RunnerConf
+    from pyspark.worker_util import EvalConf, RunnerConf
 
 if have_pandas and have_pyarrow:
     import pandas as pd
     import pyarrow as pa
 
     from pyspark.eval_handlers._pandas import (
+        ArrowBatchedUDFLegacyPandasHandler,
         PandasCoGroupedMapUDFHandler,
         PandasGroupedAggIterUDFHandler,
         PandasGroupedAggUDFHandler,
@@ -141,6 +142,77 @@ class PandasEvalTypeHandlerRegistrationTests(PySparkBaseTestCase):
         ):
             self.assertIs(get_eval_type_handler(eval_type, RunnerConf({})), handler_cls)
 
+    def test_arrow_batched_udf_legacy_pandas_variant_is_registered(self):
+        # SQL_ARROW_BATCHED_UDF picks its variant by the legacy pandas conversion conf.
+        conf = RunnerConf(
+            {"spark.sql.legacy.execution.pythonUDF.pandas.conversion.enabled": "true"}
+        )
+        self.assertIs(
+            get_eval_type_handler(PythonEvalType.SQL_ARROW_BATCHED_UDF, conf),
+            ArrowBatchedUDFLegacyPandasHandler,
+        )
+
+
+@unittest.skipIf(not (have_pandas and have_pyarrow), _missing_message)
+class ArrowBatchedUDFLegacyPandasHandlerTests(PandasEvalTypeHandlerTestCase):
+    _INPUT_TYPE = StructType([StructField("a", LongType()), StructField("b", LongType())])
+
+    def _handler(self, *udfs, runner_conf=None, input_type=None):
+        """Build the handler from one or more ``_udf`` tuples."""
+        return ArrowBatchedUDFLegacyPandasHandler(
+            udfs=list(udfs),
+            runner_conf=runner_conf or RunnerConf({}),
+            eval_conf=EvalConf({"input_type": (input_type or self._INPUT_TYPE).json()}),
+        )
+
+    def test_invokes_udf_per_row(self):
+        handler = self._handler(
+            self._udf(lambda a: a + 1),
+            self._udf(lambda a, b: a * b, args=(0, 1)),
+        )
+        out = list(
+            handler.run(0, iter([self._batch(a=[1, 2], b=[10, 20]), self._batch(a=[3], b=[4])]))
+        )
+        self.assertEqual(
+            [b.to_pydict() for b in out],
+            [{"_0": [2, 3], "_1": [10, 40]}, {"_0": [4], "_1": [12]}],
+        )
+
+    def test_passes_arg_by_keyword_offset(self):
+        handler = self._handler(self._udf(lambda x, y: x - y, args=(0,), kwargs={"y": 1}))
+        out = list(handler.run(0, iter([self._batch(a=[10, 20], b=[3, 5])])))
+        self.assertEqual(out[0].column(0).to_pylist(), [7, 15])
+
+    def test_zero_arg_udf(self):
+        handler = self._handler(self._udf(lambda: 7, args=()), input_type=StructType())
+        empty = pa.RecordBatch.from_pydict({"a": [1, 2, 3]}).select([])
+        out = list(handler.run(0, iter([empty])))
+        self.assertEqual(out[0].column(0).to_pylist(), [7, 7, 7])
+
+    def test_coerces_string_and_binary_results(self):
+        # The legacy conversion coerces results with str() / bytes() for String / Binary.
+        handler = self._handler(
+            self._udf(lambda a: a, return_type=StringType()),
+            self._udf(lambda a: None if a == 2 else bytearray(b"x"), return_type=BinaryType()),
+        )
+        out = list(handler.run(0, iter([self._batch(a=[1, 2], b=[0, 0])])))
+        self.assertEqual(out[0].column(0).to_pylist(), ["1", "2"])
+        self.assertEqual(out[0].column(1).to_pylist(), [b"x", None])
+
+    def test_concurrency_level(self):
+        conf = RunnerConf({"spark.sql.execution.pythonUDF.arrow.concurrency.level": "4"})
+        handler = self._handler(self._udf(lambda a: a * 2), runner_conf=conf)
+        out = list(handler.run(0, iter([self._batch(a=list(range(10)), b=[0] * 10)])))
+        self.assertEqual(out[0].column(0).to_pylist(), [v * 2 for v in range(10)])
+
+    def test_stop_iteration_raises_runtime_error(self):
+        def stop(a):
+            raise StopIteration()
+
+        handler = self._handler(self._udf(stop))
+        with self.assertRaises(PySparkRuntimeError):
+            list(handler.run(0, iter([self._batch(a=[1], b=[0])])))
+
 
 @unittest.skipIf(not (have_pandas and have_pyarrow), _missing_message)
 class PandasScalarUDFHandlerTests(PandasEvalTypeHandlerTestCase):
diff --git a/python/pyspark/worker.py b/python/pyspark/worker.py
index 9d87ca0fab24..31c95e633343 100644
--- a/python/pyspark/worker.py
+++ b/python/pyspark/worker.py
@@ -43,7 +43,7 @@ if TYPE_CHECKING:
     import pandas as pd
     import pyarrow as pa
 
-from pyspark import _NoValue, shuffle
+from pyspark import shuffle
 from pyspark.accumulators import (
     SpecialAccumulatorIds,
     _accumulatorRegistry,
@@ -606,7 +606,6 @@ def _elementwise_pandas_or_arrow_udf_output_to_flat_batch(
 
 def read_udfs(pickleSer, udf_info_list, eval_type, runner_conf, eval_conf):
     if eval_type in (
-        PythonEvalType.SQL_ARROW_BATCHED_UDF,
         PythonEvalType.SQL_ARROW_ELEMENTWISE_UDF,
         PythonEvalType.SQL_SCALAR_PANDAS_ELEMENTWISE_UDF,
         PythonEvalType.SQL_SCALAR_PANDAS_ITER_ELEMENTWISE_UDF,
@@ -631,187 +630,6 @@ def read_udfs(pickleSer, udf_info_list, eval_type, runner_conf, eval_conf):
 
     num_udfs = len(udfs)
 
-    if (
-        eval_type == PythonEvalType.SQL_ARROW_BATCHED_UDF
-        and not runner_conf.use_legacy_pandas_udf_conversion
-    ):
-        import pyarrow as pa
-
-        # --- UDF preparation ---
-        udf_infos = []
-        for udf_func, udf_args_offsets, udf_kwargs_offsets, udf_return_type in udfs:
-            wrapped_func, args_kwargs_offsets = wrap_kwargs_support(
-                udf_func, udf_args_offsets, udf_kwargs_offsets
-            )
-            zero_arg = len(args_kwargs_offsets) == 0
-            udf_infos.append(
-                (
-                    wrapped_func,
-                    args_kwargs_offsets or (0,),
-                    zero_arg,
-                    to_arrow_type(
-                        udf_return_type,
-                        timezone="UTC",
-                        prefers_large_types=runner_conf.use_large_var_types,
-                    ),
-                    LocalDataToArrowConversion._create_converter(
-                        udf_return_type,
-                        none_on_identity=True,
-                        int_to_decimal_coercion_enabled=runner_conf.int_to_decimal_coercion_enabled,
-                    ),
-                )
-            )
-        col_names = [f"_{i}" for i in range(len(udfs))]
-
-        # --- Input preparation ---
-        arrow_to_py_converters = [
-            ArrowTableToRowsConversion._create_converter(
-                f.dataType, none_on_identity=True, binary_as_bytes=runner_conf.binary_as_bytes
-            )
-            for f in eval_conf.input_type
-        ]
-
-        @fail_on_stopiteration
-        def _evaluate_batch_udf(udf_func, rows):
-            if runner_conf.arrow_concurrency_level <= 0:
-                return [udf_func(*row) for row in rows]
-            from concurrent.futures import ThreadPoolExecutor
-
-            with ThreadPoolExecutor(max_workers=runner_conf.arrow_concurrency_level) as pool:
-                return list(pool.map(lambda row: udf_func(*row), rows))
-
-        def func(split_index: int, data: Iterator[pa.RecordBatch]) -> Iterator[pa.RecordBatch]:
-            for input_batch in data:
-                num_rows = input_batch.num_rows
-
-                # --- Input: Arrow -> Python columns ---
-                columns = [
-                    (
-                        [conv(v) for v in ArrowTableToRowsConversion._to_pylist(col)]
-                        if conv is not None
-                        else ArrowTableToRowsConversion._to_pylist(col)
-                    )
-                    for col, conv in zip(input_batch.itercolumns(), arrow_to_py_converters)
-                ]
-                if not columns:
-                    columns = [[_NoValue] * num_rows]
-
-                # --- Process: evaluate each UDF row-by-row ---
-                output_arrays = []
-                for udf_func, offsets, zero_arg, arrow_return_type, result_conv in udf_infos:
-                    rows = (
-                        [() for _ in range(num_rows)]
-                        if zero_arg
-                        else list(zip(*[columns[o] for o in offsets]))
-                    )
-                    results = _evaluate_batch_udf(udf_func, rows)
-                    verify_result_row_count(len(results), num_rows)
-
-                    # --- Output: Python -> Arrow ---
-                    converted = (
-                        [result_conv(r) for r in results] if result_conv is not None else results
-                    )
-                    try:
-                        arr = pa.array(converted, type=arrow_return_type)
-                    except pa.lib.ArrowInvalid:
-                        arr = pa.array(converted).cast(
-                            target_type=arrow_return_type, safe=runner_conf.safecheck
-                        )
-                    output_arrays.append(arr)
-
-                yield pa.RecordBatch.from_arrays(output_arrays, col_names)
-
-        return func, ser
-
-    if (
-        eval_type == PythonEvalType.SQL_ARROW_BATCHED_UDF
-        and runner_conf.use_legacy_pandas_udf_conversion
-    ):
-        import pandas as pd
-        import pyarrow as pa
-
-        # --- UDF preparation ---
-        udf_infos = []
-        for udf_func, udf_args_offsets, udf_kwargs_offsets, udf_return_type in udfs:
-            wrapped_func, args_kwargs_offsets = wrap_kwargs_support(
-                udf_func, udf_args_offsets, udf_kwargs_offsets
-            )
-            zero_arg = len(args_kwargs_offsets) == 0
-            # Legacy coerces String/Binary for Arrow compatibility
-            coerce = (
-                str
-                if isinstance(udf_return_type, StringType)
-                else bytes
-                if isinstance(udf_return_type, BinaryType)
-                else None
-            )
-            udf_infos.append(
-                (
-                    wrapped_func,
-                    args_kwargs_offsets or (0,),
-                    zero_arg,
-                    udf_return_type,
-                    coerce,
-                )
-            )
-        col_names = [f"_{i}" for i in range(len(udfs))]
-        return_schema = StructType(
-            [StructField(name, info[3]) for name, info in zip(col_names, udf_infos)]
-        )
-
-        @fail_on_stopiteration
-        def _evaluate_batch_udf_legacy(udf_func, rows):
-            if runner_conf.arrow_concurrency_level <= 0:
-                return [udf_func(*row) for row in rows]
-            from concurrent.futures import ThreadPoolExecutor
-
-            with ThreadPoolExecutor(max_workers=runner_conf.arrow_concurrency_level) as pool:
-                return list(pool.map(lambda row: udf_func(*row), rows))
-
-        def func(split_index: int, data: Iterator[pa.RecordBatch]) -> Iterator[pa.RecordBatch]:
-            for input_batch in data:
-                # --- Input: Arrow -> pandas columns ---
-                pandas_columns = ArrowToPandasConversion.to_pandas(
-                    input_batch,
-                    timezone=runner_conf.timezone,
-                    schema=eval_conf.input_type,
-                    struct_in_pandas="row",
-                    ndarray_as_list=True,
-                    prefer_int_ext_dtype=runner_conf.prefer_int_ext_dtype,
-                    df_for_struct=False,
-                )
-                num_rows = len(pandas_columns[0]) if pandas_columns else input_batch.num_rows
-                if not pandas_columns:
-                    pandas_columns = [pd.Series([_NoValue] * num_rows)]
-
-                # --- Process: evaluate each UDF row-by-row ---
-                result_series = []
-                for udf_func, offsets, zero_arg, _, coerce in udf_infos:
-                    rows = (
-                        [() for _ in range(num_rows)]
-                        if zero_arg
-                        else list(zip(*[pandas_columns[o].tolist() for o in offsets]))
-                    )
-                    results = _evaluate_batch_udf_legacy(udf_func, rows)
-                    verify_result_row_count(len(results), num_rows)
-                    if coerce:
-                        results = [coerce(v) if v is not None else v for v in results]
-                    result_series.append(pd.Series(results))
-
-                # --- Output: pandas -> Arrow ---
-                yield PandasToArrowConversion.from_pandas(
-                    result_series,
-                    return_schema,
-                    timezone=runner_conf.timezone,
-                    safecheck=runner_conf.safecheck,
-                    arrow_cast=True,
-                    prefers_large_types=runner_conf.use_large_var_types,
-                    assign_cols_by_name=runner_conf.assign_cols_by_name,
-                    int_to_decimal_coercion_enabled=runner_conf.int_to_decimal_coercion_enabled,
-                )
-
-        return func, ser
-
     if eval_type == PythonEvalType.SQL_ARROW_ELEMENTWISE_UDF:
         # This path exchanges data with the JVM over Arrow, so PyArrow is required. Fail with a
         # clear message rather than a bare ImportError from `import pyarrow` below.
@@ -920,10 +738,10 @@ def read_udfs(pickleSer, udf_info_list, eval_type, runner_conf, eval_conf):
                     )
                     try:
                         flat_arr = pa.array(converted, type=arrow_element_type)
-                    # Broader than the SQL_ARROW_BATCHED_UDF path above (which catches only
-                    # ArrowInvalid): the element-wise wrapper commonly returns list/struct-typed
-                    # elements, whose type mismatches surface as ArrowTypeError, so both are caught
-                    # before falling back to an explicit cast.
+                    # Catch ArrowTypeError as well as ArrowInvalid: the element-wise wrapper
+                    # commonly returns list/struct-typed elements, whose type mismatches surface
+                    # as ArrowTypeError, so both are caught before falling back to an explicit
+                    # cast.
                     except (pa.lib.ArrowInvalid, pa.lib.ArrowTypeError):
                         flat_arr = pa.array(converted).cast(
                             target_type=arrow_element_type, safe=runner_conf.safecheck


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org