holdenk commented on code in PR #59724:
URL: https://github.com/apache/spark/pull/59724#discussion_r4585302847


##########
python/pyspark/sql/transpile.py:
##########
@@ -299,6 +386,186 @@ def _null_narrowed(params: List[str], test_node: ast.AST) 
-> Tuple[frozenset, fr
     return frozenset(), frozenset()
 
 
+# ----------------------------------------------------------------------------
+# Scalar pandas UDF (Series in / Series out) support. See the module docstring
+# for why the subset below is an allowlist rather than a set of exclusions.
+# ----------------------------------------------------------------------------
+
+# ``pandas.Series`` methods meaning "is this element missing", mapped to 
whether the method
+# is the positive form. All four are the same lowering up to a negation.
+_SERIES_NULL_METHODS = {"isnull": True, "isna": True, "notnull": False, 
"notna": False}
+
+# Binary and unary operators pandas applies element-wise with the same result 
Catalyst
+# produces, given operands of a matching category (`_category` still decides 
add-vs-concat
+# and multiply-vs-repeat). `**` and `/` are absent because the scalar 
transpiler does not
+# lower them either.
+#
+# `Mult` is in the allowlist for numeric multiply and for string-repeat by an 
integer
+# LITERAL only (`s * 2`). Repeat by an integral COLUMN is refused under series 
semantics in
+# `_convert_chunk`: pandas repeats element-wise only while the batch has no 
NULL, because a
+# NULL makes it hold the count as float64 and `str * float64` raises 
TypeError, so the
+# outcome depends on batching. See `_reject_series_string_repeat`.
+_SERIES_SAFE_BINOPS = (ast.Add, ast.Sub, ast.Mult, ast.Mod)
+_SERIES_SAFE_UNARYOPS = (ast.UAdd, ast.USub)
+
+
+def _is_int_literal(node: ast.AST) -> bool:
+    """True for an ``int`` constant that is not a ``bool`` (``bool`` 
subclasses ``int``).
+
+    This is the only repeat count that is safe under series semantics: it 
cannot be NaN or
+    NULL, and it is fixed at transpile time so no column value can make it 
fractional.
+    """
+    return (
+        isinstance(node, ast.Constant)
+        and isinstance(node.value, int)
+        and not isinstance(node.value, bool)
+    )
+
+
+# Raised from both the up-front ``_check_series_semantics`` call and 
``_transpile_from_ast``
+# itself; a single constant keeps the two paths reporting the same reason.
+_MULTI_STATEMENT_ERROR = (
+    "functions with more than one top-level statement are not supported by the 
transpiler"
+)
+
+
+def _match_series_null_check(node: ast.AST, params: List[str]) -> 
Optional[Tuple[ast.Name, bool]]:
+    """Match ``<param>.isnull()`` and its aliases, returning ``(receiver, 
positive)``.
+
+    ``None`` when ``node`` is any other call. The receiver must be a bare 
parameter: on an
+    intermediate expression the ``isnan`` arm of the lowering would have to 
reason about
+    which sub-expression can produce NaN, so those fall back to interpreted 
Python instead.
+    Arguments are refused too (``isna()`` takes none, but a future keyword 
should not be
+    silently ignored).
+    """
+    match node:
+        case ast.Call(
+            func=ast.Attribute(value=ast.Name(id=receiver_name) as receiver, 
attr=attr),
+            args=[],
+            keywords=[],
+        ) if receiver_name in params and attr in _SERIES_NULL_METHODS:
+            return receiver, _SERIES_NULL_METHODS[attr]
+        case _:
+            return None
+
+
+def _describe_unsupported_series_node(node: ast.AST) -> str:
+    """A short user-facing label for a node refused by 
:func:`_check_series_semantics`.
+
+    These end up in the ``Unable to transpile UDF ...`` warning, which is the 
only place a
+    user learns why the rewrite did not happen, so name the pandas-specific 
reason rather
+    than just the AST class. Only the constructs whose pandas divergence is 
non-obvious
+    get a custom message; everything else falls through to a generic label.
+    """
+    match node:
+        case ast.Compare(ops=[ast.Is(), *_]):
+            return (
+                "an `is` test (a Series object is never None, so this is 
always False at "
+                "runtime -- write `x.isnull()` for a per-element check)"
+            )
+        case ast.Compare(ops=[ast.IsNot(), *_]):
+            return (
+                "an `is not` test (a Series object is never None, so this is 
always True at "
+                "runtime -- write `x.notnull()` for a per-element check)"
+            )
+        case ast.Compare(ops=[ast.Eq() | ast.NotEq(), *_]):
+            return (
+                "an `==` / `!=` comparison (on a Series a missing value or NaN 
is never equal "
+                "to anything, so `==` gives False and `!=` gives True there, 
where Spark "
+                "treats NaN as equal to itself)"
+            )
+        case ast.Compare(ops=[ast.Lt() | ast.LtE() | ast.Gt() | ast.GtE(), 
*_]):
+            return (
+                "an ordering comparison (on a Series a missing value compares 
False rather "
+                "than raising or yielding NULL, and NaN compares False where 
Spark orders it "
+                "above every value)"
+            )
+        case ast.BoolOp() | ast.UnaryOp(op=ast.Not()):
+            return "`and` / `or` / `not` (these raise ValueError on a Series)"
+        case ast.If() | ast.IfExp():
+            return "an `if` (testing a Series for truth raises ValueError)"

Review Comment:
   Fixed in ec18766cfd2.
   
   `_describe_unsupported_series_node` now reports the existing `is` / `is not` 
reason when the first value an `if`, conditional expression, `not`, `and` or 
`or` tests is an `is` / `is not` comparison. So `0 if s is None else s`, `if s 
is None: return 0`, `not (s is None)` and `s is not None and s` now point at 
`.isnull()` / `.notnull()`. `if s > 0`, `not s` and `s and s` keep the 
ValueError reason, and that is now asserted in 
`test_control_flow_falls_back_and_still_raises`.
   
   The no-parameter message no longer names UDF_RETURN_TYPE. I checked that 
`return 'ab'` over a one-row batch fails with RESULT_ROWS_MISMATCH while 
`return 1` still raises UDF_RETURN_TYPE. New tests cover each None-guard form 
and the string body.
   
   Only the first tested value is inspected, as suggested; a later `is` operand 
(`s > 0 and s is None`) keeps the generic label.
   
   ---
   <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/arrow/test_arrow_python_udf_transpile.py:
##########
@@ -0,0 +1,1058 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""
+Transpilation of Arrow-optimized Python UDFs (``SQL_ARROW_BATCHED_UDF``).
+
+Arrow optimization is the default for regular Python UDFs, so a plain
+``functions.udf(f, "bigint")`` gets ``SQL_ARROW_BATCHED_UDF``. Until that eval 
type was
+admitted to ``_TRANSPILABLE_EVAL_TYPES`` in ``python/pyspark/sql/udf.py``, the 
transpilation
+flag did nothing on default configuration.
+
+This is a separate module from ``pyspark.sql.tests.test_udf_transpile_unit`` 
because the
+reference semantics differ. The pickled path coerces a UDF's return value 
through
+``EvaluatePython.makeFromJava``, which NULLs a type mismatch; the Arrow path 
builds a
+``pa.array`` and falls back to a cast (``ArrowBatchedUDFArrowHandler.run`` in
+``python/pyspark/eval_handlers/_arrow.py``), which can raise or convert 
instead. So every
+differential here compares transpiled-Arrow against interpreted-**Arrow**: the 
question is
+whether the rewrite matches what this UDF would have done in its own eval 
mode. The
+cell-by-cell matrix for both regimes lives in the golden files under
+``python/pyspark/sql/tests/coercion/``.
+
+Naming trap: ``SQL_ARROW_BATCHED_UDF`` (101) is the Arrow-*optimized* regular 
UDF -- Arrow
+is only the transport, and the worker still calls the function once per row 
with Python
+scalars. ``SQL_SCALAR_ARROW_UDF`` (250) is genuinely vectorized and must never 
be
+transpiled. ``test_eval_type_allowlist_is_exhaustive`` guards the distinction.
+
+UDF bodies here are all named ``def``s. The transpiler recovers source with
+``inspect.getsource``, which for a lambda passed as a call argument returns 
the enclosing
+statement -- whose top-level node is a call, not a lambda -- so transpilation 
silently falls
+back and the test passes while asserting nothing. ``_assert_transpiled`` 
catches that.
+"""
+
+import unittest
+import warnings
+from collections import Counter
+
+from pyspark.errors import PythonException
+from pyspark.sql import Row
+from pyspark.sql.functions import udf
+from pyspark.sql.types import (
+    BinaryType,
+    BooleanType,
+    ByteType,
+    CalendarIntervalType,
+    DecimalType,
+    DoubleType,
+    IntegerType,
+    LongType,
+    StringType,
+)
+from pyspark.sql.udf import UserDefinedFunction
+from pyspark.testing.objects import ExamplePoint, ExamplePointUDT
+from pyspark.testing.sqlutils import ReusedSQLTestCase
+from pyspark.testing.utils import (
+    have_pandas,
+    have_pyarrow,
+    pandas_requirement_message,
+    pyarrow_requirement_message,
+)
+from pyspark.util import PythonEvalType, is_remote_only
+
+if have_pandas:
+    import pandas as pd
+
+
+# Kept as a constant so ``test_arrow_transpile_flag_matches_reality`` fails in 
either
+# direction if the eval-type gate in python/pyspark/sql/udf.py and this file 
disagree.
+ARROW_TRANSPILE_SUPPORTED = True
+
+# Transpilation requires both flags, at construction and again in 
ConvertToCatalyst.
+_TRANSPILE_ON = {
+    "spark.sql.experimental.optimizer.transpilePyUDFs": True,
+    "spark.sql.ansi.enabled": True,
+}
+
+# ANSI stays on for the interpreted side so a differential isolates the 
rewrite rather than
+# also flipping overflow semantics.
+_TRANSPILE_OFF = {
+    "spark.sql.experimental.optimizer.transpilePyUDFs": False,
+    "spark.sql.ansi.enabled": True,
+}
+
+# A differential that silently falls back compares interpreted against 
interpreted and
+# passes for the wrong reason, so these warnings are fatal. These are exactly 
the three
+# warnings udf.py emits when a rewrite does not happen ("Unable to transpile 
UDF ...",
+# "Exception transpiling UDF ...", and the ANSI-disabled one); kept in sync 
with the
+# identical tuple in pyspark.sql.tests.pandas.test_pandas_udf_transpile.
+_BAD_TRANSPILE_WARNING_MARKERS = (
+    "Unable to transpile",
+    "Exception transpiling",
+    "is only supported when ANSI mode is enabled",
+)
+
+# "This side raised instead of returning rows."
+_RAISED = object()
+
+# Eval types that hand the function a whole pandas.Series or pyarrow.Array and 
are still
+# refused outright. SQL_SCALAR_PANDAS_UDF is deliberately absent: it is also 
vectorized, but
+# it is transpiled for the element-wise subset of bodies covered by
+# ``pyspark.sql.tests.pandas.test_pandas_udf_transpile``.
+_VECTORIZED_SCALAR_EVAL_TYPES = (
+    PythonEvalType.SQL_SCALAR_PANDAS_ITER_UDF,
+    PythonEvalType.SQL_SCALAR_ARROW_UDF,
+    PythonEvalType.SQL_SCALAR_ARROW_ITER_UDF,
+)
+
+_GROUPED_AGG_EVAL_TYPES = (
+    PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF,
+    PythonEvalType.SQL_GROUPED_AGG_PANDAS_ITER_UDF,
+    PythonEvalType.SQL_GROUPED_AGG_ARROW_UDF,
+    PythonEvalType.SQL_GROUPED_AGG_ARROW_ITER_UDF,
+)
+
+
+# --- UDF bodies 
------------------------------------------------------------------------
+
+
+def add_one(x):
+    return x + 1
+
+
+def add_four(x):
+    return x + 4
+
+
+def identity(x):
+    return x
+
+
+def constant_42(x):
+    return 42
+
+
+def gt_one(x):
+    return x > 1
+
+
+def is_null(x):
+    return x is None
+
+
+def square(x):
+    return x * x
+
+
+def mod_zero(x):
+    return x % 0
+
+
+def add_half(x):
+    return x + 0.5
+
+
+def times_thousand(x):
+    return x * 1000
+
+
+def floor_halve(x):
+    # Floor division is not lowered: the canonical "must stay interpreted" 
body.
+    return x // 2
+
+
+def floor_third(x):
+    return x // 3
+
+
+def guarded_add_one(x):
+    # Single top-level statement; the transpiler rejects more than one. The 
implicit
+    # else yields NULL, which is also what the interpreted path returns.
+    if x is not None:
+        return x + 1
+
+
+def num_add(x):
+    return x + 3
+
+
+def num_sub(x):
+    return x - 3
+
+
+def num_mul(x):
+    return x * 3
+
+
+def num_mod(x):
+    return x % 3
+
+
+def num_neg(x):
+    return -x
+
+
+def num_pos(x):
+    return +x
+
+
+_NUMERIC_ARITHMETIC = (num_add, num_sub, num_mul, num_mod, num_neg, num_pos)
+
+
+def cmp_lt(x):
+    return x < 2
+
+
+def cmp_le(x):
+    return x <= 2
+
+
+def cmp_gt(x):
+    return x > 2
+
+
+def cmp_ge(x):
+    return x >= 2
+
+
+def cmp_eq(x):
+    return x == 2
+
+
+def cmp_ne(x):
+    return x != 2
+
+
+_NUMERIC_COMPARISONS = (cmp_lt, cmp_le, cmp_gt, cmp_ge, cmp_eq, cmp_ne)
+
+
+# Annotations pin a parameter's input-type category; an unannotated parameter 
is only tried
+# as numeric and string.
+def str_concat(x: str):
+    return x + x
+
+
+def repeat_negated(x):
+    return "ab" * -x
+
+
+def repeat_positive(x):
+    return "ab" * +x
+
+
+def repeat_negated_left(x, s: str):
+    return -x * s
+
+
+def repeat_negative_float(s: str):
+    return s * -1.5
+
+
+def negated_equals_two(x):
+    return -x == 2
+
+
+def guarded_negated_equals_two(x):
+    return False if x is None else -x == 2
+
+
+def str_repeat_right(x: str):
+    return x * 3
+
+
+def str_repeat_left(x: str):
+    return 3 * x
+
+
+_STRING_BODIES = (str_concat, str_repeat_right, str_repeat_left)
+
+
+def str_is_abc(x: str):
+    return x == "abc"
+
+
+def bool_identity(x: bool):
+    return x
+
+
+# `not`/`and`/`or` need a statically-boolean operand, which a bare parameter 
is not (see
+# _is_definitely_boolean); those fall back, as 
test_udf_transpile_{not,and_or}_bare_param_*
+# in the non-Arrow unit suite pin. Wrapping a comparison is what makes them 
lowerable.
+def not_compare(x):
+    return not (x > 2)
+
+
+def and_compare(x):
+    return (x > 0) and (x < 10)
+
+
+def or_compare(x):
+    return (x < 0) or (x > 10)
+
+
+_BOOL_LOGIC_BODIES = (not_compare, and_compare, or_compare)
+
+
+def bytes_identity(x: bytes):
+    return x
+
+
+def _arrow_udf(func, return_type):
+    """Build a UDF pinned to the Arrow-optimized eval type.
+
+    ``UserDefinedFunction`` defaults to ``SQL_BATCHED_UDF``, and constructing 
it directly
+    also bypasses ``_create_py_udf``'s type-hint eval-type inference -- which 
matters for
+    the annotated bodies above, whose annotations are category hints rather 
than a
+    vectorized signature.
+    """
+    return UserDefinedFunction(func, return_type, 
evalType=PythonEvalType.SQL_ARROW_BATCHED_UDF)
+
+
+def _pickled_udf(func, return_type):
+    """Build a UDF pinned to the pickled eval type, for contrast with 
``_arrow_udf``."""
+    return UserDefinedFunction(func, return_type, 
evalType=PythonEvalType.SQL_BATCHED_UDF)
+
+
+def _eval_python_nodes(df):
+    """Count Python-eval physical operators in ``df``'s executed plan, by 
class name.
+
+    Counting nodes rather than substring-matching the plan string matters 
because
+    ``"ArrowEvalPython"`` contains ``"EvalPython"``. Traversal follows
+    ``_assert_columnar_arrow_eval`` in test_arrow_python_udf_cached.py.
+    """
+    counts: Counter = Counter()
+    stack = [df._jdf.queryExecution().executedPlan()]
+    while stack:
+        node = stack.pop()
+        name = node.getClass().getSimpleName()
+        if name == "AdaptiveSparkPlanExec":
+            stack.append(node.executedPlan())
+            continue
+        if name.endswith("EvalPythonExec"):
+            counts[name] += 1
+        children = node.children()
+        for i in range(children.size()):
+            stack.append(children.apply(i))
+    return counts
+
+
+def _python_udf_expr_count(df):
+    """Count PythonUDF expression nodes across every Python-eval operator in 
``df``.
+
+    Operator counts alone no longer say whether a call was lowered: a chain of 
UDFs is
+    evaluated as a pipeline inside ONE operator, so three chained UDFs and one 
UDF both
+    show a single ArrowEvalPythonExec. What still distinguishes them is how 
many PythonUDF
+    expressions that operator holds -- a lowered call is gone from the tree, 
while the alias
+    naming it survives, so this counts nodes rather than matching the plan 
string.
+    """
+    total = 0
+    stack = [df._jdf.queryExecution().executedPlan()]
+    while stack:
+        node = stack.pop()
+        name = node.getClass().getSimpleName()
+        if name == "AdaptiveSparkPlanExec":
+            stack.append(node.executedPlan())
+            continue
+        if name.endswith("EvalPythonExec"):
+            udfs = node.udfs()
+            for i in range(udfs.size()):
+                exprs = [udfs.apply(i)]
+                while exprs:
+                    expr = exprs.pop()
+                    if expr.getClass().getSimpleName() == "PythonUDF":
+                        total += 1
+                    expr_children = expr.children()
+                    for j in range(expr_children.size()):
+                        exprs.append(expr_children.apply(j))
+        children = node.children()
+        for i in range(children.size()):
+            stack.append(children.apply(i))
+    return total
+
+
[email protected](is_remote_only(), "UDF transpilation is only supported in 
non-Connect Spark.")
[email protected](
+    not have_pandas or not have_pyarrow,
+    pandas_requirement_message or pyarrow_requirement_message,  # type: 
ignore[arg-type]
+)
+class ArrowUDFTranspileTestsMixin:
+    """Helpers shared by the suites in this module."""
+
+    def _assert_transpiled(self, pudf, what):
+        self.assertTrue(
+            pudf.transpiled,
+            f"expected {what} to transpile, but no Catalyst expression was 
produced; "
+            "a parity assertion against the interpreted path would be vacuous",
+        )
+
+    def _values_or_raised(self, df):
+        try:
+            return [row[0] for row in df.collect()], None
+        except Exception as e:  # the exception itself is what we compare
+            return _RAISED, e
+
+    def _differential(self, func, return_type, df, *cols, eval_type=None, 
conf=None):
+        """Run ``func`` with transpilation on and off; return ``(values, 
error)`` for each.
+
+        Both sides use the same eval type, so the reference is the interpreted 
behavior of
+        the very UDF being rewritten. ``values`` is the produced list, or 
``_RAISED``.
+        """
+        eval_type = eval_type or PythonEvalType.SQL_ARROW_BATCHED_UDF
+        extra = conf or {}
+        name = getattr(func, "__name__", repr(func))
+
+        with warnings.catch_warnings(record=True) as caught:
+            warnings.simplefilter("always")
+            with self.sql_conf({**_TRANSPILE_ON, **extra}):
+                pudf = UserDefinedFunction(func, return_type, 
evalType=eval_type)
+                self._assert_transpiled(pudf, name)
+                on = self._values_or_raised(df.select(pudf(*cols)))
+        bad = [
+            str(w.message)
+            for w in caught
+            if any(m in str(w.message) for m in _BAD_TRANSPILE_WARNING_MARKERS)
+        ]
+        self.assertFalse(bad, f"unexpected transpile warnings for {name}: 
{bad}")
+
+        with self.sql_conf({**_TRANSPILE_OFF, **extra}):
+            pudf = UserDefinedFunction(func, return_type, evalType=eval_type)
+            off = self._values_or_raised(df.select(pudf(*cols)))
+
+        return on, off
+
+    def _assert_matches_interpreted(self, func, return_type, df, *cols, 
eval_type=None, conf=None):
+        """Assert transpiled and interpreted agree, including on whether they 
raise."""
+        (on_values, on_error), (off_values, off_error) = self._differential(
+            func, return_type, df, *cols, eval_type=eval_type, conf=conf
+        )
+        name = getattr(func, "__name__", repr(func))
+        if off_values is _RAISED:
+            self.assertIs(
+                on_values,
+                _RAISED,
+                f"{name}: interpreted raised {off_error!r} but transpiled 
returned {on_values!r}",
+            )
+            return
+        self.assertIsNot(
+            on_values,
+            _RAISED,
+            f"{name}: transpiled raised {on_error!r} but interpreted returned 
{off_values!r}",
+        )
+        self.assertEqual(off_values, on_values, f"{name}: transpiled != 
interpreted")
+
+
+class ArrowUDFTranspileEvalTypeGateTests(ArrowUDFTranspileTestsMixin, 
ReusedSQLTestCase):
+    """Which eval types may be transpiled at all."""
+
+    def test_arrow_transpile_flag_matches_reality(self):
+        with self.sql_conf(_TRANSPILE_ON):
+            pudf = _arrow_udf(add_one, LongType())
+            self.assertEqual(
+                bool(pudf.transpiled),
+                ARROW_TRANSPILE_SUPPORTED,
+                "ARROW_TRANSPILE_SUPPORTED disagrees with the eval-type gate 
in "
+                "python/pyspark/sql/udf.py; update whichever one is wrong.",
+            )
+
+    def test_arrow_batched_eval_type_transpiles_and_computes(self):
+        with self.sql_conf(_TRANSPILE_ON):
+            pudf = _arrow_udf(add_four, LongType())
+            self._assert_transpiled(pudf, "an Arrow-optimized UDF")
+            df = self.spark.createDataFrame([Row(a=1)])
+            self.assertEqual([5], [r[0] for r in 
df.select(pudf("a")).collect()])
+
+    def test_functions_udf_transpiles_on_default_configuration(self):
+        # The motivating case: no useArrow argument, so functions.udf picks the
+        # Arrow-optimized eval type from the default of
+        # spark.sql.execution.pythonUDF.arrow.enabled (true) -- what users 
write. Only the
+        # experimental transpile flag is set; the arrow conf is left at its 
default so this
+        # actually exercises it rather than pinning it.
+        with self.sql_conf(_TRANSPILE_ON):
+            wrapped = udf(add_four, LongType())
+            self.assertEqual(wrapped.evalType, 
PythonEvalType.SQL_ARROW_BATCHED_UDF)
+            self._assert_transpiled(wrapped._unwrapped, "functions.udf on 
default config")
+            df = self.spark.createDataFrame([Row(a=1)])
+            self.assertEqual([5], [r[0] for r in 
df.select(wrapped("a")).collect()])
+
+    def test_pickled_eval_type_still_transpiles(self):
+        # Regression guard on rewriting the gate as set membership.
+        with self.sql_conf(_TRANSPILE_ON):
+            pudf = _pickled_udf(add_four, LongType())
+            self._assert_transpiled(pudf, "a pickled UDF")
+            df = self.spark.createDataFrame([Row(a=1)])
+            self.assertEqual([5], [r[0] for r in 
df.select(pudf("a")).collect()])
+
+    def test_vectorized_scalar_eval_types_do_not_transpile(self):
+        # `x + 1` on a Series is a whole-batch operation, not the per-row 
lowering the
+        # transpiler would emit.
+        with self.sql_conf(_TRANSPILE_ON):
+            for eval_type in _VECTORIZED_SCALAR_EVAL_TYPES:
+                with self.subTest(evalType=eval_type):
+                    pudf = UserDefinedFunction(add_one, LongType(), 
evalType=eval_type)
+                    self.assertEqual([], pudf.transpiled)
+
+    def test_grouped_agg_eval_types_do_not_transpile(self):
+        with self.sql_conf(_TRANSPILE_ON):
+            for eval_type in _GROUPED_AGG_EVAL_TYPES:
+                with self.subTest(evalType=eval_type):
+                    pudf = UserDefinedFunction(add_one, LongType(), 
evalType=eval_type)
+                    self.assertEqual([], pudf.transpiled)
+
+    def test_eval_type_allowlist_is_exhaustive(self):
+        # Enumerate every eval type Spark defines rather than listing the 
excluded ones, so
+        # a newly added eval type shows up here instead of being silently 
covered.
+        expected = {PythonEvalType.SQL_BATCHED_UDF}
+        if ARROW_TRANSPILE_SUPPORTED:
+            expected.add(PythonEvalType.SQL_ARROW_BATCHED_UDF)
+        # The one vectorized eval type that is transpiled, for the 
element-wise subset only.
+        # ``add_one``'s body (`x + 1`) is inside that subset, which is why it 
appears here;
+        # the subset itself is pinned by
+        # ``pyspark.sql.tests.pandas.test_pandas_udf_transpile``.
+        expected.add(PythonEvalType.SQL_SCALAR_PANDAS_UDF)
+
+        all_eval_types = {
+            name: value
+            for name, value in vars(PythonEvalType).items()
+            if name.startswith("SQL_") and isinstance(value, int)
+        }
+        recorded = {
+            "SQL_BATCHED_UDF",
+            "SQL_ARROW_BATCHED_UDF",
+            "SQL_ARROW_ELEMENTWISE_UDF",
+            "SQL_SCALAR_PANDAS_ELEMENTWISE_UDF",
+            "SQL_SCALAR_PANDAS_ITER_ELEMENTWISE_UDF",
+            "SQL_SCALAR_ARROW_ELEMENTWISE_UDF",
+            "SQL_SCALAR_ARROW_ITER_ELEMENTWISE_UDF",
+            "SQL_SCALAR_PANDAS_UDF",
+            "SQL_GROUPED_MAP_PANDAS_UDF",
+            "SQL_GROUPED_AGG_PANDAS_UDF",
+            "SQL_WINDOW_AGG_PANDAS_UDF",
+            "SQL_SCALAR_PANDAS_ITER_UDF",
+            "SQL_MAP_PANDAS_ITER_UDF",
+            "SQL_COGROUPED_MAP_PANDAS_UDF",
+            "SQL_MAP_ARROW_ITER_UDF",
+            "SQL_GROUPED_MAP_PANDAS_UDF_WITH_STATE",
+            "SQL_GROUPED_MAP_ARROW_UDF",
+            "SQL_COGROUPED_MAP_ARROW_UDF",
+            "SQL_TRANSFORM_WITH_STATE_PANDAS_UDF",
+            "SQL_TRANSFORM_WITH_STATE_PANDAS_INIT_STATE_UDF",
+            "SQL_TRANSFORM_WITH_STATE_PYTHON_ROW_UDF",
+            "SQL_TRANSFORM_WITH_STATE_PYTHON_ROW_INIT_STATE_UDF",
+            "SQL_GROUPED_MAP_ARROW_ITER_UDF",
+            "SQL_GROUPED_MAP_PANDAS_ITER_UDF",
+            "SQL_GROUPED_AGG_PANDAS_ITER_UDF",
+            "SQL_SCALAR_ARROW_UDF",
+            "SQL_SCALAR_ARROW_ITER_UDF",
+            "SQL_GROUPED_AGG_ARROW_UDF",
+            "SQL_WINDOW_AGG_ARROW_UDF",
+            "SQL_GROUPED_AGG_ARROW_ITER_UDF",
+            "SQL_GROUPED_AGG_ARROW_INCREMENTAL_PARTIAL_UDF",
+            "SQL_GROUPED_AGG_ARROW_INCREMENTAL_FINAL_UDF",
+            "SQL_WINDOW_AGG_ARROW_INCREMENTAL_UDF",
+            "SQL_SCALAR_ARROW_INPROCESS_UDF",
+            "SQL_TABLE_UDF",
+            "SQL_ARROW_TABLE_UDF",
+            "SQL_ARROW_UDTF",
+        }
+        self.assertEqual(
+            recorded,
+            set(all_eval_types),
+            "An eval type needs triage: update the recorded inventory and 
admission tests.",
+        )
+        self.assertGreater(len(all_eval_types), 20, "eval-type introspection 
found almost none")
+
+        transpiling = {}
+        with self.sql_conf(_TRANSPILE_ON):
+            for name, value in sorted(all_eval_types.items(), key=lambda kv: 
kv[1]):
+                pudf = UserDefinedFunction(add_one, LongType(), evalType=value)
+                if pudf.transpiled:
+                    transpiling[name] = value
+
+        self.assertEqual(
+            expected,
+            set(transpiling.values()),
+            f"the set of transpiling eval types changed: 
{sorted(transpiling.items())}. "
+            "A per-row scalar Python UDF belongs in _TRANSPILABLE_EVAL_TYPES 
in "
+            "python/pyspark/sql/udf.py and in this test. An eval type that 
hands the "
+            "function a pandas.Series or pyarrow.Array needs more than that: 
the lowerings "
+            "are written against Python scalars, so admitting one means 
auditing every "
+            "construct for batch semantics first (see the 'Scalar pandas UDFs' 
section of "
+            "python/pyspark/sql/transpile.py for how that was done for "
+            "SQL_SCALAR_PANDAS_UDF).",
+        )
+
+    def test_annotated_vectorized_function_via_functions_udf_transpiles(self):
+        # ``functions.udf`` infers SQL_SCALAR_PANDAS_UDF from the pandas 
annotations, and
+        # `s + 1` is inside the element-wise subset, so this is transpiled. 
The pandas
+        # semantics are covered in 
pyspark.sql.tests.pandas.test_pandas_udf_transpile; what
+        # matters here is that arriving via ``functions.udf`` rather than 
``pandas_udf``
+        # reaches the same gate.
+        def series_add_one(s: pd.Series) -> pd.Series:
+            return s + 1
+
+        with self.sql_conf(_TRANSPILE_ON):
+            wrapped = udf(series_add_one, LongType())
+            self.assertEqual(wrapped.evalType, 
PythonEvalType.SQL_SCALAR_PANDAS_UDF)
+            self._assert_transpiled(wrapped._unwrapped, "an annotated pandas 
UDF")
+            df = self.spark.createDataFrame([Row(a=1)])
+            self.assertEqual([2], [r[0] for r in 
df.select(wrapped("a")).collect()])
+
+    def test_scalar_annotations_warn_about_eval_type_inference(self):
+        # Pins a pre-existing wart rather than endorsing it: a scalar 
annotation is not a
+        # vectorized signature, so inference raises and degrades to a warning. 
Annotations
+        # are how callers pin an input-type category, so users will hit this 
and read it as
+        # a transpiler bug.
+        def scalar_add_one(x: int) -> int:
+            return x + 1
+
+        with warnings.catch_warnings(record=True) as caught:
+            warnings.simplefilter("always")
+            with self.sql_conf({"spark.sql.execution.pythonUDF.arrow.enabled": 
True}):
+                wrapped = udf(scalar_add_one, LongType())
+        self.assertEqual(wrapped.evalType, 
PythonEvalType.SQL_ARROW_BATCHED_UDF)
+        self.assertTrue(
+            any("Cannot infer the eval type from type hints" in str(w.message) 
for w in caught),
+            f"expected the eval-type inference warning, got {[str(w.message) 
for w in caught]}",
+        )
+
+    def test_nondeterministic_arrow_udf_does_not_transpile(self):
+        # A plain Catalyst expression could be folded, reordered or 
duplicated, discarding
+        # the nondeterminism barrier.
+        with self.sql_conf(_TRANSPILE_ON):
+            pudf = _arrow_udf(add_one, LongType()).asNondeterministic()
+            self.assertEqual([], pudf.transpiled)
+
+    def test_ansi_disabled_warns_and_does_not_transpile(self):
+        for build in (_pickled_udf, _arrow_udf):
+            with self.subTest(build=build.__name__):
+                with warnings.catch_warnings(record=True) as caught:
+                    warnings.simplefilter("always")
+                    with self.sql_conf(
+                        {
+                            
"spark.sql.experimental.optimizer.transpilePyUDFs": True,
+                            "spark.sql.ansi.enabled": False,
+                        }
+                    ):
+                        pudf = build(add_one, LongType())
+                self.assertEqual([], pudf.transpiled)
+                self.assertTrue(
+                    any("ANSI mode" in str(w.message) for w in caught),
+                    f"expected the ANSI-mode warning, got {[str(w.message) for 
w in caught]}",
+                )
+
+    def test_return_type_unrepresentable_in_arrow_raises_cleanly(self):
+        # The transpile block reads self.returnType, which runs 
_check_return_type inside a
+        # broad `except Exception`. Without a narrower handler the real error 
would surface
+        # as a bogus "Exception transpiling UDF" warning first.
+        with warnings.catch_warnings(record=True) as caught:
+            warnings.simplefilter("always")
+            with self.sql_conf(_TRANSPILE_ON):
+                with self.assertRaises(Exception) as ctx:
+                    _arrow_udf(identity, CalendarIntervalType())
+        self.assertIn("Invalid return type with Arrow-optimized Python UDF", 
str(ctx.exception))
+        spurious = [str(w.message) for w in caught if "Exception transpiling" 
in str(w.message)]
+        self.assertFalse(spurious, f"spurious transpilation warning: 
{spurious}")
+
+
+class ArrowUDFTranspilePlanShapeTests(ArrowUDFTranspileTestsMixin, 
ReusedSQLTestCase):
+    """What the executed plan looks like once a UDF is (or is not) 
rewritten."""
+
+    def test_transpiled_arrow_udf_leaves_no_python_eval_operator(self):
+        with self.sql_conf(_TRANSPILE_ON):
+            pudf = _arrow_udf(add_one, LongType())
+            self._assert_transpiled(pudf, "an Arrow-optimized UDF")
+            df = self.spark.range(3).select(pudf("id").alias("v"))
+            self.assertEqual(Counter(), _eval_python_nodes(df))
+            self.assertEqual([1, 2, 3], [r[0] for r in df.collect()])
+
+    def test_untranspilable_arrow_udf_keeps_arrow_eval_python(self):
+        # Must stay interpreted, and stay on the Arrow operator rather than 
degrading to
+        # the pickled one.
+        with self.sql_conf(_TRANSPILE_ON):
+            pudf = _arrow_udf(floor_halve, LongType())
+            self.assertEqual([], pudf.transpiled)
+            counts = _eval_python_nodes(self.spark.range(4).select(pudf("id")))
+            self.assertEqual(1, counts["ArrowEvalPythonExec"])
+            self.assertEqual(0, counts["BatchEvalPythonExec"])
+
+    def test_untranspilable_pickled_udf_keeps_batch_eval_python(self):
+        with self.sql_conf(_TRANSPILE_ON):
+            pudf = _pickled_udf(floor_halve, LongType())
+            self.assertEqual([], pudf.transpiled)
+            counts = _eval_python_nodes(self.spark.range(4).select(pudf("id")))
+            self.assertEqual(1, counts["BatchEvalPythonExec"])
+            self.assertEqual(0, counts["ArrowEvalPythonExec"])
+
+    def test_transpiled_arrow_udf_in_filter_has_no_python_eval(self):
+        with self.sql_conf(_TRANSPILE_ON):
+            pudf = _arrow_udf(gt_one, BooleanType())
+            self._assert_transpiled(pudf, "a boolean Arrow-optimized UDF")
+            df = self.spark.range(4).filter(pudf("id"))
+            self.assertEqual(Counter(), _eval_python_nodes(df))
+            self.assertEqual([2, 3], [r[0] for r in df.collect()])
+
+    def test_middle_of_arrow_udf_chain_is_not_elided(self):
+        # ConvertToCatalyst keeps a transpilable UDF whose inputs are all 
Python UDFs,
+        # because UDF -> UDF -> UDF pipelines into one Arrow batch.
+        #
+        # Lowering the middle call would leave outer(cast(inner(id) + 1)). 
ExtractPythonUDFs
+        # chains a UDF only when its single child is itself a Python UDF, so 
inner and outer
+        # would land in two ArrowEvalPythonExec operators holding two 
PythonUDF expressions.
+        # Kept, all three run in one operator, so both counts below catch a 
regression.
+        with self.sql_conf(_TRANSPILE_ON):
+            outer = _arrow_udf(floor_halve, LongType())
+            middle = _arrow_udf(add_one, LongType())
+            inner = _arrow_udf(floor_third, LongType())
+            self._assert_transpiled(middle, "the middle UDF of the chain")
+            df = self.spark.range(10).select(outer(middle(inner("id"))))
+            self.assertEqual(1, _eval_python_nodes(df)["ArrowEvalPythonExec"])
+            self.assertEqual(3, _python_udf_expr_count(df))
+            # The contrast: the same middle UDF over a column rather than a 
UDF IS lowered,
+            # so only the outer call is left. Without this the assertion above 
would also
+            # pass if nothing were ever lowered.
+            lowered = self.spark.range(10).select(outer(middle("id")))
+            self.assertEqual(1, _python_udf_expr_count(lowered))
+
+    def test_output_schema_is_identical_with_and_without_transpilation(self):
+        # ConvertToCatalyst substitutes the option with no cast back to the 
declared return
+        # type, relying on the transpiler having cast already.
+        for return_type in (ByteType(), IntegerType(), LongType(), 
DoubleType()):
+            with self.subTest(returnType=return_type):
+                with self.sql_conf(_TRANSPILE_ON):
+                    on = self.spark.range(1).select(_arrow_udf(add_one, 
return_type)("id")).schema
+                with self.sql_conf(_TRANSPILE_OFF):
+                    off = self.spark.range(1).select(_arrow_udf(add_one, 
return_type)("id")).schema
+                self.assertEqual(off, on)
+
+    def test_config_toggled_after_construction_leaves_no_stale_nodes(self):
+        # TranspiledPythonUDF is Unevaluable, so ConvertToCatalyst must strip 
it when the

Review Comment:
   Fixed in ec18766cfd2.
   
   The test now reads the optimized plan (new `_optimized_type` helper) and 
asserts `_eval_python_nodes` is empty with transpilation on. It compares the 
column type only, not nullability: the substituted option can be non-nullable 
where the Python UDF is always nullable, which belongs to the separate 
nullability decision, not this test.
   
   I checked it by removing the final `cast(returnType)` in transpile.py: the 
test now fails (the plan validator rejects the schema change as soon as the 
optimized plan is built), where the old analyzed-plan `.schema` read could not 
see 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/pandas/test_pandas_udf_transpile.py:
##########
@@ -0,0 +1,967 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""
+Transpilation of scalar pandas UDFs (``SQL_SCALAR_PANDAS_UDF``).
+
+Unlike the regular Python UDF eval types, a scalar pandas UDF is genuinely 
vectorized: the
+function is handed one ``pandas.Series`` per argument and must return a 
Series. Most of what
+the transpiler lowers for a Python scalar would therefore be WRONG here, so 
only an
+element-wise subset is rewritten (``+`` ``-`` ``*`` ``%``, unary ``+``/``-``, 
and the
+``Series.isnull()`` family) and everything else falls back to interpreted 
Python. The subset
+and the reasoning behind each exclusion live in the "Scalar pandas UDFs" 
section of
+``python/pyspark/sql/transpile.py``; this module is where those claims are 
checked.
+
+The tests come in three kinds, and the distinction matters when one fails:
+
+``...SubsetTests``
+    Differentials over the supported subset. Both sides run at 
``SQL_SCALAR_PANDAS_UDF``, so
+    the reference is the interpreted behavior of the very UDF being rewritten 
-- not the
+    pickled path, which coerces return values differently.
+
+``...RefusalTests``
+    Bodies outside the subset. These assert two things at once: that no 
Catalyst expression
+    was produced, and that behavior is byte-for-byte what it was with the 
feature off. That
+    second half is the important one, because several of these UDFs *raise* 
today
+    (``if <series>:`` raises ValueError, a scalar body raises UDF_RETURN_TYPE) 
and a rewrite
+    that silently made them succeed would be a behavior change, not a fix.
+
+``...DivergenceTests``
+    The places a transpiled pandas UDF is known to answer differently, pinned 
with the actual
+    values so that a change is a test failure rather than a surprise in 
production. Nearly
+    all come from numpy computing in the input's fixed width: it wraps on 
integer overflow, it
+    keeps ``float32`` through a ``float`` literal, it converts an integral 
column to
+    ``float64`` as soon as a batch contains a NULL. The precision loss is 
batch-dependent:
+    moving the NULL to another partition changes the answer, so the test uses 
an explicit
+    single-partition DataFrame. The exception is the ``%`` int64 boundary, 
where numpy is
+    exact and the lowering raises.
+
+UDF bodies are module-level ``def``s. ``inspect.getsource`` on a lambda passed 
as a call
+argument returns the enclosing statement, whose top-level node is a call 
rather than a lambda,
+so transpilation silently falls back and a differential would compare 
interpreted against
+interpreted and pass while asserting nothing. ``_assert_transpiled`` catches 
that.
+"""
+
+import unittest
+import warnings
+
+from pyspark.sql import Row
+from pyspark.sql import functions as F
+from pyspark.sql.functions import pandas_udf
+from pyspark.sql.tests.arrow.test_arrow_python_udf_transpile import 
_eval_python_nodes
+from pyspark.sql.types import (
+    BooleanType,
+    DecimalType,
+    DoubleType,
+    FloatType,
+    LongType,
+    StringType,
+)
+from pyspark.sql.udf import UserDefinedFunction
+from pyspark.testing.sqlutils import ReusedSQLTestCase
+from pyspark.testing.utils import (
+    have_pandas,
+    have_pyarrow,
+    pandas_requirement_message,
+    pyarrow_requirement_message,
+)
+from pyspark.util import PythonEvalType, is_remote_only
+
+# Transpilation requires both flags, at construction and again in 
ConvertToCatalyst.
+_TRANSPILE_ON = {
+    "spark.sql.experimental.optimizer.transpilePyUDFs": True,
+    "spark.sql.ansi.enabled": True,
+}
+
+# ANSI stays on for the interpreted side so a differential isolates the 
rewrite rather than
+# also flipping overflow semantics.
+_TRANSPILE_OFF = {
+    "spark.sql.experimental.optimizer.transpilePyUDFs": False,
+    "spark.sql.ansi.enabled": True,
+}
+
+# A differential that silently fell back would compare interpreted against 
interpreted and
+# pass for the wrong reason, so these warnings are fatal in the subset tests.
+_BAD_TRANSPILE_WARNING_MARKERS = (
+    "Unable to transpile",
+    "Exception transpiling",
+    "is only supported when ANSI mode is enabled",
+)
+
+# "This side raised instead of returning rows."
+_RAISED = object()
+
+NAN = float("nan")
+
+# 2**53 + 1 is the smallest positive integer float64 cannot represent, so it 
is where the
+# interpreted path's int -> float64 conversion starts losing precision.
+UNREPRESENTABLE_IN_FLOAT64 = 2**53 + 1
+LONG_MAX = 9223372036854775807
+LONG_MIN = -9223372036854775808
+
+
+# --- UDF bodies (supported subset) 
-----------------------------------------------------
+
+
+def add_one(s):
+    return s + 1
+
+
+def add_wide_literal(s):
+    return s + 1000
+
+
+def identity(s):
+    return s
+
+
+def subtract_two(s):
+    return s - 2
+
+
+def times_three(s):
+    return s * 3
+
+
+def negate(s):
+    return -s
+
+
+def unary_plus(s):
+    return +s
+
+
+def mod_three(s):
+    return s % 3
+
+
+def modulo(a, b):
+    return a % b
+
+
+def times_one_and_a_half(s):
+    return s * 1.5
+
+
+def combine(a, b):
+    return a * b - 1
+
+
+def concat_bang(s):
+    return s + "!"
+
+
+def repeat_twice(s):
+    return s * 2
+
+
+def repeat_by_column(s, n):
+    return s * n
+
+
+def prefixed(s):
+    return "x" + s
+
+
+def is_missing(s):
+    return s.isnull()
+
+
+def is_missing_isna(s):
+    return s.isna()
+
+
+def is_present_notnull(s):
+    return s.notnull()
+
+
+def is_present_notna(s):
+    return s.notna()
+
+
+def add_tenth(s):
+    return s + 0.1
+
+
+def times_inf(s):
+    # 1e400 is an inf float constant, so this is inside the allowlist, and 0 * 
inf is NaN.
+    # The only body here that produces NaN from non-NaN input, which is what 
makes it the
+    # probe for the two NaN regimes.
+    return s * 1e400
+
+
+# --- UDF bodies (outside the subset) 
---------------------------------------------------
+
+
+def greater_than_zero(s):
+    # A bool Series interpreted, and a perfectly reasonable pandas UDF -- but 
the scalar
+    # lowering guards NULL operands with raise_error(), which is right for a 
Python scalar
+    # and wrong for a Series (where a missing value simply compares False).
+    return s > 0
+
+
+def equals_five(s):
+    return s == 5
+
+
+def not_equals_zero(s):
+    return s != 0
+
+
+def is_none(s):
+    # Interpreted this is a Python bool, not a Series, so it fails with 
UDF_RETURN_TYPE.
+    # `s.isnull()` is the construct that means per-element.
+    return s is None
+
+
+def is_not_none(s):
+    return s is not None
+
+
+def ternary_none_guard(s):
+    return 0 if s is None else s
+
+
+def branching(s):
+    if s > 0:
+        return 1
+    return 0
+
+
+def logical_not(s):
+    return not s
+
+
+def logical_and(s):
+    return s and s
+
+
+def halved(s):
+    return s / 2
+
+
+def absolute(s):
+    return abs(s)
+
+
+def filled(s):
+    return s.fillna(0)
+
+
+def isnull_of_expression(s):
+    # Only a bare parameter may be the receiver, so this falls back even 
though every
+    # individual piece is in the subset.
+    return (s + 1).isnull()
+
+
+def constant_body(s):
+    # Returns a Python int, not a Series: the interpreted path fails with 
UDF_RETURN_TYPE.
+    return 1
+
+
+def bare_return(s):
+    return
+
+
+def bool_constant(s):
+    return True
+
+
+def free_variable(s):
+    return s + _UNDEFINED_NAME  # noqa: F821
+
+
+def two_statements(s):
+    x = s + 1
+    return x
+
+
[email protected](is_remote_only(), "UDF transpilation is only supported in 
non-Connect Spark.")
[email protected](
+    not have_pandas or not have_pyarrow,
+    pandas_requirement_message or pyarrow_requirement_message,  # type: 
ignore[arg-type]
+)
+class PandasUDFTranspileTestsMixin:
+    """Helpers shared by the suites in this module."""
+
+    def _pandas_udf(self, func, return_type):
+        """Build a scalar pandas UDF without going through type-hint inference.
+
+        ``pandas_udf`` needs either annotations or an explicit functionType, 
and the bodies
+        here are deliberately unannotated so that neither the eval type nor 
the transpiler's
+        input-type categories depend on them.
+        """
+        return UserDefinedFunction(func, return_type, 
evalType=PythonEvalType.SQL_SCALAR_PANDAS_UDF)
+
+    def _assert_transpiled(self, pudf, what):
+        self.assertTrue(
+            pudf.transpiled,
+            f"expected {what} to transpile, but no Catalyst expression was 
produced; "
+            "a parity assertion against the interpreted path would be vacuous",
+        )
+
+    def _values_or_raised(self, df):
+        try:
+            return [row[0] for row in df.collect()], None
+        except Exception as e:  # the exception itself is what we compare
+            return _RAISED, e
+
+    def _differential(self, func, return_type, df, *cols, conf=None):
+        """Run ``func`` with transpilation on and off; return ``(values, 
error)`` for each.
+
+        Both sides run at ``SQL_SCALAR_PANDAS_UDF``, so the reference is the 
interpreted
+        behavior of the very UDF being rewritten.
+        """
+        extra = conf or {}
+        name = getattr(func, "__name__", repr(func))
+
+        with warnings.catch_warnings(record=True) as caught:
+            warnings.simplefilter("always")
+            with self.sql_conf({**_TRANSPILE_ON, **extra}):
+                pudf = self._pandas_udf(func, return_type)
+                self._assert_transpiled(pudf, name)
+                on = self._values_or_raised(df.select(pudf(*cols)))
+        bad = [
+            str(w.message)
+            for w in caught
+            if any(m in str(w.message) for m in _BAD_TRANSPILE_WARNING_MARKERS)
+        ]
+        self.assertFalse(bad, f"unexpected transpile warnings for {name}: 
{bad}")
+
+        with self.sql_conf({**_TRANSPILE_OFF, **extra}):
+            pudf = self._pandas_udf(func, return_type)
+            off = self._values_or_raised(df.select(pudf(*cols)))
+
+        return on, off
+
+    def _assert_matches_interpreted(self, func, return_type, df, *cols, 
conf=None):
+        """Assert transpiled and interpreted agree, including on whether they 
raise."""
+        (on_values, on_error), (off_values, off_error) = self._differential(
+            func, return_type, df, *cols, conf=conf
+        )
+        name = getattr(func, "__name__", repr(func))
+        if off_values is _RAISED:
+            self.assertIs(
+                on_values,
+                _RAISED,
+                f"{name}: interpreted raised {off_error!r} but transpiled 
returned {on_values!r}",
+            )
+            return
+        self.assertIsNot(
+            on_values,
+            _RAISED,
+            f"{name}: transpiled raised {on_error!r} but interpreted returned 
{off_values!r}",
+        )
+        # repr(), not assertEqual: a genuine NaN on both sides 
(preferIntExtensionDtype)
+        # must compare equal here, and float('nan') != float('nan') under 
assertEqual.
+        self.assertEqual(repr(off_values), repr(on_values), f"{name}: 
transpiled != interpreted")
+
+    def _assert_falls_back(self, func, return_type, df, *cols, 
expect_reason=None):
+        """Assert ``func`` is not rewritten AND behaves exactly as it does 
with the flag off.
+
+        The second half is what makes these tests worth having: several of 
these bodies raise
+        interpreted, and "the rewrite made a raising UDF return values" is a 
behavior change
+        even though it looks like an improvement.
+        """
+        name = getattr(func, "__name__", repr(func))
+        with warnings.catch_warnings(record=True) as caught:
+            warnings.simplefilter("always")
+            with self.sql_conf(_TRANSPILE_ON):
+                pudf = self._pandas_udf(func, return_type)
+                self.assertEqual(
+                    [],
+                    pudf.transpiled,
+                    f"{name} was rewritten, but its body is outside the 
element-wise subset "
+                    "a pandas Series supports",
+                )
+                on = self._values_or_raised(df.select(pudf(*cols)))
+        if expect_reason is not None:
+            messages = " ".join(str(w.message) for w in caught)
+            self.assertIn(
+                expect_reason,
+                messages,
+                f"{name}: expected the fallback reason to mention 
{expect_reason!r}, "
+                f"got {messages!r}",
+            )
+
+        with self.sql_conf(_TRANSPILE_OFF):
+            pudf = self._pandas_udf(func, return_type)
+            off = self._values_or_raised(df.select(pudf(*cols)))
+
+        on_values, on_error = on
+        off_values, off_error = off
+        if off_values is _RAISED:
+            self.assertIs(
+                on_values,
+                _RAISED,
+                f"{name}: raises with transpilation off ({off_error!r}) but 
returned "
+                f"{on_values!r} with it on; falling back must preserve the 
failure",
+            )
+            self.assertEqual(
+                type(off_error),
+                type(on_error),
+                f"{name}: fallback changed the exception type",
+            )
+            return
+        self.assertEqual(off_values, on_values, f"{name}: fallback changed the 
result")
+
+    # --- DataFrame fixtures ---
+
+    def _longs(self, *values):
+        return self.spark.createDataFrame([(v,) for v in values], "a bigint")
+
+    def _doubles(self, *values):
+        return self.spark.createDataFrame([(v,) for v in values], "a double")
+
+    def _strings(self, *values):
+        return self.spark.createDataFrame([(v,) for v in values], "a string")
+
+    def _single_partition_longs(self, *values):
+        """One partition, so every row shares a batch.
+
+        The int -> float64 conversion happens per batch, so a NULL only 
degrades the values
+        it is batched with. Tests that pin that behavior must control the 
partitioning.
+        """
+        return self.spark.createDataFrame(
+            self.spark.sparkContext.parallelize([(v,) for v in values], 1), "a 
bigint"
+        )
+
+
+class PandasUDFTranspileSubsetTests(PandasUDFTranspileTestsMixin, 
ReusedSQLTestCase):
+    """Differentials over the bodies the transpiler is allowed to rewrite."""
+
+    def test_arithmetic_on_longs(self):
+        df = self._longs(1, None, 5, -3, 0)
+        for func in (add_one, identity, subtract_two, times_three, negate, 
unary_plus, mod_three):
+            with self.subTest(func=func.__name__):
+                self._assert_matches_interpreted(func, LongType(), df, "a")
+
+    def test_arithmetic_on_narrow_integrals(self):
+        for dtype in ("tinyint", "smallint", "int"):
+            df = self.spark.createDataFrame([(1,), (None,), (-3,), (0,)], f"a 
{dtype}")
+            for func in (add_one, subtract_two, times_three, negate, 
mod_three):
+                with self.subTest(dtype=dtype, func=func.__name__):
+                    self._assert_matches_interpreted(func, LongType(), df, "a")
+
+    def test_integral_options_do_not_duplicate_noncheap_arguments(self):
+        df = self.spark.createDataFrame([(0, 1), (0, None), (1, 3)], "k int, v 
bigint")
+        results = []
+        for conf in (_TRANSPILE_OFF, _TRANSPILE_ON):
+            with self.sql_conf(conf):
+                pudf = self._pandas_udf(add_one, LongType())
+                grouped = df.groupBy("k").agg(F.sum(pudf(F.col("v") + 
1)).alias("total"))
+                left = df.alias("left")
+                right = df.alias("right")
+                joined = left.join(right, pudf(F.col("left.v") + 1) == 
F.col("right.v")).select(
+                    F.col("left.v"), F.col("right.v")
+                )
+                if conf is _TRANSPILE_ON:
+                    self.assertEqual(0, 
sum(_eval_python_nodes(grouped).values()))
+                    self.assertEqual(0, 
sum(_eval_python_nodes(joined).values()))
+                    self.assertNotIn(
+                        "isnan", 
grouped._jdf.queryExecution().optimizedPlan().toString()
+                    )
+                results.append((grouped.orderBy("k").collect(), 
joined.collect()))
+        self.assertEqual(results[0], results[1])
+
+    def test_fractional_options_do_not_duplicate_noncheap_arguments(self):
+        # The NaN normalization and the null check read their input once for a 
float variant,
+        # so a non-cheap argument still transpiles under an aggregate.
+        df = self.spark.createDataFrame(
+            [(0, 1.0), (0, NAN), (1, None), (1, 3.5)], "k int, v double"
+        )
+        for func, return_type in ((add_one, DoubleType()), (is_missing, 
BooleanType())):
+            with self.subTest(func=func.__name__):
+                results = []
+                for conf in (_TRANSPILE_OFF, _TRANSPILE_ON):
+                    with self.sql_conf(conf):
+                        pudf = self._pandas_udf(func, return_type)
+                        grouped = df.groupBy("k").agg(F.max(pudf(F.col("v") + 
1)).alias("m"))
+                        if conf is _TRANSPILE_ON:
+                            self.assertEqual(0, 
sum(_eval_python_nodes(grouped).values()))
+                        results.append(grouped.orderBy("k").collect())
+                self.assertEqual(results[0], results[1])
+
+    def test_arithmetic_on_doubles_including_nan(self):
+        # NaN is the case the isnan-to-NULL normalization exists for: 
interpreted, the result
+        # Series is masked with `series.isnull()`, which is True for NaN, so 
NaN reaches Spark
+        # as NULL. Catalyst would otherwise keep the NaN. NaN propagates 
identically through
+        # every allowlisted operator, so the operator matrix stays on the long 
column above
+        # and this covers the two shapes that differ: an int literal and a 
float one.
+        df = self._doubles(1.0, None, NAN, -2.5, 0.0)
+        for func in (add_one, add_tenth, negate):
+            with self.subTest(func=func.__name__):
+                self._assert_matches_interpreted(func, DoubleType(), df, "a")
+
+    def test_nan_result_becomes_null_not_nan(self):
+        # The explicit form of the above: pin the value, not just the 
agreement, so a
+        # regression that dropped the normalization is legible.
+        df = self._doubles(1.0, NAN, None)
+        with self.sql_conf(_TRANSPILE_ON):
+            pudf = self._pandas_udf(add_one, DoubleType())
+            self._assert_transpiled(pudf, "add_one on doubles")
+            self.assertEqual([2.0, None, None], [r[0] for r in 
df.select(pudf("a")).collect()])
+
+    def test_two_argument_body(self):
+        df = self.spark.createDataFrame(
+            [(2, 3), (None, 4), (5, None), (None, None)], "a bigint, b bigint"
+        )
+        self._assert_matches_interpreted(combine, LongType(), df, "a", "b")
+
+    def test_string_concat_and_repeat(self):
+        df = self._strings("ab", None, "")
+        for func in (concat_bang, prefixed, repeat_twice, identity):
+            with self.subTest(func=func.__name__):
+                self._assert_matches_interpreted(func, StringType(), df, "a")
+
+    def test_string_repeat_by_a_literal_int_transpiles(self):
+        # The one safe repeat count: a literal int can be neither NaN nor NULL 
and is fixed
+        # at transpile time. `repeat_twice` (s * 2) is also in 
test_string_concat_and_repeat;
+        # pinned again here as the positive counterpart to the refusals below.
+        with self.sql_conf(_TRANSPILE_ON):
+            pudf = self._pandas_udf(repeat_twice, StringType())
+            self._assert_transpiled(pudf, "s * 2")
+        self._assert_matches_interpreted(repeat_twice, StringType(), 
self._strings("ab", None), "a")
+
+    def test_string_repeat_by_a_column_falls_back(self):
+        # A bigint count repeats element-wise only while its batch has no 
NULL: with one,
+        # pandas holds the column as float64 and `str * float64` raises 
TypeError, where the
+        # lowered repeat(s, cast(n as int)) would return values. So whether 
the query fails
+        # would depend on batching, and the transpiler must refuse. One 
partition puts both
+        # rows in one batch. (A double count never reaches the refusal: 
`_category` has no
+        # string-by-float variant.)
+        df = self.spark.createDataFrame(
+            self.spark.sparkContext.parallelize([("ab", 2), ("ab", None)], 1),
+            "a string, n bigint",
+        )
+        with self.sql_conf(_TRANSPILE_OFF):
+            off = self._values_or_raised(
+                df.select(self._pandas_udf(repeat_by_column, 
StringType())("a", "n"))
+            )
+        self.assertIs(_RAISED, off[0])
+        self.assertIn("TypeError", str(off[1]))
+        self._assert_falls_back(repeat_by_column, StringType(), df, "a", "n")
+
+    def test_string_repeat_by_a_fractional_literal_falls_back(self):
+        # A float literal (`s * 1.5`) is refused too: repeat by a fractional 
count has no
+        # element-wise meaning, and pandas raises TypeError. Falling back 
preserves that
+        # raise, rather than returning the truncated-repeat the scalar eval 
types still do.
+        self._assert_falls_back(times_one_and_a_half, StringType(), 
self._strings("ab"), "a")
+
+    def test_series_null_check_family(self):
+        for func in (is_missing, is_missing_isna, is_present_notnull, 
is_present_notna):
+            with self.subTest(func=func.__name__):
+                self._assert_matches_interpreted(func, BooleanType(), 
self._longs(1, None), "a")
+
+    def test_series_null_check_treats_nan_as_missing(self):
+        # ``Series.isnull()`` is True for NaN, and by the time the UDF runs a 
NULL in a
+        # double column has already become NaN, so the lowering needs the 
isnan arm to agree.
+        # The value is pinned as well as the agreement, because `isnull(a)` 
alone would also
+        # agree with an interpreted path that had the same bug.
+        df = self._doubles(1.0, None, NAN)
+        self._assert_matches_interpreted(is_missing, BooleanType(), df, "a")
+        with self.sql_conf(_TRANSPILE_ON):
+            pudf = self._pandas_udf(is_missing, BooleanType())
+            self.assertEqual(
+                [False, True, True],
+                [r[0] for r in df.select(pudf("a")).collect()],
+                "NaN must count as missing, like pandas -- isnull(a) alone 
would say False",
+            )
+
+    def test_series_null_check_on_string_column(self):
+        # A string column needs no isnan arm; its missing values are exactly 
the NULLs.
+        self._assert_matches_interpreted(is_missing, BooleanType(), 
self._strings("x", None), "a")
+
+    def test_int_extension_dtype_disables_transpilation(self):
+        # Integral inputs become masked arrays whose derived results can 
retain NaN.
+        # Refuse the regime at construction and again if the conf changes 
afterwards.
+        ext_on = 
{"spark.sql.execution.pythonUDF.pandas.preferIntExtensionDtype": True}
+        with self.sql_conf({**_TRANSPILE_ON, **ext_on}):
+            with warnings.catch_warnings(record=True):
+                warnings.simplefilter("always")
+                self.assertEqual([], self._pandas_udf(add_one, 
LongType()).transpiled)
+                self.assertEqual([], self._pandas_udf(is_missing, 
BooleanType()).transpiled)
+
+    def test_int_extension_dtype_flipped_after_construction_still_agrees(self):
+        # The Python-side gate cannot catch this: the UDF is built under the 
default regime,
+        # so it carries transpiled options, and the conf only changes 
afterwards. The
+        # ConvertToCatalyst re-check is what keeps the result right.
+        df = self._longs(0)
+        with self.sql_conf(_TRANSPILE_ON):
+            pudf = self._pandas_udf(times_inf, DoubleType())
+            self._assert_transpiled(pudf, "times_inf")
+            with self.sql_conf(
+                
{"spark.sql.execution.pythonUDF.pandas.preferIntExtensionDtype": True}
+            ):
+                on = [r[0] for r in df.select(pudf("a")).collect()]
+        with self.sql_conf(
+            {**_TRANSPILE_OFF, 
"spark.sql.execution.pythonUDF.pandas.preferIntExtensionDtype": True}
+        ):
+            off = [
+                r[0] for r in df.select(self._pandas_udf(times_inf, 
DoubleType())("a")).collect()
+            ]
+        # 0 * inf is NaN, and under this conf that NaN reaches Spark as NaN, 
not NULL.
+        self.assertEqual(1, len(off))
+        self.assertTrue(off[0] != off[0], f"expected interpreted NaN, got 
{off!r}")
+        self.assertEqual(repr(off), repr(on), "the ConvertToCatalyst re-check 
did not fall back")
+
+    def 
test_nan_from_infinite_arithmetic_becomes_null_in_the_default_regime(self):
+        # The other half of the pair above: with the conf off, the interpreted 
NaN really is
+        # masked to NULL, which is what the normalization reproduces.
+        self._assert_matches_interpreted(times_inf, DoubleType(), 
self._longs(0, 2), "a")
+
+    def test_pandas_udf_decorator_path_transpiles(self):
+        # What users actually write, via the public API rather than 
UserDefinedFunction.
+        with self.sql_conf(_TRANSPILE_ON):
+            wrapped = pandas_udf(add_one, LongType(), 
PythonEvalType.SQL_SCALAR_PANDAS_UDF)
+            self.assertEqual(wrapped.evalType, 
PythonEvalType.SQL_SCALAR_PANDAS_UDF)
+            self._assert_transpiled(wrapped._unwrapped, "pandas_udf(add_one)")
+            df = self.spark.createDataFrame([Row(a=1)])
+            self.assertEqual([2], [r[0] for r in 
df.select(wrapped("a")).collect()])
+
+    def test_transpiled_pandas_udf_called_with_keyword_arguments(self):
+        # The rewrite references its inputs positionally as _udf_param_N, so
+        # UserDefinedFunction.__call__ resolves kwargs to positional order 
using the parameter
+        # names captured at transpilation time; without that the JVM would 
splice
+        # NamedArgumentExpression nodes into the rewritten tree. Shared with 
the other eval
+        # types but not otherwise covered for any of them, which is why it 
lives here.
+        df = self.spark.createDataFrame(
+            self.spark.sparkContext.parallelize([(2, 3), (None, 4)], 1), "a 
bigint, b bigint"
+        )
+        with self.sql_conf(_TRANSPILE_ON):
+            pudf = self._pandas_udf(combine, LongType())
+            self._assert_transpiled(pudf, "combine")
+            on = [r[0] for r in df.select(pudf(b=df["b"], 
a=df["a"])).collect()]

Review Comment:
   Fixed in ec18766cfd2.
   
   The keyword-call test now uses `ten_a_plus_b` (`a * 10 + b`), which is not 
symmetric in its arguments, and asserts via `_eval_python_nodes` that no Python 
evaluation is left in the executed plan. Expected rows are now `[23, None]`. 
`combine` stays for the differential test.
   
   I checked it with two throwaway mutations of `UserDefinedFunction.__call__`: 
skipping the keyword resolution fails the plan assertion (`0 != 1`), and 
reversing the resolved order fails with `[23, None] != [32, None]`.
   
   ---
   <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: [email protected]

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


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

Reply via email to