You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "allisonwang-db (via GitHub)" <gi...@apache.org> on 2025/07/28 21:13:50 UTC
[PR] [SPARK-52980][PYTHON] Support Arrow Python UDTFs [spark]
allisonwang-db opened a new pull request, #51692:
URL: https://github.com/apache/spark/pull/51692
<!--
Thanks for sending a pull request! Here are some tips for you:
1. If this is your first time, please read our contributor guidelines: https://spark.apache.org/contributing.html
2. Ensure you have added or run the appropriate tests for your PR: https://spark.apache.org/developer-tools.html
3. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP][SPARK-XXXX] Your PR title ...'.
4. Be sure to keep the PR description updated to reflect all changes.
5. Please write your PR title to summarize what this PR proposes.
6. If possible, provide a concise example to reproduce the issue for a faster review.
7. If you want to add a new configuration, please read the guideline first for naming configurations in
'core/src/main/scala/org/apache/spark/internal/config/ConfigEntry.scala'.
8. If you want to add or modify an error type or message, please read the guideline first in
'common/utils/src/main/resources/error/README.md'.
-->
### What changes were proposed in this pull request?
<!--
Please clarify what changes you are proposing. The purpose of this section is to outline the changes and how this PR fixes the issue.
If possible, please consider writing useful notes for better and faster reviews in your PR. See the examples below.
1. If you refactor some codes with changing classes, showing the class hierarchy will help reviewers.
2. If you fix some SQL features, you can provide some references of other DBMSes.
3. If there is design documentation, please add the link.
4. If there is a discussion in the mailing list, please add the link.
-->
This PR introduces PyArrow-native support for User Defined Table Functions (UDTFs) in PySpark, enabling vectorized computation without row-by-row processing overhead. The new `arrow_udtf` decorator allows UDTF handlers to work directly with Arrow RecordBatch and Arrays.
The current PR supports scalar input arguments:
```
@arrow_udtf(returnType="x int, y int")
class ArrayUDTF:
def eval(self, x: pa.Array, y: pa.Array) -> Iterator[pa.RecordBatch | pa.Table]:
# Process arrays vectorized
yield result_table
```
And a subsequent PR will support table argument
```
@arrow_udtf(returnType="x int, y int")
class TableUDTF:
def eval(self, batch: pa.RecordBatch):
# Process entire batch vectorized
yield result_table
```
### Why are the changes needed?
<!--
Please clarify why the changes are needed. For instance,
1. If you propose a new API, clarify the use case for a new API.
2. If you fix a bug, you can clarify why it is a bug.
-->
To support vectorized Python UDTFs and provide performance improvements
### Does this PR introduce _any_ user-facing change?
<!--
Note that it means *any* user-facing change including all aspects such as new features, bug fixes, or other behavior changes. Documentation-only updates are not considered user-facing changes.
If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description and/or an example to show the behavior difference if possible.
If possible, please also clarify if this is a user-facing change compared to the released Spark versions or within the unreleased branches such as master.
If no, write 'No'.
-->
Yes. This PR adds a new user-facing API for vectorized Python UDTFs.
### How was this patch tested?
<!--
If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
If tests were not added, please describe why they were not added and/or why it was difficult to add.
If benchmark tests were added, please run the benchmarks in GitHub Actions for the consistent environment, and the instructions could accord to: https://spark.apache.org/developer-tools.html#github-workflow-benchmarks.
-->
New unit tests
### Was this patch authored or co-authored using generative AI tooling?
<!--
If generative AI tooling has been used in the process of authoring this patch, please include the
phrase: 'Generated-by: ' followed by the name of the tool and its version.
If no, write 'No'.
Please refer to the [ASF Generative Tooling Guidance](https://www.apache.org/legal/generative-tooling.html) for details.
-->
No
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-52980][PYTHON] Support Arrow Python UDTFs [spark]
Posted by "allisonwang-db (via GitHub)" <gi...@apache.org>.
allisonwang-db closed pull request #51692: [SPARK-52980][PYTHON] Support Arrow Python UDTFs
URL: https://github.com/apache/spark/pull/51692
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-52980][PYTHON] Support Arrow Python UDTFs [spark]
Posted by "allisonwang-db (via GitHub)" <gi...@apache.org>.
allisonwang-db commented on PR #51692:
URL: https://github.com/apache/spark/pull/51692#issuecomment-3152917756
Thanks, merging to master.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-52980][PYTHON] Support Arrow Python UDTFs [spark]
Posted by "allisonwang-db (via GitHub)" <gi...@apache.org>.
allisonwang-db commented on PR #51692:
URL: https://github.com/apache/spark/pull/51692#issuecomment-3161160087
@zhengruifeng thanks creating a fix pr: https://github.com/apache/spark/pull/51880
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-52980][PYTHON] Support Arrow Python UDTFs [spark]
Posted by "allisonwang-db (via GitHub)" <gi...@apache.org>.
allisonwang-db commented on code in PR #51692:
URL: https://github.com/apache/spark/pull/51692#discussion_r2241325363
##########
python/pyspark/sql/pandas/serializers.py:
##########
@@ -197,6 +197,15 @@ def load_stream(self, stream):
return ArrowStreamSerializer.load_stream(self, stream)
+class ArrowStreamArrowUDTFSerializer(ArrowStreamUDTFSerializer):
Review Comment:
I don't think we can support this type coercion? E.g int64 → int32 fails. Do you know how Python Arrow UDF handles return type coercion? We should make Arrow Python UDTFs consistent.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-52980][PYTHON] Support Arrow Python UDTFs [spark]
Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng commented on code in PR #51692:
URL: https://github.com/apache/spark/pull/51692#discussion_r2239032745
##########
python/pyspark/worker.py:
##########
@@ -1896,6 +1906,180 @@ def mapper(_, it):
cleanup()
return mapper, None, ser, ser
+
+ elif eval_type == PythonEvalType.SQL_ARROW_UDTF:
+
+ def wrap_pyarrow_udtf(f, return_type):
+ import pyarrow as pa
+
+ arrow_return_type = to_arrow_type(
+ return_type, prefers_large_types=use_large_var_types(runner_conf)
+ )
+ return_type_size = len(return_type)
+
+ def verify_result(result):
+ if not isinstance(result, (pa.Table, pa.RecordBatch)):
+ raise PySparkTypeError(
+ errorClass="INVALID_ARROW_UDTF_RETURN_TYPE",
+ messageParameters={
+ "return_type": type(result).__name__,
+ "value": str(result),
+ "func": f.__name__,
+ },
+ )
+
+ if isinstance(result, pa.Table):
+ if result.num_rows == 0:
+ return pa.RecordBatch.from_pylist(
+ [], schema=pa.schema(list(arrow_return_type))
+ )
+ else:
+ result = (
+ result.to_batches()[0]
+ if result.to_batches()
+ else pa.RecordBatch.from_pylist([], schema=result.schema)
+ )
+
+ # Validate the output schema when the result has columns
+ if result.num_columns > 0:
+ if result.num_columns != return_type_size:
+ raise PySparkRuntimeError(
+ errorClass="UDTF_RETURN_SCHEMA_MISMATCH",
+ messageParameters={
+ "expected": str(return_type_size),
+ "actual": str(result.num_columns),
+ "func": f.__name__,
+ },
+ )
+
+ # Verify the type and the schema of the result.
+ verify_arrow_result(
+ pa.Table.from_batches([result], schema=pa.schema(list(arrow_return_type))),
+ assign_cols_by_name=False,
+ expected_cols_and_types=[
+ (col.name, to_arrow_type(col.dataType)) for col in return_type.fields
+ ],
+ )
+ return result
+
+ # Wrap the exception thrown from the UDTF in a PySparkRuntimeError.
+ def func(*a: Any) -> Any:
+ try:
+ return f(*a)
+ except SkipRestOfInputTableException:
+ raise
+ except Exception as e:
+ raise PySparkRuntimeError(
+ errorClass="UDTF_EXEC_ERROR",
+ messageParameters={"method_name": f.__name__, "error": str(e)},
+ )
+
+ def check_return_value(res):
+ # Check whether the result of a PyArrow UDTF is iterable before processing
+ if res is not None:
+ if not isinstance(res, Iterable):
+ raise PySparkRuntimeError(
+ errorClass="UDTF_RETURN_NOT_ITERABLE",
+ messageParameters={
+ "type": type(res).__name__,
+ "func": f.__name__,
+ },
+ )
+ if check_output_row_against_schema is not None:
+ # For PyArrow UDTFs, we need to convert the result to rows for validation
+ if isinstance(res, (pa.Table, pa.RecordBatch)):
+ table = (
+ res if isinstance(res, pa.Table) else pa.Table.from_batches([res])
+ )
+ for batch in table.to_batches():
+ for row_idx in range(batch.num_rows):
+ row_data = tuple(
+ batch.column(i)[row_idx].as_py()
+ for i in range(batch.num_columns)
+ )
+ check_output_row_against_schema(row_data)
+ else:
+ for row in res:
+ if row is not None:
+ check_output_row_against_schema(row)
+ yield from res
+ return
+
+ yield from res
+
+ def convert_to_arrow(data: Iterable):
+ data_list = list(check_return_value(data))
+ if len(data_list) == 0:
+ return [
+ pa.RecordBatch.from_pylist([], schema=pa.schema(list(arrow_return_type)))
+ ]
+
+ # Handle PyArrow Tables/RecordBatches directly
+ batches = []
+ for item in data_list:
+ if isinstance(item, pa.Table):
+ batches.extend(item.to_batches())
+ elif isinstance(item, pa.RecordBatch):
+ batches.append(item)
+ else:
+ # Fallback for other data types
+ # TODO: shall we be strict here and throw exceptions?
Review Comment:
I think we should fail here, `arrow_udtf` should not return normal row data
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-52980][PYTHON] Support Arrow Python UDTFs [spark]
Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng commented on code in PR #51692:
URL: https://github.com/apache/spark/pull/51692#discussion_r2239054392
##########
python/pyspark/sql/pandas/serializers.py:
##########
@@ -197,6 +197,15 @@ def load_stream(self, stream):
return ArrowStreamSerializer.load_stream(self, stream)
+class ArrowStreamArrowUDTFSerializer(ArrowStreamUDTFSerializer):
Review Comment:
qq: dose arrow udtf (and arrow-optimized python udtf) support return type coercion?
e.g.
```
@arrow_udtf(returnType="id int")
class TestUDTF:
def eval(self) -> Iterator["pa.Table"]:
yield table with long values
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-52980][PYTHON] Support Arrow Python UDTFs [spark]
Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng commented on PR #51692:
URL: https://github.com/apache/spark/pull/51692#issuecomment-3160049044
@allisonwang-db the new test failed in a daily job https://github.com/apache/spark/actions/runs/16772683954/job/47491522789 with minimum versions( pyarrow=15.0, pandas=2.2.0)
Can we fix the code or test to be compatiable with those versions? otherwise, we will need to
upgrade the minimum versions
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-52980][PYTHON] Support Arrow Python UDTFs [spark]
Posted by "ueshin (via GitHub)" <gi...@apache.org>.
ueshin commented on code in PR #51692:
URL: https://github.com/apache/spark/pull/51692#discussion_r2243488941
##########
python/pyspark/sql/pandas/serializers.py:
##########
@@ -197,6 +197,15 @@ def load_stream(self, stream):
return ArrowStreamSerializer.load_stream(self, stream)
+class ArrowStreamArrowUDTFSerializer(ArrowStreamUDTFSerializer):
+ """
+ Serializer for PyArrow-native UDTFs that work directly with PyArrow RecordBatches and Arrays.
+ """
+
+ # TODO: support table arguments
Review Comment:
nit: shall we file another JIRA ticket for this and mark this todo as `TODO(SPARK-xxx)` to track it?
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/python/ExtractPythonUDFs.scala:
##########
@@ -406,6 +406,10 @@ object ExtractPythonUDTFs extends Rule[LogicalPlan] {
BatchEvalPythonUDTF(func, g.requiredChildOutput, g.generatorOutput, child)
case PythonEvalType.SQL_ARROW_TABLE_UDF =>
ArrowEvalPythonUDTF(func, g.requiredChildOutput, g.generatorOutput, child, func.evalType)
+ case PythonEvalType.SQL_ARROW_UDTF =>
+ ArrowEvalPythonUDTF(func, g.requiredChildOutput, g.generatorOutput, child, func.evalType)
+ case _ =>
+ throw SparkException.internalError(s"Unsupported UDTF eval type: ${func.evalType}")
Review Comment:
Nice!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-52980][PYTHON] Support Arrow Python UDTFs [spark]
Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng commented on PR #51692:
URL: https://github.com/apache/spark/pull/51692#issuecomment-3138461658
LGTM pending CI
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-52980][PYTHON] Support Arrow Python UDTFs [spark]
Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng commented on code in PR #51692:
URL: https://github.com/apache/spark/pull/51692#discussion_r2247206389
##########
python/pyspark/sql/udtf.py:
##########
@@ -242,6 +247,61 @@ def _create_py_udtf(
)
+def _create_pyarrow_udtf(
+ cls: Type,
+ returnType: Optional[Union[StructType, str]],
+ name: Optional[str] = None,
+ deterministic: bool = False,
+) -> "UserDefinedTableFunction":
+ """Create a PyArrow-native Python UDTF."""
+ # Validate PyArrow dependencies
+ try:
+ require_minimum_pandas_version()
Review Comment:
nit, it seems arrow udtf doesn't depend on pandas?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-52980][PYTHON] Support Arrow Python UDTFs [spark]
Posted by "allisonwang-db (via GitHub)" <gi...@apache.org>.
allisonwang-db commented on code in PR #51692:
URL: https://github.com/apache/spark/pull/51692#discussion_r2244101191
##########
python/pyspark/sql/pandas/serializers.py:
##########
@@ -197,6 +197,15 @@ def load_stream(self, stream):
return ArrowStreamSerializer.load_stream(self, stream)
+class ArrowStreamArrowUDTFSerializer(ArrowStreamUDTFSerializer):
Review Comment:
Thanks I will create a follow up to support this for Arrow Python UDTFs. The behavior should be the same.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-52980][PYTHON] Support Arrow Python UDTFs [spark]
Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng commented on code in PR #51692:
URL: https://github.com/apache/spark/pull/51692#discussion_r2241413025
##########
python/pyspark/sql/pandas/serializers.py:
##########
@@ -197,6 +197,15 @@ def load_stream(self, stream):
return ArrowStreamSerializer.load_stream(self, stream)
+class ArrowStreamArrowUDTFSerializer(ArrowStreamUDTFSerializer):
Review Comment:
for arrow udf, we just support in in https://github.com/apache/spark/pull/51665, int64 -> int32 fails when overflow.
for other existing eval types, the coercion will be supported in https://github.com/apache/spark/pull/51635
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-52980][PYTHON] Support Arrow Python UDTFs [spark]
Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng commented on code in PR #51692:
URL: https://github.com/apache/spark/pull/51692#discussion_r2238271264
##########
python/pyspark/sql/tests/test_arrow_udtf.py:
##########
@@ -0,0 +1,327 @@
+#
+# 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.
+#
+import unittest
+from typing import Iterator
+
+from pyspark.errors.exceptions.captured import PythonException
+from pyspark.sql.functions import arrow_udtf, lit
+from pyspark.sql.types import Row
+from pyspark.testing.sqlutils import ReusedSQLTestCase, have_pyarrow, pyarrow_requirement_message
+from pyspark.testing import assertDataFrameEqual
+
+if have_pyarrow:
+ import pyarrow as pa
+
+
+@unittest.skipIf(not have_pyarrow, pyarrow_requirement_message)
+class ArrowUDTFTests(ReusedSQLTestCase):
+ def test_arrow_udtf_zero_args(self):
+ @arrow_udtf(returnType="id int, value string")
+ class TestUDTF:
+ def eval(self) -> Iterator["pa.Table"]:
+ result_table = pa.table(
+ {
+ "id": pa.array([1, 2, 3], type=pa.int32()),
+ "value": pa.array(["a", "b", "c"], type=pa.string()),
+ }
+ )
+ yield result_table
+
+ # Test direct DataFrame API usage
+ result_df = TestUDTF()
+ expected_df = self.spark.createDataFrame(
+ [(1, "a"), (2, "b"), (3, "c")], "id int, value string"
+ )
+ assertDataFrameEqual(result_df, expected_df)
+
+ # Test SQL registration and usage
+ self.spark.udtf.register("test_zero_args_udtf", TestUDTF)
+ sql_result_df = self.spark.sql("SELECT * FROM test_zero_args_udtf()")
+ assertDataFrameEqual(sql_result_df, expected_df)
+
+ def test_arrow_udtf_scalar_args_only(self):
+ @arrow_udtf(returnType="x int, y int, sum int")
+ class ScalarArgsUDTF:
+ def eval(self, x: "pa.Array", y: "pa.Array") -> Iterator["pa.Table"]:
+ assert isinstance(x, pa.Array), f"Expected pa.Array, got {type(x)}"
+ assert isinstance(y, pa.Array), f"Expected pa.Array, got {type(y)}"
+
+ x_val = x[0].as_py()
+ y_val = y[0].as_py()
+ result_table = pa.table(
+ {
+ "x": pa.array([x_val], type=pa.int32()),
+ "y": pa.array([y_val], type=pa.int32()),
+ "sum": pa.array([x_val + y_val], type=pa.int32()),
+ }
+ )
+ yield result_table
+
+ # Test direct DataFrame API usage
+ result_df = ScalarArgsUDTF(lit(5), lit(10))
+ expected_df = self.spark.createDataFrame([(5, 10, 15)], "x int, y int, sum int")
+ assertDataFrameEqual(result_df, expected_df)
+
+ # Test SQL registration and usage
+ self.spark.udtf.register("ScalarArgsUDTF", ScalarArgsUDTF)
+ sql_result_df = self.spark.sql("SELECT * FROM ScalarArgsUDTF(5, 10)")
+ assertDataFrameEqual(sql_result_df, expected_df)
+
+ # Test with different values via SQL
+ sql_result_df2 = self.spark.sql("SELECT * FROM ScalarArgsUDTF(4, 7)")
+ expected_df2 = self.spark.createDataFrame([(4, 7, 11)], "x int, y int, sum int")
+ assertDataFrameEqual(sql_result_df2, expected_df2)
+
+ def test_arrow_udtf_record_batch_iterator(self):
+ @arrow_udtf(returnType="batch_id int, name string, count int")
+ class RecordBatchUDTF:
+ def eval(self, batch_size: "pa.Array") -> Iterator["pa.RecordBatch"]:
+ assert isinstance(
+ batch_size, pa.Array
+ ), f"Expected pa.Array, got {type(batch_size)}"
+
+ size = batch_size[0].as_py()
+
+ for batch_id in range(3):
+ batch = pa.record_batch(
+ {
+ "batch_id": pa.array([batch_id] * size, type=pa.int32()),
+ "name": pa.array([f"batch_{batch_id}"] * size, type=pa.string()),
+ "count": pa.array(list(range(size)), type=pa.int32()),
+ }
+ )
+ yield batch
+
+ # Test direct DataFrame API usage
+ result_df = RecordBatchUDTF(lit(2))
+ expected_data = [
+ (0, "batch_0", 0),
+ (0, "batch_0", 1),
+ (1, "batch_1", 0),
+ (1, "batch_1", 1),
+ (2, "batch_2", 0),
+ (2, "batch_2", 1),
+ ]
+ expected_df = self.spark.createDataFrame(
+ expected_data, "batch_id int, name string, count int"
+ )
+ assertDataFrameEqual(result_df, expected_df)
+
+ # Test SQL registration and usage
+ self.spark.udtf.register("record_batch_udtf", RecordBatchUDTF)
+ sql_result_df = self.spark.sql(
+ "SELECT * FROM record_batch_udtf(2) ORDER BY batch_id, count"
+ )
+ assertDataFrameEqual(sql_result_df, expected_df)
+
+ # Test with different batch size via SQL
+ sql_result_df2 = self.spark.sql("SELECT * FROM record_batch_udtf(1) ORDER BY batch_id")
+ expected_data2 = [
+ (0, "batch_0", 0),
+ (1, "batch_1", 0),
+ (2, "batch_2", 0),
+ ]
+ expected_df2 = self.spark.createDataFrame(
+ expected_data2, "batch_id int, name string, count int"
+ )
+ assertDataFrameEqual(sql_result_df2, expected_df2)
+
+ def test_arrow_udtf_error_not_iterator(self):
+ @arrow_udtf(returnType="x int, y string")
+ class NotIteratorUDTF:
+ def eval(self) -> "pa.Table":
+ return pa.table(
+ {"x": pa.array([1], type=pa.int32()), "y": pa.array(["test"], type=pa.string())}
+ )
+
+ with self.assertRaisesRegex(PythonException, "UDTF_RETURN_NOT_ITERABLE"):
+ result_df = NotIteratorUDTF()
+ result_df.collect()
+
+ def test_arrow_udtf_error_wrong_yield_type(self):
+ @arrow_udtf(returnType="x int, y string")
+ class WrongYieldTypeUDTF:
+ def eval(self) -> Iterator["pa.Table"]:
+ yield {"x": [1], "y": ["test"]}
+
+ with self.assertRaisesRegex(PythonException, "UDTF_ARROW_TYPE_CONVERSION_ERROR"):
+ result_df = WrongYieldTypeUDTF()
+ result_df.collect()
+
+ def test_arrow_udtf_error_invalid_arrow_type(self):
+ @arrow_udtf(returnType="x int, y string")
+ class InvalidArrowTypeUDTF:
+ def eval(self) -> Iterator["pa.Table"]:
+ yield "not_an_arrow_table"
+
+ with self.assertRaisesRegex(PythonException, "UDTF_ARROW_TYPE_CONVERSION_ERROR"):
+ result_df = InvalidArrowTypeUDTF()
+ result_df.collect()
+
+ def test_arrow_udtf_error_mismatched_schema(self):
+ @arrow_udtf(returnType="x int, y string")
+ class MismatchedSchemaUDTF:
+ def eval(self) -> Iterator["pa.Table"]:
+ result_table = pa.table(
+ {
+ "wrong_col": pa.array([1], type=pa.int32()),
+ "another_wrong_col": pa.array([2.5], type=pa.float64()),
+ }
+ )
+ yield result_table
+
+ with self.assertRaisesRegex(PythonException, "Schema at index 0 was different"):
+ result_df = MismatchedSchemaUDTF()
+ result_df.collect()
+
+ def test_arrow_udtf_sql_with_aggregation(self):
+ @arrow_udtf(returnType="category string, count int")
+ class CategoryCountUDTF:
+ def eval(self, categories: "pa.Array") -> Iterator["pa.Table"]:
+ # The input is a single array element, extract the array contents
+ cat_array = categories[0].as_py() # Get the array from the first (and only) element
+
+ # Count occurrences
+ counts = {}
+ for cat in cat_array:
+ if cat is not None:
+ counts[cat] = counts.get(cat, 0) + 1
+
+ if counts:
+ result_table = pa.table(
+ {
+ "category": pa.array(list(counts.keys()), type=pa.string()),
+ "count": pa.array(list(counts.values()), type=pa.int32()),
+ }
+ )
+ yield result_table
+
+ self.spark.udtf.register("category_count_udtf", CategoryCountUDTF)
+
+ # Test with array input
+ result_df = self.spark.sql(
+ "SELECT * FROM category_count_udtf(array('A', 'B', 'A', 'C', 'B', 'A')) "
+ "ORDER BY category"
+ )
+ expected_df = self.spark.createDataFrame(
+ [("A", 3), ("B", 2), ("C", 1)], "category string, count int"
+ )
+ assertDataFrameEqual(result_df, expected_df)
+
+ def test_arrow_udtf_sql_with_struct_output(self):
+ @arrow_udtf(returnType="person struct<name:string,age:int>, status string")
+ class PersonStatusUDTF:
+ def eval(self, name: "pa.Array", age: "pa.Array") -> Iterator["pa.Table"]:
+ name_val = name[0].as_py()
+ age_val = age[0].as_py()
+
+ status = "adult" if age_val >= 18 else "minor"
+
+ # Create struct array
+ person_array = pa.array(
+ [{"name": name_val, "age": age_val}],
+ type=pa.struct([("name", pa.string()), ("age", pa.int32())]),
+ )
+
+ result_table = pa.table(
+ {
+ "person": person_array,
+ "status": pa.array([status], type=pa.string()),
+ }
+ )
+ yield result_table
+
+ self.spark.udtf.register("person_status_udtf", PersonStatusUDTF)
+
+ result_df = self.spark.sql("SELECT * FROM person_status_udtf('John', 25)")
+ # Note: Using Row constructor for the expected struct value
+ expected_df = self.spark.createDataFrame(
+ [(Row(name="John", age=25), "adult")],
+ "person struct<name:string,age:int>, status string",
+ )
+ assertDataFrameEqual(result_df, expected_df)
+
+ def test_arrow_udtf_sql_conditional_yield(self):
+ @arrow_udtf(returnType="number int, type string")
+ class FilterNumbersUDTF:
+ def eval(self, start: "pa.Array", end: "pa.Array") -> Iterator["pa.Table"]:
+ start_val = start[0].as_py()
+ end_val = end[0].as_py()
+
+ numbers = []
+ types = []
+
+ for i in range(start_val, end_val + 1):
+ if i % 2 == 0: # Only yield even numbers
+ numbers.append(i)
+ types.append("even")
+
+ if numbers: # Only yield if we have data
+ result_table = pa.table(
+ {
+ "number": pa.array(numbers, type=pa.int32()),
+ "type": pa.array(types, type=pa.string()),
+ }
+ )
+ yield result_table
+
+ self.spark.udtf.register("filter_numbers_udtf", FilterNumbersUDTF)
+
+ result_df = self.spark.sql("SELECT * FROM filter_numbers_udtf(1, 10) ORDER BY number")
+ expected_df = self.spark.createDataFrame(
+ [(2, "even"), (4, "even"), (6, "even"), (8, "even"), (10, "even")],
+ "number int, type string",
+ )
+ assertDataFrameEqual(result_df, expected_df)
+
+ def test_arrow_udtf_sql_empty_result(self):
+ @arrow_udtf(returnType="value int")
+ class EmptyResultUDTF:
+ def eval(self, condition: "pa.Array") -> Iterator["pa.Table"]:
+ # Only yield if condition is true
+ if condition[0].as_py():
+ result_table = pa.table(
+ {
+ "value": pa.array([42], type=pa.int32()),
+ }
+ )
+ yield result_table
+ # If condition is false, don't yield anything
+
+ self.spark.udtf.register("empty_result_udtf", EmptyResultUDTF)
+
+ # Test with true condition
+ result_df_true = self.spark.sql("SELECT * FROM empty_result_udtf(true)")
+ expected_df_true = self.spark.createDataFrame([(42,)], "value int")
+ assertDataFrameEqual(result_df_true, expected_df_true)
+
+ # Test with false condition (empty result)
+ result_df_false = self.spark.sql("SELECT * FROM empty_result_udtf(false)")
+ expected_df_false = self.spark.createDataFrame([], "value int")
+ assertDataFrameEqual(result_df_false, expected_df_false)
+
+
+if __name__ == "__main__":
+ from pyspark.sql.tests.test_arrow_udtf import *
Review Comment:
nit: add this file in `modules.py`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org