You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "holdenk (via GitHub)" <gi...@apache.org> on 2026/10/22 21:17:17 UTC

[PR] [SPARK-55213][PYTHON] Provide hooks for custom transpilers [spark]

holdenk opened a new pull request, #59721:
URL: https://github.com/apache/spark/pull/59721

   ### What changes were proposed in this pull request?
   
   SPARK-55213 asks for an internal API that lets accelerators (CUDA, cuDF, Rust, ...) plug in their own UDF transpilations with safe fallback semantics. This PR adds one of those hooks: a custom transpiler variety can now report the input categories its generated expression actually needs, instead of being labeled with the input-type combo the caller guessed.
   
   `_transpile_func` labeled every transpiled UDF option with the input-type combo it *asked* the variety about, not the categories the option the variety *built* actually needs. A variety that works out its own input types (e.g. one that reads the function's annotations and supports types the combo enum does not cover) had no way to report them, so its option was matched against the caller's guess. Without this, every new type a variety supports is another entry in a fixed category enum.
   
   This widens `AbstractTranspiler._transpile_from_ast`'s return type to `Optional[Union[Column, Tuple[Column, List[str]]]]`:
   - A plain `Column` keeps the existing contract (the option is labeled with the `param_categories` combo the caller passed in).
   - A `(Column, list[str])` tuple reports the option's own per-public-param categories (`"numeric"` / `"string"` / `"bool"` / `"binary"`); the caller uses them when present and falls back to the combo otherwise, so existing varieties do not move.
   - To decline, return plain `None` (not inside a tuple).
   
   The caller validates the variety's return shape before trusting it; anything malformed is refused so the UDF falls back to interpreted Python with a reason rather than breaking at call time:
   - A return that is neither a `Column` nor a `(Column, list[str])` tuple (e.g. a bare list by typo) is refused. It would otherwise surface a raw JVM error at UDF-call time.
   - A tuple whose first element is not a `Column` (including `(None, categories)`) is refused. Appending a `None` Column would surface a raw JVM NPE at call time, and a variety that built categories but no column is a bug worth surfacing, not a silent decline.
   - A tuple with the wrong arity (not exactly two elements) is refused with a clear reason, rather than an opaque "too many values to unpack".
   - A non-list `categories` (e.g. a string) is refused; without the check a string of the right length would slip through `len()`/`list()` as bogus per-character categories.
   - A categories list whose length differs from the public param count is refused. The JVM's all-or-nothing length guard would otherwise silently drop every variety's options.
   
   `AbstractTranspiler` is experimental, so the signature is cheap to change now and less so once there are more varieties.
   
   ### Why are the changes needed?
   
   This is a step toward SPARK-55213's goal of providing hooks for custom transpilers: an internal API that lets accelerators (CUDA, cuDF, Rust, ...) add their own UDF transpilations with safe fallback semantics. A variety that derives its own input types -- e.g. an out-of-tree one that reads the function's annotations and supports types the combo enum does not cover -- is currently matched against the caller's combo guess, and every new type it supports forces another entry in the category enum. Letting the variety report its own categories decouples the option from the caller's guess and keeps the enum from growing per type. The shape/length validation is the "safe fallback" half of the JIRA: a buggy variety falls back to interpreted Python with a reason instead of breaking a working UDF or silently disabling other varieties' options.
   
   ### Does this PR introduce _any_ user-facing change?
   
   No. `AbstractTranspiler` and `_transpile_from_ast` are experimental internal APIs behind `spark.sql.experimental.optimizer.transpilePyUDFs`. The shipped `CatalystTranspiler` continues to return a plain `Column`, so its behavior is unchanged; only out-of-tree experimental varieties opt into the new tuple form.
   
   ### How was this patch tested?
   
   New unit tests in `python/pyspark/sql/tests/test_udf_transpile_unit.py`:
   - `test_udf_transpile_variety_reports_own_categories` — a custom variety returns `(Column, ["bool","bool"])`; asserts `_transpiled_input_categories` is `[["bool","bool"]]`, not the combo's numeric guess.
   - `test_udf_transpile_variety_plain_column_falls_back_to_combo` — a plain-`Column` variety is labeled with the combo (existing contract preserved).
   - `test_udf_transpile_variety_tuple_with_none_column_falls_back` — a variety returning `(None, categories)` is refused as malformed (not a silent decline) and the UDF falls back to interpreted Python with a reason.
   - `test_udf_transpile_variety_malformed_return_falls_back` — a variety returning a bare list is refused and falls back.
   - `test_udf_transpile_variety_wrong_length_categories_falls_back` — a variety whose categories list is the wrong length is refused and falls back.
   - `test_udf_transpile_variety_wrong_arity_tuple_falls_back` — a 3-element tuple is refused with a clear reason, not an opaque unpack error.
   - `test_udf_transpile_variety_non_list_categories_falls_back` — a string `categories` is refused instead of slipping through as bogus per-character categories.
   
   `spark-presend --fast` green: static checks 0 errors, `dev/check-license` OK, `dev/lint-python` OK, and `test_udf_transpile_unit`, `test_udf_transpile_hypothesis` (`RUN_HYPOTHESIS=1`, 200 examples), and `test_udf_transpile_parity` all pass.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Cursor, Claude (GLM 5.2)
   


-- 
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-55213][PYTHON] Provide hooks for custom transpilers [spark]

Posted by "holdenk (via GitHub)" <gi...@apache.org>.
holdenk closed pull request #59721: [SPARK-55213][PYTHON] Provide hooks for custom transpilers
URL: https://github.com/apache/spark/pull/59721


-- 
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-55213][PYTHON] Provide hooks for custom transpilers [spark]

Posted by "spark-test (via GitHub) via reviews" <re...@spark.apache.org>.
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: 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-55213][PYTHON] Provide hooks for custom transpilers [spark]

Posted by "spark-test (via GitHub)" <gi...@apache.org>.
spark-test commented on code in PR #59721:
URL: https://github.com/apache/spark/pull/59721#discussion_r4419992746


##########
python/pyspark/sql/transpile.py:
##########
@@ -1379,22 +1497,25 @@ def _transpile_func(
         for transpiler in transpilers:
             for combo in combos:
                 try:
-                    transpiled_column = transpiler._transpile_from_ast(
-                        src, ast_info, function_ast, public_params, returnType, combo
+                    result = transpiler._transpile_from_ast(
+                        src, ast_info, function_ast, public_params, returnType, combo, held_code
                     )
-                    if transpiled_column is not None:
-                        transpiled.append(transpiled_column)
-                        input_categories.append(
-                            [combo.get(i, "numeric") for i in range(len(public_params))]
-                        )
+                    if result is not None:
+                        column, categories = _variety_option(result, combo, len(public_params))
+                        transpiled.append(column)

Review Comment:
   **Nit (P3):** With the tuple return, a variety that works out its own categories returns the same `(Column, categories)` for every `combo`, and each one is appended. The new REPL test already pins `[["numeric"], ["numeric"]]` for a one-parameter UDF, and a three-parameter UDF without an AST (all parameters untyped, so 8 combos) gets 8 identical options from one variety. Only the first can ever be used: `optionMatchesTypes` depends only on the categories and argument types, so the copies survive or prune together, and `ConvertToCatalyst` substitutes the head survivor. The others are still shipped over Py4J, placeholder-rewritten, resolved and coerced on every application, and the variety's lowering repeats per combo, which works against the "one transpiled option per (backend x input-type variant)" intent stated above.
   
   Skipping the append when this variety has already contributed an option with the same categories keeps option order and selection unchanged. It would also help to say in the `_transpile_from_ast` docstring that the hook is called once per combo.
   
   **Verification:**
   - **Regression:** An exec-defined one-parameter UDF lowered by a self-categorizing variety carries a single ['numeric'] option, and a three-parameter one carries one option instead of eight.
   - **Behavior:** A variety whose categories differ per combo still contributes one option per distinct category list, in the original order, and the built-in transpiler's options for untyped parameters are unchanged.



##########
python/pyspark/sql/transpile.py:
##########
@@ -1205,6 +1247,49 @@ def _get_function_from_ast(body: ast.AST, held_code: Any) -> Tuple[Optional[ast.
     )
 
 
+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.
+        if not isinstance(categories, list):
+            raise UnsupportedOperationException(
+                "transpiler returned categories that are not a list"
+            )
+        # The JVM drops the WHOLE option set on a length mismatch, so a
+        # wrong-length list would silently neuter every variety.
+        if len(categories) != num_params:
+            raise UnsupportedOperationException(
+                f"transpiler returned {len(categories)} input categories for "
+                f"{num_params} parameters"
+            )
+        return column, list(categories)

Review Comment:
   **Nit (P3):** `categories` is checked for type and length but not for its contents, so values outside the vocabulary documented on the hook get through:
   
   - A non-string element, e.g. `(col("_udf_param_0").cast(returnType), [LongType()])`, is stored and only fails when the UDF is called: `_judf` -> `_create_judf` hands the nested list to Py4J (`auto_convert=True`), whose `ListConverter` adds the `DataType`, and `get_command_part` then calls `_get_object_id()` on it, raising `AttributeError` on every call. That is the call-time break the shape checks above are meant to prevent.
   - An out-of-vocabulary string (`'Numeric'`, `'int'`) or `None` is accepted, so no fallback reason is recorded, and `optionMatchesTypes` later drops the option through `case _ => false`, silently disabling the variety.
   
   Checking here that every element is a `str` from the documented vocabulary, and raising the same `UnsupportedOperationException` as the other checks, would turn both into recorded fallbacks.
   
   **Verification:**
   - **Regression:** A variety that returns a DataType object as a category is refused with a reason at UDF construction, and calling the UDF runs interpreted Python instead of failing while the JVM UDF is created.
   - **Regression:** A variety that returns an out-of-vocabulary string such as 'Numeric' is refused with a reason, rather than producing an option the analyzer drops silently.
   - **Behavior:** Every documented category value is still accepted and labels its option as returned.



##########
python/pyspark/sql/transpile.py:
##########
@@ -1256,62 +1341,93 @@ def _transpile_func(
                 [],
                 [],
             )
+        # Hand each transpiler whatever could be extracted: the AST from the
+        # source on disk when it is trustworthy, and the code object that
+        # actually runs (``held_code``) when there is one. A transpiler declines
+        # when the form it needs is missing -- the built-in lowering works from
+        # the AST, a numba-style variety from the bytecode -- so an extraction
+        # failure is recorded as a reason for the fallback warning, not refused
+        # outright. Only BOTH missing means there is nothing to lower from.
+        held_code = _held_code(func)
+        src = None
+        ast_info = None
+        function_ast = None
+        errors: List[str] = []
         # A functools.wraps-style decorator makes ``inspect.getsource`` return
         # the WRAPPED function's source (getsource follows ``__wrapped__``),
-        # while the UDF actually executes the wrapper. Transpiling would
-        # silently reproduce the wrong behavior, so refuse and fall back.
+        # while the UDF actually executes the wrapper -- the AST is a lie, but
+        # ``held_code`` is exactly what runs.
         # ``_call_impl`` first: a ``staticmethod`` / ``classmethod`` exposes a
-        # ``__wrapped__`` of its own, so asking the descriptor refuses every one of
-        # them for a wraps decorator that is not there.
+        # ``__wrapped__`` of its own, so asking the descriptor distrusts every
+        # one of them for a wraps decorator that is not there.
         if (
             getattr(func, "__wrapped__", None) is not None
             or getattr(_call_impl(_call_dunder(func)), "__wrapped__", None) is not None
         ):
+            errors.append(
+                "a functools.wraps decorator makes the visible source the wrapped "
+                "function's, not the wrapper's; only the bytecode is trustworthy"
+            )
+        else:
+            # Not ``ast``: that name would shadow the module for this function.
+            src, ast_info = _get_src_ast_from_func(func)
+            if ast_info is None:
+                errors.append("Error getting ast for function")
+            else:
+                # Get the lambda body and parameters
+                function_ast, extraction_error = _get_function_from_ast(ast_info, held_code)
+                if function_ast is None:
+                    errors.append(extraction_error)

Review Comment:
   **Non-blocking (P2):** When `_get_function_from_ast` rejects the source, only the reason is recorded here: `src` and `ast_info` keep the rejected source, and since every Python function has a `held_code`, the varieties below are now called with it (and `function_ast=None`). Before this PR this path returned before any transpiler ran.
   
   That contradicts the new hook docstring, which says `src` / `ast_info` / `function_ast` are `None` when no trustworthy source exists. For example, `make_adder = lambda n: lambda x: x + n; add_three = make_adder(3)` is rejected because the located lambda takes `n`, not `x` (the existing test around `test_udf_transpile_unit.py:2631` pins this), but a variety now receives `src='make_adder = lambda n: lambda x: x + n'` and its module AST. A variety that trusts a non-None `ast_info` can then lower the outer lambda instead of the one that runs, which is exactly what the SPARK-58650 check guards against. The built-in `CatalystTranspiler` is only safe because it also checks `function_ast`.
   
   Suggest resetting `src` and `ast_info` to `None` here too, matching the `functools.wraps` branch, which never hands the untrusted source over.
   
   **Verification:**
   - **Regression:** A recording variety handed an ambiguous lambda (one lambda returned by another on a single line) observes src, ast_info, and function_ast as None, and held_code as the held lambda's code object.
   - **Behavior:** With only the built-in transpiler configured, the same ambiguous lambda still falls back to interpreted Python with its parameter-mismatch reason and no transpiled parameter names.



##########
python/pyspark/sql/transpile.py:
##########
@@ -1256,62 +1341,93 @@ def _transpile_func(
                 [],
                 [],
             )
+        # Hand each transpiler whatever could be extracted: the AST from the
+        # source on disk when it is trustworthy, and the code object that
+        # actually runs (``held_code``) when there is one. A transpiler declines
+        # when the form it needs is missing -- the built-in lowering works from
+        # the AST, a numba-style variety from the bytecode -- so an extraction
+        # failure is recorded as a reason for the fallback warning, not refused
+        # outright. Only BOTH missing means there is nothing to lower from.
+        held_code = _held_code(func)
+        src = None
+        ast_info = None
+        function_ast = None
+        errors: List[str] = []
         # A functools.wraps-style decorator makes ``inspect.getsource`` return
         # the WRAPPED function's source (getsource follows ``__wrapped__``),
-        # while the UDF actually executes the wrapper. Transpiling would
-        # silently reproduce the wrong behavior, so refuse and fall back.
+        # while the UDF actually executes the wrapper -- the AST is a lie, but
+        # ``held_code`` is exactly what runs.
         # ``_call_impl`` first: a ``staticmethod`` / ``classmethod`` exposes a
-        # ``__wrapped__`` of its own, so asking the descriptor refuses every one of
-        # them for a wraps decorator that is not there.
+        # ``__wrapped__`` of its own, so asking the descriptor distrusts every
+        # one of them for a wraps decorator that is not there.
         if (
             getattr(func, "__wrapped__", None) is not None
             or getattr(_call_impl(_call_dunder(func)), "__wrapped__", None) is not None
         ):
+            errors.append(
+                "a functools.wraps decorator makes the visible source the wrapped "
+                "function's, not the wrapper's; only the bytecode is trustworthy"
+            )
+        else:
+            # Not ``ast``: that name would shadow the module for this function.
+            src, ast_info = _get_src_ast_from_func(func)
+            if ast_info is None:
+                errors.append("Error getting ast for function")
+            else:
+                # Get the lambda body and parameters
+                function_ast, extraction_error = _get_function_from_ast(ast_info, held_code)
+                if function_ast is None:
+                    errors.append(extraction_error)
+        if function_ast is None and held_code is None:
             return (
                 [],
-                [
-                    "decorated callables (functools.wraps) are not supported: "
-                    "the visible source is the wrapped function's, not the "
-                    "wrapper's, so transpilation would change behavior"
-                ],
+                errors + ["and no bytecode is available either, cannot transpile"],
                 [],
                 [],
                 [],
             )
-        # Not ``ast``: that name would shadow the module for this whole function.
-        src, ast_info = _get_src_ast_from_func(func)
-        if ast_info is None:
-            return ([], ["Error getting ast for function, cannot transpile"], [], [], [])
-        # Get the lambda body and parameters
-        function_ast, extraction_error = _get_function_from_ast(ast_info, _held_code(func))
-        if function_ast is None:
-            return ([], [extraction_error], [], [], [])
         # Default, variadic (``*args`` / ``**kwargs``) and keyword-only params
         # can't be represented by the positional ``_udf_param_N`` placeholder
         # scheme: a call site may omit a defaulted argument, leaving the
         # placeholder referencing a position the call never bound. A
         # positional-only param has no such gap -- it is always bound by
-        # position -- so it is not refused here; a DEFAULTED one still hits
-        # ``fn_args.defaults`` above.
-        fn_args = function_ast.args
-        if (
-            fn_args.defaults
-            or any(d is not None for d in fn_args.kw_defaults)
-            or fn_args.kwonlyargs
-            or fn_args.vararg is not None
-            or fn_args.kwarg is not None
-        ):
+        # position -- so it is not refused here; a DEFAULTED one still hits the
+        # check below. The check runs on the AST when there is one, on the code
+        # object otherwise: ``__defaults__`` / ``__kwdefaults__`` live on the
+        # function, the variadic and keyword-only counts on its code object.
+        if function_ast is not None:
+            fn_args = function_ast.args
+            unsupported_params = bool(
+                fn_args.defaults
+                or any(d is not None for d in fn_args.kw_defaults)
+                or fn_args.kwonlyargs
+                or fn_args.vararg is not None
+                or fn_args.kwarg is not None
+            )
+        else:
+            owner = _code_owner(func)
+            unsupported_params = bool(
+                getattr(owner, "__defaults__", None)
+                or getattr(owner, "__kwdefaults__", None)
+                or held_code.co_kwonlyargcount

Review Comment:
   **Nit (P3):** Of the code-object checks in this branch, only `__defaults__` has a test (`test_udf_transpile_repl_function_with_defaults_falls_back`). The existing keyword-only/variadic fallback cases and the positional-only keyword-call test use file-defined functions, so they take the AST branch instead.
   
   If `co_kwonlyargcount` were dropped here, an `exec`-defined `def f(a, *, b): return a` would get params `['a']`, a variety's one-category option would pass the builder's arity check for `u(df.a)`, and the lowered option would be served where Python raises `TypeError` for the missing keyword-only argument. Likewise, if the no-AST positional-only names further down (`params[: held_code.co_posonlyargcount]`) came back empty, the kwargs rewrite in `udf.py` would turn `u(a=df.a)` on an `exec`-defined `def f(a, /)` into a positional call that Python itself rejects. The suite would stay green in both cases.
   
   See **Shared repair plan 1** in the review body.



##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -1539,6 +1539,366 @@ 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 numeric 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())
+            # Numeric is the only combo for two int-annotated params.
+            self.assertEqual([["numeric", "numeric"]], 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"])
+            # One untyped param from the code object: numeric and string combos.
+            self.assertEqual([["numeric"], ["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)
+            [result] = df.select(u("a")).collect()
+            self.assertEqual(result[0], 41)

Review Comment:
   **Nit (P3):** `ident` returns its input and the option is `cast(_udf_param_0 as bigint)`, so 41 comes back whether the option was substituted or the Python UDF ran. The comment above says the bytecode variety "still lowers" the UDF, but as the `_vals` helper notes, produced options do not prove the JVM used them. Asserting `self._eval_python_count(...) == 0` on the selected DataFrame, as `_vals` does, would give the new no-AST path a real failure signal.
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/ResolveTranspiledPythonUDFOptionsSuite.scala:
##########
@@ -92,4 +92,48 @@ class ResolveTranspiledPythonUDFOptionsSuite extends PlanTest {
     val pruned = prune(node, LocalRelation(a))
     assert(pruned.transpiledOptions == List(onlyOpt))
   }
+
+  test("keeps the timestamp option for a timestamp column and drops the numeric one") {
+    val a = $"a".timestamp
+    val tsOpt = a
+    val numOpt = Add(a, Literal(1L))
+    val node = TranspiledPythonUDF("udf", pyUDF(Seq(a)), List(tsOpt, numOpt),
+      List(List("timestamp"), List("numeric")))
+    val pruned = prune(node, LocalRelation(a))
+    assert(pruned.transpiledOptions == List(tsOpt))
+    assert(pruned.optionInputCategories.isEmpty)
+  }
+
+  test("keeps the array option for an array column and drops the numeric one") {
+    val a = $"a".array(StringType)
+    val arrOpt = a
+    val numOpt = Add(a, Literal(1L))
+    val node = TranspiledPythonUDF("udf", pyUDF(Seq(a)), List(arrOpt, numOpt),
+      List(List("array"), List("numeric")))
+    val pruned = prune(node, LocalRelation(a))
+    assert(pruned.transpiledOptions == List(arrOpt))
+    assert(pruned.optionInputCategories.isEmpty)
+  }
+
+  test("keeps the map option for a map column and drops the string one") {

Review Comment:
   **Nit (P3):** These cases only cover the accepting side of the new `map`/`array` matches: the options that get dropped are labeled `numeric`/`string`, which fall through on their own. If `case ("map", dt) => dt.isInstanceOf[MapType]` were widened to accept any type, or `"array"` also matched `MapType`, every test in this suite would still pass, and a container-labeled option kept over the wrong column type would fail the query at CheckAnalysis instead of falling back to the Python UDF. Negative cases in the style of the timestamp-vs-long test below would close the gap.
   
   **Verification:**
   - **Regression:** A 'map'-labeled option is dropped for ArrayType and LongType arguments, and an 'array'-labeled option is dropped for MapType and LongType arguments, leaving no options.



-- 
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-55213][PYTHON] Provide hooks for custom transpilers [spark]

Posted by "spark-test (via GitHub) via reviews" <re...@spark.apache.org>.
spark-test commented on code in PR #59721:
URL: https://github.com/apache/spark/pull/59721#discussion_r4690596101


##########
python/pyspark/sql/transpile.py:
##########
@@ -1217,40 +1511,67 @@ def _annotation_category(annotation: Optional[ast.AST]) -> Optional[str]:
         return "bool"
     if name == "bytes":
         return "binary"
+    if name in ("dict", "Dict", "Mapping"):
+        return "map"
+    if name in ("list", "List"):
+        return _array_annotation_category(annotation)
     return None
 
 
-def _param_category_combos(function_ast: ast.FunctionDef, public_params: List[str]) -> List[dict]:
+def _annotation_candidates(annotation: Optional[ast.AST]) -> List[str]:
+    """The categories to try for a parameter with this annotation.
+
+    A pinning annotation yields its one category. ``Sequence`` yields both an
+    array category (element-aware as for ``list``) and ``"string"``: a ``str``
+    is a ``Sequence`` too, so pinning it to an array alone would drop the option
+    a string column matches. Anything else is untyped and is tried as each
+    numeric and string variant."""
+    annotation = _strip_optional(annotation)
+    cat = _annotation_category(annotation)
+    if cat is not None:
+        return [cat]

Review Comment:
   **Blocking (P1):** With transpilation on, `def f(x: Optional[float]): return x * 2.0` declared DOUBLE and applied to a BIGINT column lowers on the base branch: `Optional[float]` is unrecognised there, so the parameter is tried as integer, float and string, and the integer option matches BIGINT. Here `_strip_optional` reduces the annotation to `float`, this line returns `['float']` as its only candidate, `categoryMatches('float', LongType)` is false, the analyzer empties the options and `ConvertToCatalyst` keeps the Python UDF, so by this reading of the code every row goes through a Python worker. The same happens for `float | None` over INT, `Optional[int]` over DOUBLE, `dict` or `list` over a scalar column the body ignores (the new `test_udf_transpile_map_and_array_input_categories` asserts that fallback for a STRING column), and `Sequence` over a numeric column. v4.3.0's `transpile.py` also treats these annotations as untyped.
   
   Results match wherever the native lowering agreed with Python, but the cost now grows with the rows processed. A stateful streaming query whose state key holds such a UDF's output over non-nullable inputs can also fail to restart from a checkpoint the native plan wrote: the Python result is nullable, and `StateSchemaCompatibilityChecker` rejects a key field that becomes nullable. The PR description says the shipped Catalyst lowering is unchanged, and nothing states this trade-off.
   
   See **Shared repair plan 1** in the review body.



##########
python/pyspark/sql/transpile.py:
##########
@@ -1217,40 +1511,67 @@ def _annotation_category(annotation: Optional[ast.AST]) -> Optional[str]:
         return "bool"
     if name == "bytes":
         return "binary"
+    if name in ("dict", "Dict", "Mapping"):
+        return "map"
+    if name in ("list", "List"):
+        return _array_annotation_category(annotation)
     return None
 
 
-def _param_category_combos(function_ast: ast.FunctionDef, public_params: List[str]) -> List[dict]:
+def _annotation_candidates(annotation: Optional[ast.AST]) -> List[str]:
+    """The categories to try for a parameter with this annotation.
+
+    A pinning annotation yields its one category. ``Sequence`` yields both an
+    array category (element-aware as for ``list``) and ``"string"``: a ``str``
+    is a ``Sequence`` too, so pinning it to an array alone would drop the option
+    a string column matches. Anything else is untyped and is tried as each
+    numeric and string variant."""
+    annotation = _strip_optional(annotation)
+    cat = _annotation_category(annotation)
+    if cat is not None:
+        return [cat]
+    if _annotation_name(annotation) == "Sequence":
+        return [_array_annotation_category(annotation), "string"]
+    return ["integer", "float", "string"]
+
+
+def _param_category_combos(
+    function_ast: Optional[ast.FunctionDef], public_params: List[str]
+) -> List[dict]:
     """Per-variant maps ``{public_param_index -> category}``.
 
     A typed param (``def f(a: str, b: int)``) is pinned to its category
-    (``"integer"``/``"float"``/``"string"``/``"bool"``/``"binary"``); an
+    (``"integer"``/``"float"``/``"string"``/``"bool"``/``"binary"``/
+    ``"map"``/``"array"``/``"array<c>"``); an
     untyped param is tried as ``"integer"``, ``"float"``, and ``"string"``
     separately so the JVM can select the variant that matches the bound column
-    type and apply the right NaN semantics. To cap plan growth, when more than
-    three params are untyped we collapse the untyped ones to one variant per
-    base category (encourage typing inputs to keep the matrix small) while
-    keeping every typed param pinned.
+    type and apply the right NaN semantics. A ``Sequence`` param is tried as
+    ``"array"`` and ``"string"``. To cap plan growth, when more than three
+    params are unpinned (untyped or ``Sequence``) we collapse them to one
+    variant per base category (encourage typing inputs to keep the matrix
+    small) while keeping every typed param pinned. A param that cannot take a
+    fill keeps its first candidate instead, so a ``Sequence`` param still gets
+    its array option. A ``None`` ``function_ast`` means no trustworthy source,
+    hence no annotations: every param is untyped.
     """
     n = len(public_params)
-    all_args = _positional_args(function_ast)
-    public_args = all_args[len(all_args) - n :]
-    candidates: List[List[str]] = []
-    untyped = 0
-    for arg in public_args:
-        cat = _annotation_category(arg.annotation)
-        if cat is None:
-            candidates.append(["integer", "float", "string"])
-            untyped += 1
-        else:
-            candidates.append([cat])
-    if untyped > 3:
-        # Cap the 3**untyped blow-up; collapse untyped params to one variant
-        # per base fill while keeping typed params pinned.
-        return [
-            {i: c[0] if len(c) == 1 else fill for i, c in enumerate(candidates)}
-            for fill in ("integer", "float", "string")
-        ]
+    if function_ast is None:
+        candidates = [_annotation_candidates(None) for _ in range(n)]
+    else:
+        all_args = _positional_args(function_ast)
+        public_args = all_args[len(all_args) - n :]
+        candidates = [_annotation_candidates(arg.annotation) for arg in public_args]
+    unpinned = sum(1 for c in candidates if len(c) > 1)

Review Comment:
   **Nit (P3):** On the base branch `def f(a: Optional[int], b, c, d)` counts four untyped parameters and is capped at the all-integer, all-float and all-string fills. `Optional[int]` now has a single candidate, so `unpinned` is three, the cap does not apply, and a body such as `a + 1` gets the full 27-combo product: 27 lowerings when the UDF is defined, 27 options converted by `UserDefinedPythonFunction.builder` on every call and 27 option subtrees walked on every analysis, where the base branch built at most three. The cost is bounded and never per row, and the option chosen for uniform column types is the same, but neither the description nor the docstrings mention it. `dict` and `list` parameters behave the same way.
   
   See **Shared repair plan 1** in the review body.



##########
python/pyspark/sql/transpile.py:
##########
@@ -30,10 +30,23 @@
 untyped parameter is transpiled into one option per input-type category
 (numeric and string) and the JVM picks the one matching the bound column
 types -- falling back to interpreted Python when none fit. Annotating the
-UDF's parameters (e.g. ``def f(a: int, b: str)``) pins each category and
-keeps the option matrix small; prefer doing so. To bound plan growth,
-functions with more than three untyped parameters only emit the
-all-numeric and all-string variants.
+UDF's parameters (e.g. ``def f(a: int, b: str)``) pins each category --
+numeric, string, bool, binary, or map/array for dict/list annotations --
+and keeps the option matrix small; prefer doing so. A ``Sequence``
+annotation is tried as both array and string, since a ``str`` is one too.
+``Optional[X]`` pins what ``X`` does. To bound plan growth, functions with
+more than three unpinned (untyped or ``Sequence``) parameters only emit the
+all-integer, all-float and all-string fills of those parameters; typed
+parameters stay pinned.
+
+A ``list`` annotation that names its element type (``list[int]``,
+``List[str]``, ``list[list[bytes]]``) yields an element-aware category such as
+``array<integer>``, matched only by an array column whose elements match too.
+Knowing the elements lets ``==`` / ``!=`` on two such arrays (or one and
+``None``) lower to Spark's ``=`` when the elements are integer, string, bool or
+binary, and lets an if/else choose between two arrays of one category. A bare

Review Comment:
   **Nit (P3):** Three statements in these paragraphs (lines 33-49) do not match the code. A `Sequence` parameter cannot take the integer or float fill, so `_param_category_combos` keeps its array category under those fills (line 1571, as `test_param_category_combos_sequence_is_array_or_string` pins), not "the all-integer, all-float and all-string fills of those parameters". An if/else between two arrays of one category is refused when their innermost element is a map or a bare array, as for two `list[dict]` branches, because `_convert_if_like` checks `_SCALAR_ELEMENT_CATS`. And the sentence that a bare `list`, float elements and ordering stay interpreted holds only for `==`, `!=` and ordering: `is None` lowers on a bare list and on any map, and an if/else over two `list[float]` arrays lowers, since `float` is in `_SCALAR_ELEMENT_CATS`. The `==` sentence also leaves out nested arrays of integer, string, bool or binary elements, which lower. Stating the cap rule for `Sequence` paramet
 ers and the `==` and if/else rules separately would fix it.
   
   **Verification:**
   - **Inspection:** The transpiler module docstring says a Sequence parameter keeps its array category under the integer and float fills of a capped function, that == and != on element-aware arrays lower when the innermost elements are integer, string, bool or binary, nested arrays included, that an if/else lowers between two arrays of one category whose innermost elements are integer, float, string, bool or binary, or one such array and None, and that is None lowers on any array or map.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveTranspiledPythonUDFOptions.scala:
##########
@@ -97,23 +120,93 @@ object ResolveTranspiledPythonUDFOptions extends Rule[LogicalPlan] {
   // - "string" requires the default UTF8_BINARY collation: under a non-binary
   //   collation (e.g. UTF8_LCASE) Spark's `=`/`<`/`concat` follow collation
   //   rules while Python compares codepoints, so `'abc' == 'ABC'` would return
-  //   true where Python returns False.
-  private def optionMatchesTypes(categories: Seq[String], argTypes: Seq[DataType]): Boolean = {
-    if (categories.isEmpty) {
-      true
-    } else if (categories.length != argTypes.length) {
-      false
-    } else {
-      categories.zip(argTypes).forall {
-        case ("integer", dt) => dt.isInstanceOf[IntegralType]
-        case ("float", dt) =>
-          dt.isInstanceOf[FractionalType] && !dt.isInstanceOf[DecimalType]
-        case ("numeric", dt) => dt.isInstanceOf[NumericType] && !dt.isInstanceOf[DecimalType]
-        case ("string", st: StringType) => st.isUTF8BinaryCollation
-        case ("bool", dt) => dt.isInstanceOf[BooleanType]
-        case ("binary", dt) => dt.isInstanceOf[BinaryType]
-        case _ => false
+  //   true where Python returns False. "array<string>" inherits the gate through
+  //   the element match, which is what lets the transpiler lower `==` on it.
+  // - "timestamp" does not match TimestampType (TIMESTAMP, local time zone) or DateType.
+  //   Batched Python UDFs rebuild a TIMESTAMP value as a naive datetime in the worker's
+  //   local zone, while Catalyst's datetime functions use spark.sql.session.timeZone, so
+  //   e.g. `hour(ts)` would return the session-zone hour where Python returns the
+  //   executor's. TIMESTAMP_NTZ is the one type whose Python and Catalyst views agree.
+  //   A UDF that falls back only for this reason logs it (`timeZoneMismatch`).

Review Comment:
   **Nit (P3):** `timeZoneMismatch` replaces only top-level `TimestampType` arguments with TIMESTAMP_NTZ and counts only top-level `timestamp` categories (lines 187-194), so an `array<timestamp>` option, which the Python vocabulary accepts and `categoryMatches` drops over ARRAY<TIMESTAMP> for exactly this reason, falls back with no log. Two nearby comments are stale too: the class doc's "see `optionMatchesTypes`" (lines 46-47) points at a function that only zips categories with argument types, so it should name `categoryMatches` and `timeZoneMismatch`, and the "Two deliberate exclusions" heading (line 115) now heads three bullets. Either `timeZoneMismatch` recurses through arrays, or the comments say what it logs:
   
   ```suggestion
     //   Only a top-level "timestamp" over a TIMESTAMP argument is logged (`timeZoneMismatch`).
   ```
   
   See **Shared repair plan 2** in the review body.



##########
python/pyspark/sql/transpile.py:
##########
@@ -181,20 +250,83 @@ def register(cls) -> None:
     def _transpile_from_ast(
         self,
         src: Optional[str],
-        ast_info: ast.AST,
-        function_ast: ast.FunctionDef,
+        ast_info: Optional[ast.AST],
+        function_ast: Optional[ast.FunctionDef],
         params: List[str],
         returnType: "DataTypeOrString",
         param_categories: Optional[dict] = None,
-    ) -> Optional[Column]:
-        """Lower ``function_ast`` to a :class:`Column`, or return ``None`` to decline.
+        held_code: Any = None,
+        code_owner: Any = None,
+        udf_callable: Optional[Callable[..., Any]] = None,
+    ) -> Optional[Union[Column, Tuple[Column, List[str]]]]:
+        """Lower the UDF to a :class:`Column`, or return ``None`` to decline.
 
         The override point for ``spark.sql.experimental.optimizer.pyTranspilers``.
 
+        The caller hands over whatever it could extract, in two forms. One of
+        them is always present; a transpiler declines when the one it needs is
+        not -- the built-in lowering works from the source form, a numba-style
+        variety from the bytecode form.
+
+        Source form, all ``None`` when no trustworthy source exists (a REPL- or
+        exec-defined function, a functools.wraps-decorated callable whose
+        visible source is the wrapped function's, a rejected lambda, or a
+        builtin):
+
+        * ``src`` -- the source text read for the callable.
+        * ``ast_info`` -- the module-level AST parsed from ``src``.
+        * ``function_ast`` -- the :class:`ast.FunctionDef` that runs (a lambda
+          is synthesized into one).
+
+        Bytecode form, all ``None`` together for builtins and slot wrappers:
+
+        * ``held_code`` -- the code object that actually runs when the UDF is
+          called.
+        * ``code_owner`` -- the function or method that owns ``held_code``
+          (``held_code is code_owner.__code__``). Everything the code object
+          does not carry lives here: ``__closure__`` and ``__globals__`` (two
+          closures from one factory share ``held_code`` and differ only in
+          their cells), ``__defaults__``, and ``__annotations__``. For a
+          callable instance this is its type's ``__call__``, unwrapped from any
+          ``staticmethod`` / ``classmethod``.
+        * ``udf_callable`` -- the object handed to ``udf()`` itself: the
+          function, the bound method (whose ``__self__`` is the receiver), or
+          the callable instance (whose attributes ``__call__`` reads).
+
+        A variety must not call ``udf_callable`` or ``code_owner``: deciding
+        what to transpile never runs user code. Code that does not return its
+        value -- a generator, coroutine, or async generator -- never reaches a
+        variety, nor does code with default, variadic, or keyword-only params.
+
         ``params`` is the CALLER-FACING parameter list: a receiver already bound, as
         on a method or callable instance, has been removed, so ``params[i]`` is the
         name bound to placeholder ``_udf_param_i`` with no offsetting needed. It is
         also the list ``param_categories`` is keyed by.
+
+        A plain :class:`Column` return is labeled with the ``param_categories``
+        combo the caller passed in. A variety that works out its own input types
+        returns ``(Column, list[str])`` instead -- one category per public param
+        (``"integer"`` / ``"float"`` / ``"numeric"`` / ``"string"`` / ``"bool"`` /
+        ``"binary"`` / ``"timestamp"`` / ``"map"`` / ``"array"``, or an element-aware
+        ``"array<c>"`` for any of these ``c``, e.g. ``"array<integer>"``) describing
+        the option it built, which the caller uses in place of the combo. ``"timestamp"``
+        matches TIMESTAMP_NTZ only: a TIMESTAMP (local time zone) value reaches
+        Python as a naive datetime in the worker's zone while Catalyst uses
+        ``spark.sql.session.timeZone``, so a lowering over it can silently
+        disagree with Python. A TIMESTAMP or DATE column matches no
+        ``"timestamp"`` option, and when that leaves the UDF without one the
+        analyzer logs it as the reason for the fallback. The hook is called

Review Comment:
   **Nit (P3):** `timeZoneMismatch` maps only `TimestampType` arguments to TIMESTAMP_NTZ before re-matching (`ResolveTranspiledPythonUDFOptions.scala` lines 184-199), so a DATE column never produces a reason, and `ResolveTranspiledPythonUDFOptionsSuite` asserts no warning for one. A variety author looking for the documented warning to explain a DATE fallback finds none; the logging clause should name TIMESTAMP columns only.
   
   ```suggestion
           disagree with Python. A TIMESTAMP or DATE column matches no
           ``"timestamp"`` option, and only a TIMESTAMP column that leaves the UDF without
           one is logged by the analyzer as the reason for the fallback. The hook is called
   ```
   
   See **Shared repair plan 2** in the review body.



##########
python/pyspark/sql/transpile.py:
##########
@@ -464,6 +615,18 @@ def _convert_if_like(
         # (e.g. a bare ``None``) are treated as compatible and don't force this.
         body_cat = self._safe_category(params, body_node)
         else_cat = self._safe_category(params, else_node)
+        # Two branches of one element-aware array category share a common type
+        # (`array<int>` and `array<bigint>` widen), and a None-literal branch
+        # unifies with either. Anything else with a map/array branch -- a map, an
+        # array whose element type is not known, or an operand whose category is
+        # unknown -- may have no common type, failing analysis instead of falling
+        # back.
+        if not _complex_operands_ok(_SCALAR_ELEMENT_CATS, body_cat, else_cat, body_node, else_node):
+            raise UnsupportedOperationException(
+                "if/else branches have a `map`/`array` operand without a "
+                "matching element-aware array category on the other side; "
+                "complex branches fall back to interpreted Python"

Review Comment:
   **Nit (P3):** `_complex_operands_ok(_SCALAR_ELEMENT_CATS, ...)` refuses two branches of one element-aware category whenever their innermost element is not a scalar category. For `def f(a: list[dict], b: list[dict], c: bool): return (a if c else b) is None` both branches are `array<map>`, yet the fallback warning says the other side has no matching element-aware category. The message should name the real requirement, two element-aware arrays of one category with scalar innermost elements or one such array and None, and the comment at lines 618-623, which says two branches of one element-aware category share a common type, needs the same change. The wording below keeps the prefix the tests match on.
   
   ```suggestion
                   "if/else branches have a `map`/`array` operand; they lower only as two "
                   "element-aware arrays of one category with scalar elements (or one and "
                   "None), so these fall back to interpreted Python"
   ```
   
   **Verification:**
   - **Regression:** For def f(a: list[dict], b: list[dict], c: bool): return (a if c else b) is None, the fallback reason says the branches' innermost elements must be scalar categories rather than that the other side lacks a matching category.
   - **Behavior:** For branches annotated list[int] and list[str], the fallback reason still covers the mismatched element categories.



##########
python/pyspark/sql/transpile.py:
##########
@@ -218,10 +350,29 @@ def _is_definitely_basic_type(node: ast.AST) -> bool:
         case ast.Call(func=ast.Name(id="len"), args=[_], keywords=[]):
             # len() always returns an int: CPython raises if __len__ returns anything else.
             return True
+        # A ternary and `and` / `or` yield one of their operands, and a bool is
+        # basic. Without these, a comparison on them (`(a if c else b) is None`,
+        # `(a is None) != (b is None)`) was not seen as boolean and fell to
+        # `_category`'s numeric catch-all, so a bool body passed the return-type
+        # check for a numeric return type.
+        case ast.IfExp(body=body, orelse=orelse):
+            return _is_definitely_basic_type(body) and _is_definitely_basic_type(orelse)
+        case ast.BoolOp(values=values):
+            return all(_is_definitely_basic_type(v) for v in values)
+        case _ if _is_definitely_boolean(node):

Review Comment:
   **Non-blocking (P2):** This arm and the `IfExp` and `BoolOp` arms above it make a comparison over a ternary, `and`/`or` or another comparison definitely boolean. A call such as `s.upper()` or `s.lower()` is still not basic, because `_is_definitely_boolean` is true only for the table's bool-valued methods, so `s.upper() == 'A'` stays not definitely boolean and `_category` labels it numeric. By this reading of the code, `@udf('int') def f(s: str): return s.upper() == 'A'` over 'a' and 'b' lowers to a cast of the comparison and returns 1 and 0, where the Python UDF returns NULL for both. With a LONG return type, `1 if s.upper() == 'A' else 0` tests `(upper(s) = 'A') != 0` and `(s.upper() == 'A') + 1` adds a boolean to an int; ANSI analysis rejects both, so the whole query fails where Python returns a value. Treating a call to one of the `_STRING_METHODS` with its table argument count as basic (they lower only for string receivers and return a str or a bool) would extend the same fix 
 to these operands.
   
   **Verification:**
   - **Regression:** A UDF declared to return INT whose body is s.upper() == 'A', over a STRING column holding 'a' and 'b', falls back to interpreted Python and returns NULL for both rows.
   - **Regression:** With a LONG return type, bodies s.lower() + t == 'ab' and s.upper() is None fall back with the bool-typed lowering reason and return the interpreted NULL.
   - **Behavior:** With a BOOLEAN return type, s.upper() == 'A' still lowers with no Python evaluation in the plan and returns the values the Python function returns.
   - **Regression:** A body that returns 1 when s.upper() == 'A' and 0 otherwise, with a LONG return type and over a STRING column of non-null values, lowers and returns the values the Python function returns instead of failing the query at analysis.
   - **Regression:** With a LONG return type, the body (s.upper() == 'A') + 1 over a STRING column of non-null values falls back to interpreted Python and returns 2 or 1, as the Python function does, instead of failing the query at analysis.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveTranspiledPythonUDFOptions.scala:
##########
@@ -97,23 +120,93 @@ object ResolveTranspiledPythonUDFOptions extends Rule[LogicalPlan] {
   // - "string" requires the default UTF8_BINARY collation: under a non-binary
   //   collation (e.g. UTF8_LCASE) Spark's `=`/`<`/`concat` follow collation
   //   rules while Python compares codepoints, so `'abc' == 'ABC'` would return
-  //   true where Python returns False.
-  private def optionMatchesTypes(categories: Seq[String], argTypes: Seq[DataType]): Boolean = {
-    if (categories.isEmpty) {
-      true
-    } else if (categories.length != argTypes.length) {
-      false
-    } else {
-      categories.zip(argTypes).forall {
-        case ("integer", dt) => dt.isInstanceOf[IntegralType]
-        case ("float", dt) =>
-          dt.isInstanceOf[FractionalType] && !dt.isInstanceOf[DecimalType]
-        case ("numeric", dt) => dt.isInstanceOf[NumericType] && !dt.isInstanceOf[DecimalType]
-        case ("string", st: StringType) => st.isUTF8BinaryCollation
-        case ("bool", dt) => dt.isInstanceOf[BooleanType]
-        case ("binary", dt) => dt.isInstanceOf[BinaryType]
-        case _ => false
+  //   true where Python returns False. "array<string>" inherits the gate through
+  //   the element match, which is what lets the transpiler lower `==` on it.
+  // - "timestamp" does not match TimestampType (TIMESTAMP, local time zone) or DateType.
+  //   Batched Python UDFs rebuild a TIMESTAMP value as a naive datetime in the worker's
+  //   local zone, while Catalyst's datetime functions use spark.sql.session.timeZone, so
+  //   e.g. `hour(ts)` would return the session-zone hour where Python returns the
+  //   executor's. TIMESTAMP_NTZ is the one type whose Python and Catalyst views agree.
+  //   A UDF that falls back only for this reason logs it (`timeZoneMismatch`).
+  // "map" and a bare "array" match any element/key type: the category names the
+  //   container, not its contents, and a variety that reports "map"/"array" is
+  //   responsible for the per-element lowering (an out-of-tree transpiler verifies
+  //   its rewrite before serving it, so a wrong shape does not ship). They need no
+  //   collation gate: the built-in transpiler refuses to lower any comparison of
+  //   them, so no built-in option observes an element's collation.
+  //   One exception: a container holding a map keyed by a nanosecond timestamp matches
+  //   neither. Python refuses to receive such a map (TIMESTAMP_NANOS_PYTHON_MAP_KEY), so an
+  //   option over it would return a value where the Python UDF raises. "array<c>" inherits
+  //   the exclusion through the element match, which reaches any nested map through one of
+  //   these two cases.
+  private def categoryMatches(category: String, dt: DataType): Boolean = (category, dt) match {
+    case ("integer", _) => dt.isInstanceOf[IntegralType]
+    case ("float", _) => dt.isInstanceOf[FractionalType] && !dt.isInstanceOf[DecimalType]
+    case ("numeric", _) => dt.isInstanceOf[NumericType] && !dt.isInstanceOf[DecimalType]
+    case ("string", st: StringType) => st.isUTF8BinaryCollation
+    case ("bool", _) => dt.isInstanceOf[BooleanType]
+    case ("binary", _) => dt.isInstanceOf[BinaryType]
+    case ("timestamp", _) => dt.isInstanceOf[TimestampNTZType]
+    case ("map", mt: MapType) => !hasTimestampNanosMapKey(mt)

Review Comment:
   **Non-blocking (P2):** The nanosecond-key exclusion exists because an option over a map Python refuses to receive "would return a value where the Python UDF raises" (lines 137-141), and the same holds for other keys Python cannot hash. `EvaluatePython.toJava` hands an ArrayType key to the worker as a `java.util.ArrayList` inside a `java.util.HashMap`, which unpickles as a dict with a list key, and CPython raises `TypeError: unhashable type: 'list'` while building it; a struct key holding an array arrives as a Row holding a list, and a binary key arrives as a `bytearray` when `spark.sql.execution.pyspark.binaryAsBytes` is false. Spark accepts all of these as map key types. Since `dict` now pins `map`, the built-in transpiler gives `def f(x: dict, y: int): return y + 1` an option that this case keeps over a `map<array<int>,string>` column, so by this reading of the code the query returns `y + 1` where the Python UDF fails the task, and `def f(x: dict): return x is None` returns fals
 e the same way. Extending `hasTimestampNanosMapKey`, with its name and comment, to keys that contain an ArrayType, directly or inside a struct or user-defined type, and to BinaryType keys while `binaryAsBytes` is false, as `BatchEvalPythonExec` reads it, would drop those options.
   
   **Verification:**
   - **Regression:** With the built-in transpiler, a UDF def f(x: dict, y: int): return y + 1 applied to a map<array<int>,string> column and a BIGINT column keeps a Python evaluation in the executed plan instead of the lowered option.
   - **Regression:** The analyzer rule drops a 'map' option for map<array<int>,string> and map<struct<a:array<int>>,int> arguments, and 'array' and 'array<map>' options for an array<map<array<int>,int>> argument.
   - **Behavior:** A 'map' option is still kept for map<string,int> and map<struct<a:int>,int> arguments, and for map<binary,int> unless spark.sql.execution.pyspark.binaryAsBytes is false, in which case it is dropped.



##########
python/pyspark/sql/transpile.py:
##########
@@ -1519,62 +1926,117 @@ def _transpile_func(
                 [],
                 [],
             )
+        # Hand each transpiler whatever could be extracted: the AST from the
+        # source on disk when it is trustworthy, and the code object that
+        # actually runs (``held_code``) when there is one. A transpiler declines
+        # when the form it needs is missing -- the built-in lowering works from
+        # the AST, a numba-style variety from the bytecode -- so an extraction
+        # failure is recorded as a reason for the fallback warning, not refused
+        # outright. Only BOTH missing means there is nothing to lower from.
+        held_code = _held_code(func)
+        # The function that owns ``held_code``: the closure cells, globals,
+        # defaults and annotations a bytecode variety needs live here, not on
+        # the code object. ``None`` exactly when ``held_code`` is.
+        code_owner = _code_owner(func) if held_code is not None else None
+        src = None
+        ast_info = None
+        function_ast = None
+        errors: List[str] = []
         # A functools.wraps-style decorator makes ``inspect.getsource`` return
         # the WRAPPED function's source (getsource follows ``__wrapped__``),
-        # while the UDF actually executes the wrapper. Transpiling would
-        # silently reproduce the wrong behavior, so refuse and fall back.
+        # while the UDF actually executes the wrapper -- the AST is a lie, but
+        # ``held_code`` is exactly what runs.
         # ``_call_impl`` first: a ``staticmethod`` / ``classmethod`` exposes a
-        # ``__wrapped__`` of its own, so asking the descriptor refuses every one of
-        # them for a wraps decorator that is not there.
+        # ``__wrapped__`` of its own, so asking the descriptor distrusts every
+        # one of them for a wraps decorator that is not there.
         if (
             getattr(func, "__wrapped__", None) is not None
             or getattr(_call_impl(_call_dunder(func)), "__wrapped__", None) is not None
         ):
+            errors.append(
+                "a functools.wraps decorator makes the visible source the wrapped "
+                "function's, not the wrapper's; only the bytecode is trustworthy"
+            )
+        else:
+            # Not ``ast``: that name would shadow the module for this function.
+            src, ast_info = _get_src_ast_from_func(func)
+            if ast_info is None:
+                errors.append("Error getting ast for function")
+            else:
+                # Get the lambda body and parameters
+                function_ast, extraction_error = _get_function_from_ast(ast_info, held_code)
+                if function_ast is None:
+                    errors.append(extraction_error)
+                    # Rejected source is not trustworthy either; hand varieties None.
+                    src, ast_info = None, None
+        if function_ast is None and held_code is None:
             return (
                 [],
-                [
-                    "decorated callables (functools.wraps) are not supported: "
-                    "the visible source is the wrapped function's, not the "
-                    "wrapper's, so transpilation would change behavior"
+                errors + ["and no bytecode is available either, cannot transpile"],
+                [],
+                [],
+                [],
+            )
+        # A generator, coroutine, or async generator returns an iterator or an
+        # awaitable from the call, never the value its body computes, so no
+        # lowering of that body can agree with Python. Refused from the flags of
+        # the code that runs, whichever form a variety would lower from.
+        if held_code is not None and held_code.co_flags & (
+            inspect.CO_GENERATOR | inspect.CO_COROUTINE | inspect.CO_ASYNC_GENERATOR
+        ):
+            return (
+                [],
+                errors
+                + [
+                    "generator, coroutine, and async generator functions return an "
+                    "iterator or awaitable rather than a value, so they are not "
+                    "supported by the transpiler"
                 ],
                 [],
                 [],
                 [],
             )
-        # Not ``ast``: that name would shadow the module for this whole function.
-        src, ast_info = _get_src_ast_from_func(func)
-        if ast_info is None:
-            return ([], ["Error getting ast for function, cannot transpile"], [], [], [])
-        # Get the lambda body and parameters
-        function_ast, extraction_error = _get_function_from_ast(ast_info, _held_code(func))
-        if function_ast is None:
-            return ([], [extraction_error], [], [], [])
         # Default, variadic (``*args`` / ``**kwargs``) and keyword-only params
         # can't be represented by the positional ``_udf_param_N`` placeholder
         # scheme: a call site may omit a defaulted argument, leaving the
         # placeholder referencing a position the call never bound. A
         # positional-only param has no such gap -- it is always bound by
-        # position -- so it is not refused here; a DEFAULTED one still hits
-        # ``fn_args.defaults`` above.
-        fn_args = function_ast.args
-        if (
-            fn_args.defaults
-            or any(d is not None for d in fn_args.kw_defaults)
-            or fn_args.kwonlyargs
-            or fn_args.vararg is not None
-            or fn_args.kwarg is not None
-        ):
+        # position -- so it is not refused here; a DEFAULTED one still hits the
+        # check below. The check runs on the AST when there is one, on the code
+        # object otherwise: ``__defaults__`` / ``__kwdefaults__`` live on the
+        # function, the variadic and keyword-only counts on its code object.
+        if function_ast is not None:
+            fn_args = function_ast.args
+            unsupported_params = bool(
+                fn_args.defaults
+                or any(d is not None for d in fn_args.kw_defaults)
+                or fn_args.kwonlyargs
+                or fn_args.vararg is not None
+                or fn_args.kwarg is not None
+            )
+        else:
+            unsupported_params = bool(

Review Comment:
   **Nit (P3):** Every callable without source in `test_udf_transpile_unit.py` is an exec-defined plain function (`ident`, `add(a, b=1)`, `f(a, *, b)`, `f(a, /)`, `repl_ident`, `add(a, b, c)`, `repl_gen`), plus a one-parameter `functools.wraps` wrapper and a rejected lambda, and every variety that sees one returns a `(Column, categories)` tuple; the only variadic UDF in the suite, `with_varargs`, is file-defined and takes the AST route. So dropping the `CO_VARARGS`/`CO_VARKEYWORDS` term here would let a source-less `def f(a, *rest)` reach a variety with `params == ['a']`, dropping the receiver twice would shift every placeholder for an exec-defined `__call__(self, x)` or bound method, and returning `[{}]` from the no-source combos would label every plain-Column option numeric, all without a failing test. Exec-defined fixtures for a variadic function and a `functools.wraps` wrapper declared with `*args, **kwargs`, a callable instance and a bound method, plus a recording plain-Column v
 ariety, would give each a failure signal.
   
   This extends an [existing discussion](https://github.com/apache/spark/pull/59721#discussion_r4419992749).
   
   **Verification:**
   - **Behavior:** A source-less variadic function and a functools.wraps wrapper declared with *args and **kwargs fall back with the default, variadic or keyword-only reason, and the recording variety is never called.
   - **Behavior:** For an exec-defined callable instance and a bound method of an exec-defined class, the variety receives the parameter list without the receiver, and the lowered option returns the call-site argument.
   - **Behavior:** A plain-Column variety handed an exec-defined two-parameter function is asked about the nine untyped combos, and its options carry those combos' labels.



-- 
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-55213][PYTHON] Provide hooks for custom transpilers [spark]

Posted by "holdenk (via GitHub) via reviews" <re...@spark.apache.org>.
holdenk commented on code in PR #59721:
URL: https://github.com/apache/spark/pull/59721#discussion_r4580911911


##########
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:
   Fixed in ceda2e5905e. Added two tests in `test_udf_transpile_unit.py`:
   
   - `test_udf_transpile_variety_accepts_every_documented_category` reports each of the nine entries (spelled out in the test, not read from `_VARIETY_CATEGORIES`) for a one-parameter UDF and asserts one option labeled with exactly that entry.
   - `test_udf_transpile_variety_container_and_timestamp_lowering` lowers `size` over non-null array and map columns and a null check over a `TIMESTAMP` column, and asserts no `EvalPython` in the executed plan and the same values as the Python function.
   
   Dropping `"array"` from the vocabulary fails both. I did not mutate the JVM matcher. The timestamp case's column type will need to follow whatever the timestamp decision settles on.
   
   ---
   <sub>🤖 Posted by an AI agent (Claude Code · skill `none`) on behalf of @holdenk.</sub>
   <!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk -->
   



##########
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:
   Fixed in ceda2e5905e. Reworded as suggested. The test comment now says the same thing, and the test returns a tuple of valid names instead of a string, so only the list check can refuse it.
   
   ---
   <sub>🤖 Posted by an AI agent (Claude Code · skill `none`) on behalf of @holdenk.</sub>
   <!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk -->
   



##########
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:
   Fixed in ceda2e5905e. The variety now records `src` and `ast_info` as well, and the test asserts all three are None alongside `held_code` being the wrapper's code object.
   
   ---
   <sub>🤖 Posted by an AI agent (Claude Code · skill `none`) on behalf of @holdenk.</sub>
   <!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk -->
   



-- 
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