You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by ru...@apache.org on 2023/08/08 03:10:39 UTC

[spark] branch branch-3.5 updated: [SPARK-44005][PYTHON] Improve error messages for regular Python UDTFs that return non-tuple values

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

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


The following commit(s) were added to refs/heads/branch-3.5 by this push:
     new b7a9b85716c [SPARK-44005][PYTHON] Improve error messages for regular Python UDTFs that return non-tuple values
b7a9b85716c is described below

commit b7a9b85716c7fb0aedb78bb8a04b00ba6c132d28
Author: allisonwang-db <al...@databricks.com>
AuthorDate: Tue Aug 8 11:09:58 2023 +0800

    [SPARK-44005][PYTHON] Improve error messages for regular Python UDTFs that return non-tuple values
    
    ### What changes were proposed in this pull request?
    
    This PR improves error messages for regular Python UDTFs when the result rows are not one of tuple, list and dict. Note this is supported when arrow optimization is enabled.
    
    ### Why are the changes needed?
    
    To make Python UDTFs more user friendly.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes.
    ```
    class TestUDTF:
        def eval(self, a: int):
            yield a
    ```
    Before this PR, this will fail with this error
    `Unexpected tuple 1 with StructType`
    
    After this PR, this will have a more user-friendly error:
    `[UDTF_INVALID_OUTPUT_ROW_TYPE] The type of an individual output row in the UDTF is invalid. Each row should be a tuple, list, or dict, but got 'int'. Please make sure that the output rows are of the correct type.`
    
    ### How was this patch tested?
    
    Existing UTs.
    
    Closes #42353 from allisonwang-db/spark-44005-non-tuple-return-val.
    
    Authored-by: allisonwang-db <al...@databricks.com>
    Signed-off-by: Ruifeng Zheng <ru...@apache.org>
    (cherry picked from commit 590b77f76284ad03ad8b3b6d30b23983c66513fc)
    Signed-off-by: Ruifeng Zheng <ru...@apache.org>
---
 python/pyspark/errors/error_classes.py |  5 +++++
 python/pyspark/sql/tests/test_udtf.py  | 26 +++++++++++---------------
 python/pyspark/worker.py               | 12 +++++++++---
 3 files changed, 25 insertions(+), 18 deletions(-)

diff --git a/python/pyspark/errors/error_classes.py b/python/pyspark/errors/error_classes.py
index 937a8758404..279812ebae1 100644
--- a/python/pyspark/errors/error_classes.py
+++ b/python/pyspark/errors/error_classes.py
@@ -733,6 +733,11 @@ ERROR_CLASSES_JSON = """
       "User defined table function encountered an error in the '<method_name>' method: <error>"
     ]
   },
+  "UDTF_INVALID_OUTPUT_ROW_TYPE" : {
+    "message" : [
+        "The type of an individual output row in the UDTF is invalid. Each row should be a tuple, list, or dict, but got '<type>'. Please make sure that the output rows are of the correct type."
+    ]
+  },
   "UDTF_RETURN_NOT_ITERABLE" : {
     "message" : [
       "The return value of the UDTF is invalid. It should be an iterable (e.g., generator or list), but got '<type>'. Please make sure that the UDTF returns one of these types."
diff --git a/python/pyspark/sql/tests/test_udtf.py b/python/pyspark/sql/tests/test_udtf.py
index 0540ecddde7..d152228fc52 100644
--- a/python/pyspark/sql/tests/test_udtf.py
+++ b/python/pyspark/sql/tests/test_udtf.py
@@ -139,24 +139,21 @@ class BaseUDTFTestsMixin:
         self.assertEqual(rows, [Row(a=1, b=2), Row(a=2, b=3)])
 
     def test_udtf_eval_returning_non_tuple(self):
+        @udtf(returnType="a: int")
         class TestUDTF:
             def eval(self, a: int):
                 yield a
 
-        func = udtf(TestUDTF, returnType="a: int")
-        # TODO(SPARK-44005): improve this error message
-        with self.assertRaisesRegex(PythonException, "Unexpected tuple 1 with StructType"):
-            func(lit(1)).collect()
+        with self.assertRaisesRegex(PythonException, "UDTF_INVALID_OUTPUT_ROW_TYPE"):
+            TestUDTF(lit(1)).collect()
 
-    def test_udtf_eval_returning_non_generator(self):
+        @udtf(returnType="a: int")
         class TestUDTF:
             def eval(self, a: int):
                 return (a,)
 
-        func = udtf(TestUDTF, returnType="a: int")
-        # TODO(SPARK-44005): improve this error message
-        with self.assertRaisesRegex(PythonException, "Unexpected tuple 1 with StructType"):
-            func(lit(1)).collect()
+        with self.assertRaisesRegex(PythonException, "UDTF_INVALID_OUTPUT_ROW_TYPE"):
+            TestUDTF(lit(1)).collect()
 
     def test_udtf_with_invalid_return_value(self):
         @udtf(returnType="x: int")
@@ -1159,21 +1156,20 @@ class UDTFArrowTestsMixin(BaseUDTFTestsMixin):
         self.spark.conf.set("spark.sql.execution.pythonUDTF.arrow.enabled", old_value)
 
     def test_udtf_eval_returning_non_tuple(self):
+        @udtf(returnType="a: int")
         class TestUDTF:
             def eval(self, a: int):
                 yield a
 
-        func = udtf(TestUDTF, returnType="a: int")
         # When arrow is enabled, it can handle non-tuple return value.
-        self.assertEqual(func(lit(1)).collect(), [Row(a=1)])
+        assertDataFrameEqual(TestUDTF(lit(1)), [Row(a=1)])
 
-    def test_udtf_eval_returning_non_generator(self):
+        @udtf(returnType="a: int")
         class TestUDTF:
             def eval(self, a: int):
-                return (a,)
+                return [a]
 
-        func = udtf(TestUDTF, returnType="a: int")
-        self.assertEqual(func(lit(1)).collect(), [Row(a=1)])
+        assertDataFrameEqual(TestUDTF(lit(1)), [Row(a=1)])
 
     def test_numeric_output_type_casting(self):
         class TestUDTF:
diff --git a/python/pyspark/worker.py b/python/pyspark/worker.py
index c9eedd43b29..f844a131455 100644
--- a/python/pyspark/worker.py
+++ b/python/pyspark/worker.py
@@ -665,9 +665,8 @@ def read_udtf(pickleSer, infile, eval_type):
             return_type_size = len(return_type)
 
             def verify_and_convert_result(result):
-                # TODO(SPARK-44005): support returning non-tuple values
-                if result is not None and hasattr(result, "__len__"):
-                    if len(result) != return_type_size:
+                if result is not None:
+                    if hasattr(result, "__len__") and len(result) != return_type_size:
                         raise PySparkRuntimeError(
                             error_class="UDTF_RETURN_SCHEMA_MISMATCH",
                             message_parameters={
@@ -675,6 +674,13 @@ def read_udtf(pickleSer, infile, eval_type):
                                 "actual": str(len(result)),
                             },
                         )
+
+                    if not (isinstance(result, (list, dict, tuple)) or hasattr(result, "__dict__")):
+                        raise PySparkRuntimeError(
+                            error_class="UDTF_INVALID_OUTPUT_ROW_TYPE",
+                            message_parameters={"type": type(result).__name__},
+                        )
+
                 return toInternal(result)
 
             # Evaluate the function and return a tuple back to the executor.


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