You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "fangchenli (via GitHub)" <gi...@apache.org> on 2026/01/03 22:29:50 UTC
[PR] [WIP][SPARK-54891](https://issues.apache.org/jira/browse/SPARK-54891) Unified type coercion for Arrow-backed Python UDFs [spark]
fangchenli opened a new pull request, #53666:
URL: https://github.com/apache/spark/pull/53666
<!--
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 implements unified type coercion for Arrow-backed Python UDF. It adds a `CoercionPolicy` option to the config and the coerce() methods to DataType classes to control type conversion behavior when Arrow optimization is enabled.
### 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.
-->
When Arrow optimization is enabled for Python UDFs, the type coercion behavior differs from that of the pickle-based UDFs. We need to control the coercion behavior for backward compatibility and to help migrations.
### 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. A new configuration spark.sql.execution.pythonUDF.coercion.policy is added with three options:
- PERMISSIVE: Matches pickle behavior - returns None for most type mismatches
- WARN: Same as PERMISSIVE but logs warnings when Arrow would behave differently
- STRICT: Arrow handles type conversion natively (original Arrow behavior)
With PERMISSIVE (default), users can enable Arrow optimization without behavior changes.
### 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.
-->
Both unit tests and integration tests were added
### 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.
-->
Generated-by: Claude Opus 4.5
--
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-54891] Unified type coercion for Arrow-backed Python UDFs [spark]
Posted by "fangchenli (via GitHub)" <gi...@apache.org>.
fangchenli closed pull request #53666: [SPARK-54891] Unified type coercion for Arrow-backed Python UDFs
URL: https://github.com/apache/spark/pull/53666
--
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] [WIP][SPARK-54891](https://issues.apache.org/jira/browse/SPARK-54891) Unified type coercion for Arrow-backed Python UDFs [spark]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #53666:
URL: https://github.com/apache/spark/pull/53666#issuecomment-3707413141
## JIRA Issue Information
=== Sub-task SPARK-54891 ===
Summary: Unified type coercion for Arrow-backed Python UDFs
Assignee: None
Status: Open
Affected: ["4.2.0"]
---
*This comment was automatically generated by GitHub Actions*
--
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-54891] Unified type coercion for Arrow-backed Python UDFs [spark]
Posted by "fangchenli (via GitHub)" <gi...@apache.org>.
fangchenli commented on PR #53666:
URL: https://github.com/apache/spark/pull/53666#issuecomment-3752882184
Close for now since coercion adds significant overhead.
--
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-54891] Unified type coercion for Arrow-backed Python UDFs [spark]
Posted by "gaogaotiantian (via GitHub)" <gi...@apache.org>.
gaogaotiantian commented on PR #53666:
URL: https://github.com/apache/spark/pull/53666#issuecomment-3712290867
I have some detail suggestions on the code itself but I want to wait until we have a further discussion about this feature (just to avoid wasting our time).
The current implementation (or the concept as its own) will introduce a non-trivial overhead for data conversion. For simple and common types like integer, bytes, strings, we introduced multiple python-level function calls to each element, which could result in a perf regression - to default behavior.
The implementation is not complete either I think? We need to handle this in all container types I assume?
I'd suggest that we discuss whether we want to implement this - if the benefit trumps the overhead in both perf and maintenance, before we start reviewing the code itself.
--
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-54891] Unified type coercion for Arrow-backed Python UDFs [spark]
Posted by "zhengruifeng (via GitHub)" <gi...@apache.org>.
zhengruifeng commented on code in PR #53666:
URL: https://github.com/apache/spark/pull/53666#discussion_r2660065753
##########
python/pyspark/worker.py:
##########
@@ -343,7 +365,7 @@ def evaluate(*args):
Takes list of Python objects and returns tuple of
(results, arrow_return_type, return_type).
"""
- return list(pool.map(lambda row: func(*row), get_args(*args)))
+ return list(pool.map(lambda row: coerce_result(func(*row)), get_args(*args)))
Review Comment:
I feel such coercion should happen in `serializers.py`
##########
python/pyspark/sql/types.py:
##########
@@ -1052,6 +1256,28 @@ def fromInternal(self, obj: List[Optional[T]]) -> List[Optional[T]]:
return obj
return obj and [self.elementType.fromInternal(v) for v in obj]
+ def coerce(self, value: Any, policy: "CoercionPolicy" = CoercionPolicy.PERMISSIVE) -> Any:
+ if value is None:
+ return None
+ # list -> array: exact match
+ if isinstance(value, list):
Review Comment:
should `elementType.coerce` be called here?
##########
python/pyspark/sql/types.py:
##########
@@ -1835,6 +2070,31 @@ def fromInternal(self, obj: Tuple) -> "Row":
values = obj
return _create_row(self.names, values)
+ def coerce(self, value: Any, policy: "CoercionPolicy" = CoercionPolicy.PERMISSIVE) -> Any:
Review Comment:
do we need call `fields[...].dataType.coerce` to handle children fields?
##########
python/pyspark/worker.py:
##########
@@ -311,6 +315,7 @@ def wrap_arrow_batch_udf(f, args_offsets, kwargs_offsets, return_type, runner_co
def wrap_arrow_batch_udf_arrow(f, args_offsets, kwargs_offsets, return_type, runner_conf):
Review Comment:
this code path is for arrow-optimized python udf without legcay pandas conversion, there is another path `wrap_arrow_batch_udf_legacy` for python udf with legcay pandas conversion
##########
python/pyspark/sql/types.py:
##########
@@ -1203,6 +1429,15 @@ def fromInternal(self, obj: Dict[T, Optional[U]]) -> Dict[T, Optional[U]]:
(self.keyType.fromInternal(k), self.valueType.fromInternal(v)) for k, v in obj.items()
)
+ def coerce(self, value: Any, policy: "CoercionPolicy" = CoercionPolicy.PERMISSIVE) -> Any:
Review Comment:
do we need to call `keyType.coerce` and `valueType.coerce`?
##########
python/pyspark/sql/tests/test_arrow_udf_coercion.py:
##########
@@ -0,0 +1,330 @@
+#
+# 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.
+#
+
+"""
+Integration tests for unified type coercion in Arrow-backed Python UDFs.
+
+These tests verify:
+1. PERMISSIVE policy: Arrow-enabled UDFs produce the same results as pickle-based UDFs
+2. WARN policy: Same as PERMISSIVE but with warnings (tested at unit level)
+3. STRICT policy: Arrow handles type conversion natively (no coercion applied)
+
+The goal is to ensure backward compatibility when enabling Arrow optimization.
+"""
+
+import array
+import datetime
+import re
+import unittest
+from decimal import Decimal
+
+from pyspark.sql import Row
+from pyspark.sql.functions import udf
+from pyspark.sql.types import (
+ ArrayType,
+ BinaryType,
+ BooleanType,
+ ByteType,
+ DateType,
+ DecimalType,
+ DoubleType,
+ FloatType,
+ IntegerType,
+ LongType,
+ MapType,
+ ShortType,
+ StringType,
+ StructField,
+ StructType,
+ TimestampType,
+)
+from pyspark.testing.utils import (
+ have_pyarrow,
+ have_pandas,
+ pyarrow_requirement_message,
+ pandas_requirement_message,
+)
+from pyspark.testing.sqlutils import ReusedSQLTestCase
+
+
+def normalize_result(value):
+ """Normalize result for comparison, handling Java object hash codes."""
+ result_str = repr(value)
+ # Normalize Java object hash codes to make tests deterministic
+ return re.sub(r"@[a-fA-F0-9]+", "@<hash>", result_str)
+
+
+@unittest.skipIf(
+ not have_pandas or not have_pyarrow,
+ pandas_requirement_message or pyarrow_requirement_message,
+)
+class ArrowUDFCoercionTests(ReusedSQLTestCase):
Review Comment:
new test files should be listed in `modules.py`, otherwise it won't take effect in pyspark
--
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-54891] Unified type coercion for Arrow-backed Python UDFs [spark]
Posted by "fangchenli (via GitHub)" <gi...@apache.org>.
fangchenli commented on PR #53666:
URL: https://github.com/apache/spark/pull/53666#issuecomment-3712560654
> I'd suggest that we discuss whether we want to implement this - if the benefit trumps the overhead in both perf and maintenance, before we start reviewing the code itself.
Thanks for the feedback. I'll benchmark it to determine the overhead.
--
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