spark-test commented on code in PR #59721:
URL: https://github.com/apache/spark/pull/59721#discussion_r4576756305


##########
python/pyspark/sql/transpile.py:
##########
@@ -1396,6 +1439,62 @@ def _get_function_from_ast(body: ast.AST, held_code: 
Any) -> Tuple[Optional[ast.
     )
 
 
+# The input categories a variety may report; mirrors ``optionMatchesTypes`` on 
the JVM.
+_VARIETY_CATEGORIES = frozenset(
+    ("integer", "float", "numeric", "string", "bool", "binary", "timestamp", 
"map", "array")

Review Comment:
   **Nit (P3):** Only `bool` and `numeric` are ever reported by a test 
variety's `(Column, list[str])` return, and the plain-Column tests take the 
combo label, which skips this check. If any of the other seven entries here 
were dropped or misspelled, a variety reporting it would be refused at UDF 
construction with an "unknown input categories" reason, the UDF would run as 
interpreted Python, and every test would still pass. For `timestamp`, `map`, 
and `array`, the rest of the path is untested from Python as well: the analyzer 
keeping the option for a matching column and `ConvertToCatalyst` substituting 
it are covered only by the Scala suite, with hand-built nodes.
   
   A table-driven test in which a variety reports each entry for a 
one-parameter UDF would cover the vocabulary, and one end-to-end test with a 
lowering that holds for every element type, such as `size` over a column of 
non-null arrays, would cover the new categories. Non-null matters there because 
under ANSI `size(NULL)` is NULL where Python's `len(None)` raises. The new 
categories' spelling in that test should follow whatever the container and 
timestamp decision challenges in this review settle on.
   
   **Verification:**
   - **Behavior:** A test variety that reports each vocabulary entry in turn 
for a one-parameter UDF gets one option labeled with exactly that entry.
   - **Behavior:** A UDF whose variety reports the array or map category for an 
element-agnostic lowering, applied to a matching column of non-null values, 
leaves no Python evaluation in the executed plan and returns the same values as 
the interpreted UDF; a timestamp case does the same for a zone-independent 
lowering, such as a null check, over the timestamp type the category matches.
   - **Regression:** Removing any entry from the Python category vocabulary, or 
the timestamp, map, or array case from the JVM matcher, makes one of the new 
tests fail.



##########
python/pyspark/sql/transpile.py:
##########
@@ -1396,6 +1439,62 @@ def _get_function_from_ast(body: ast.AST, held_code: 
Any) -> Tuple[Optional[ast.
     )
 
 
+# The input categories a variety may report; mirrors ``optionMatchesTypes`` on 
the JVM.
+_VARIETY_CATEGORIES = frozenset(
+    ("integer", "float", "numeric", "string", "bool", "binary", "timestamp", 
"map", "array")
+)
+
+
+def _variety_option(result: Any, combo: dict, num_params: int) -> 
Tuple[Column, List[str]]:
+    """Return the ``(column, categories)`` option for one 
``_transpile_from_ast`` result.
+
+    A plain :class:`Column` is labeled with ``combo``; a ``(Column, 
list[str])``
+    tuple keeps the variety's own categories. Malformed returns raise.
+    """
+    if isinstance(result, Column):
+        return result, [combo.get(i, "numeric") for i in range(num_params)]
+    if isinstance(result, tuple):
+        # Guard the shape before unpacking so a wrong-arity tuple reports a
+        # clear reason instead of an opaque "too many values to unpack".
+        if len(result) != 2:
+            raise UnsupportedOperationException(
+                f"transpiler returned a {len(result)}-element tuple; "
+                "expected (Column, list[str]) or None"
+            )
+        column, categories = result
+        # Declining is plain None; a None Column would surface a raw JVM NPE.
+        if not isinstance(column, Column):
+            raise UnsupportedOperationException(
+                "transpiler returned a (Column, list[str]) tuple whose first "
+                "element is not a Column; return None to decline"
+            )
+        # A non-list categories (e.g. a string) has a len and is iterable, so
+        # it would otherwise slip through as bogus per-char categories.

Review Comment:
   **Nit (P3):** The vocabulary check a few lines below now refuses a string's 
characters on its own, since every vocabulary entry is at least three 
characters long, so the case this comment names can no longer slip through. 
What this check still prevents is a tuple, dict, or set of valid names, each of 
which would pass every later check; a set would come back in arbitrary order 
and pair categories with the wrong parameters. As written, the comment makes 
the check look redundant. The comment in 
`test_udf_transpile_variety_non_list_categories_falls_back` repeats the same 
reason and could be reworded the same way.
   
   ```suggestion
           # Categories must be an ordered list, one per public param: a tuple, 
dict,
           # or set of valid names would pass the checks below, and a set's 
order is arbitrary.
   ```
   
   **Verification:**
   - **Inspection:** The comments for the non-list categories check, in the 
validation code and in its test, state that an ordered per-parameter list is 
required and no longer claim a string would pass as per-character categories.



##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -1561,6 +1561,471 @@ def _category_uncached(self, params, node):
         self.assertIsNotNone(converted)
         self.assertLessEqual(transpiler.category_calls, 
len(list(ast.walk(function_ast))))
 
+    def test_udf_transpile_variety_reports_own_categories(self):
+        # A (Column, list[str]) tuple labels the option with the categories the
+        # variety built, not the combo the caller asked about.
+        from pyspark.sql.functions import col
+        from pyspark.sql.transpile import AbstractTranspiler
+
+        class BoolOnlyTranspiler(AbstractTranspiler):
+            variety = "bool_only_55213"
+
+            def _transpile_from_ast(
+                self,
+                src,
+                ast_info,
+                function_ast,
+                params,
+                returnType,
+                param_categories=None,
+                held_code=None,
+            ):
+                return (
+                    col("_udf_param_0").cast(returnType),
+                    ["bool"] * len(params),
+                )
+
+        with self._with_variety(BoolOnlyTranspiler):
+
+            def add(a: int, b: int):
+                return a + b
+
+            u = self._transpiled_udf(add, LongType())
+            # The combo's integer guess (the only combo for two int-annotated
+            # params) must NOT label the option.
+            self.assertEqual([["bool", "bool"]], 
u._transpiled_input_categories)
+
+    def test_udf_transpile_variety_plain_column_falls_back_to_combo(self):
+        # A plain Column return (the existing contract) is labeled with the
+        # combo the caller asked about, not anything the variety invented.
+        from pyspark.sql.functions import col
+        from pyspark.sql.transpile import AbstractTranspiler
+
+        class NumericOnlyTranspiler(AbstractTranspiler):
+            variety = "numeric_only_55213"
+
+            def _transpile_from_ast(
+                self,
+                src,
+                ast_info,
+                function_ast,
+                params,
+                returnType,
+                param_categories=None,
+                held_code=None,
+            ):
+                return col("_udf_param_0").cast(returnType)
+
+        with self._with_variety(NumericOnlyTranspiler):
+
+            def add(a: int, b: int):
+                return a + b
+
+            u = self._transpiled_udf(add, LongType())
+            # Integer is the only combo for two int-annotated params.
+            self.assertEqual([["integer", "integer"]], 
u._transpiled_input_categories)
+
+    def test_udf_transpile_variety_tuple_with_none_column_falls_back(self):
+        # Declining is plain ``None``; a ``(None, categories)`` tuple is 
refused.
+        from pyspark.sql.transpile import AbstractTranspiler
+
+        class DeclineInTupleTranspiler(AbstractTranspiler):
+            variety = "decline_in_tuple_55213"
+
+            def _transpile_from_ast(
+                self,
+                src,
+                ast_info,
+                function_ast,
+                params,
+                returnType,
+                param_categories=None,
+                held_code=None,
+            ):
+                return (None, ["numeric"] * len(params))
+
+        with self._with_variety(DeclineInTupleTranspiler):
+
+            def add(a: int, b: int):
+                return a + b
+
+            _, reasons = self._fallback_reason(add, LongType())
+            self.assertIn("not a Column", reasons)
+
+    def test_udf_transpile_variety_malformed_return_falls_back(self):
+        from pyspark.sql.functions import col
+        from pyspark.sql.transpile import AbstractTranspiler
+
+        class ListReturningTranspiler(AbstractTranspiler):
+            variety = "list_returning_55213"
+
+            def _transpile_from_ast(
+                self,
+                src,
+                ast_info,
+                function_ast,
+                params,
+                returnType,
+                param_categories=None,
+                held_code=None,
+            ):
+                # A list, not a tuple: the documented shape is (Column, 
list[str]),
+                # and this is the natural slip.
+                return [col("_udf_param_0").cast(returnType), ["numeric"] * 
len(params)]
+
+        with self._with_variety(ListReturningTranspiler):
+
+            def add(a: int, b: int):
+                return a + b
+
+            _, reasons = self._fallback_reason(add, LongType())
+            self.assertIn("unsupported result", reasons)
+
+    def test_udf_transpile_variety_wrong_length_categories_falls_back(self):
+        # A wrong-length categories list is refused.
+        from pyspark.sql.functions import col
+        from pyspark.sql.transpile import AbstractTranspiler
+
+        class WrongLengthTranspiler(AbstractTranspiler):
+            variety = "wrong_length_55213"
+
+            def _transpile_from_ast(
+                self,
+                src,
+                ast_info,
+                function_ast,
+                params,
+                returnType,
+                param_categories=None,
+                held_code=None,
+            ):
+                # One category short of the two public params.
+                return (col("_udf_param_0").cast(returnType), ["numeric"])
+
+        with self._with_variety(WrongLengthTranspiler):
+
+            def add(a: int, b: int):
+                return a + b
+
+            _, reasons = self._fallback_reason(add, LongType())
+            self.assertIn("input categories", reasons)
+
+    def test_udf_transpile_variety_wrong_arity_tuple_falls_back(self):
+        # A tuple with the wrong number of elements is refused with a clear
+        # reason, not an opaque "too many values to unpack".
+        from pyspark.sql.functions import col
+        from pyspark.sql.transpile import AbstractTranspiler
+
+        class ThreeElementTupleTranspiler(AbstractTranspiler):
+            variety = "three_element_tuple_55213"
+
+            def _transpile_from_ast(
+                self,
+                src,
+                ast_info,
+                function_ast,
+                params,
+                returnType,
+                param_categories=None,
+                held_code=None,
+            ):
+                return (col("_udf_param_0").cast(returnType), ["numeric"] * 
len(params), "extra")
+
+        with self._with_variety(ThreeElementTupleTranspiler):
+
+            def add(a: int, b: int):
+                return a + b
+
+            _, reasons = self._fallback_reason(add, LongType())
+            self.assertIn("3-element tuple", reasons)
+
+    def test_udf_transpile_variety_non_list_categories_falls_back(self):
+        # A non-list categories (a string) has a len and is iterable, so
+        # without the isinstance check it would slip through as bogus chars.
+        from pyspark.sql.functions import col
+        from pyspark.sql.transpile import AbstractTranspiler
+
+        class StringCategoriesTranspiler(AbstractTranspiler):
+            variety = "string_categories_55213"
+
+            def _transpile_from_ast(
+                self,
+                src,
+                ast_info,
+                function_ast,
+                params,
+                returnType,
+                param_categories=None,
+                held_code=None,
+            ):
+                # "nu" has len 2 for the two public params -- passes the
+                # length check, but is not a list.
+                return (col("_udf_param_0").cast(returnType), "nu")
+
+        with self._with_variety(StringCategoriesTranspiler):
+
+            def add(a: int, b: int):
+                return a + b
+
+            _, reasons = self._fallback_reason(add, LongType())
+            self.assertIn("not a list", reasons)
+
+    def test_udf_transpile_variety_receives_held_code(self):
+        # ``held_code`` is the code object that runs when the UDF is called,
+        # passed alongside the AST form.
+        from pyspark.sql.functions import col
+        from pyspark.sql.transpile import AbstractTranspiler
+
+        seen = {}
+
+        class CodeSeeingTranspiler(AbstractTranspiler):
+            variety = "code_seeing_55213"
+
+            def _transpile_from_ast(
+                self,
+                src,
+                ast_info,
+                function_ast,
+                params,
+                returnType,
+                param_categories=None,
+                held_code=None,
+            ):
+                seen["function_ast"] = function_ast
+                seen["held_code"] = held_code
+                return (col("_udf_param_0").cast(returnType), ["numeric"] * 
len(params))
+
+        with self._with_variety(CodeSeeingTranspiler):
+
+            def add(a: int, b: int):
+                return a + b
+
+            self._transpiled_udf(add, LongType())
+            self.assertIsNotNone(seen["function_ast"])
+            self.assertIs(add.__code__, seen["held_code"])
+
+    def test_udf_transpile_bytecode_variety_handles_repl_function(self):
+        # An exec/REPL-defined UDF has no source (``function_ast`` is None)
+        # but its bytecode runs fine -- a bytecode variety still lowers it.
+        from pyspark.sql.functions import col
+        from pyspark.sql.transpile import AbstractTranspiler
+
+        seen = {}
+
+        class BytecodeOnlyTranspiler(AbstractTranspiler):
+            variety = "bytecode_only_55213"
+
+            def _transpile_from_ast(
+                self,
+                src,
+                ast_info,
+                function_ast,
+                params,
+                returnType,
+                param_categories=None,
+                held_code=None,
+            ):
+                seen["function_ast"] = function_ast
+                seen["held_code"] = held_code
+                return (col("_udf_param_0").cast(returnType), ["numeric"] * 
len(params))
+
+        ns: dict = {}
+        exec("def ident(a):\n    return a", ns)
+        ident = ns["ident"]
+        with self._with_variety(BytecodeOnlyTranspiler):
+            u = self._transpiled_udf(ident, LongType())
+            self.assertIsNone(seen["function_ast"])
+            self.assertIs(ident.__code__, seen["held_code"])
+            # The variety reports the same categories for every combo: one 
option.
+            self.assertEqual([["numeric"]], u._transpiled_input_categories)
+            from pyspark.sql.types import StructField, StructType
+
+            long_schema = StructType([StructField("a", LongType(), 
nullable=True)])
+            df = self.spark.createDataFrame([Row(a=41)], schema=long_schema)
+            projected = df.select(u("a"))
+            self.assertEqual(0, self._eval_python_count(projected))
+            self.assertEqual(projected.collect()[0][0], 41)
+
+    def test_udf_transpile_bytecode_variety_handles_wraps_decorated(self):
+        # A functools.wraps-decorated UDF's visible source is the WRAPPED
+        # function's, so the AST is withheld (``function_ast`` is None) -- but
+        # the wrapper's bytecode is what runs, and a bytecode variety may
+        # lower it. (With the built-in transpiler it still falls back.)
+        import functools
+
+        from pyspark.sql.functions import col
+        from pyspark.sql.transpile import AbstractTranspiler
+
+        seen = {}
+
+        class BytecodeVarietyTranspiler(AbstractTranspiler):
+            variety = "bytecode_wrapped_55213"
+
+            def _transpile_from_ast(
+                self,
+                src,
+                ast_info,
+                function_ast,
+                params,
+                returnType,
+                param_categories=None,
+                held_code=None,
+            ):
+                seen["function_ast"] = function_ast
+                seen["held_code"] = held_code
+                return (col("_udf_param_0").cast(returnType), ["numeric"] * 
len(params))
+
+        def base(x):
+            return x + 1
+
+        @functools.wraps(base)
+        def wrapper(x):
+            return base(x) * 10
+
+        with self._with_variety(BytecodeVarietyTranspiler):
+            self._transpiled_udf(wrapper, LongType())
+            self.assertIsNone(seen["function_ast"])

Review Comment:
   **Nit (P3):** This test records and asserts only `function_ast` and 
`held_code`, but the hook docstring promises that `src` and `ast_info` are None 
on the `functools.wraps` branch too. The code withholds them today. But 
`inspect.getsource` follows `__wrapped__`, so a later change that read the 
source before the wraps check, while still skipping the extraction, would hand 
varieties `base`'s source and module AST while the UDF runs `wrapper`. A 
variety lowering from `src` would then return 6 for an input of 5 where the 
interpreted UDF returns 60, and this test would still pass. So would 
`test_udf_transpile_falls_back_for_wraps_decorated_function`, because the 
built-in transpiler also needs `function_ast`. Recording `src` and `ast_info` 
in this variety's `_transpile_from_ast` as well, and asserting that all three 
are None as `test_udf_transpile_variety_gets_no_rejected_source` does, would 
close the gap.
   
   **Verification:**
   - **Regression:** A recording variety handed a functools.wraps-decorated UDF 
observes `src`, `ast_info`, and `function_ast` all as None and `held_code` as 
the wrapper's code object, so handing it the wrapped function's source or AST 
fails the test.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to