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


##########
python/pyspark/sql/transpile.py:
##########
@@ -940,7 +1261,10 @@ def _convert_chunk(self, params: List[str], body: ast.AST 
| None) -> Column:
                                 .when(right_col < 0, lit(-1))
                                 .otherwise(lit(0))
                             )
-                            return sb * pmod(sb * left_col, _abs(right_col))
+                            result = sb * pmod(sb * left_col, _abs(right_col))

Review Comment:
   **Blocking (P1):** Reading this lowering, `a % b` over doubles silently 
returns a wrong value whenever the divisor and a nonzero remainder have 
opposite signs and the divisor is infinite or large enough to absorb the 
remainder. `MathUtils.pmod` returns `(r + n) % n` for a negative remainder 
(`MathUtils.scala:136-139`), so for the row (-3.0, inf) it computes `(-3.0 + 
inf) % inf`, which is NaN, and for (-1e-20, 1e20) it computes `1e20 % 1e20`, 
which is 0.0. Python gives inf and 1e20, and so does pandas (`pd.Series([-3.0]) 
% float('inf')` is `[inf]` on NumPy 1 and NumPy 2). Transpiled pickled UDFs 
already did this on the base branch; this change sends the default 
`functions.udf` eval type and scalar pandas UDFs through the same formula, and 
for pandas the NaN-to-NULL wrap then turns the NaN into NULL. The new tests 
only use `% 3` and finite divisors, so they cannot see it. SPARK-60655 fixed 
the same divergence for pandas API on Spark.
   
   See **Shared repair plan 1** in the review body.



##########
python/pyspark/sql/transpile.py:
##########
@@ -90,6 +90,75 @@
 expression. A draw is never inlined, because those rules check determinism.
 
 An argument the body never reads is not computed at all.
+
+
+Scalar pandas UDFs
+------------------
+A scalar pandas UDF receives one ``pandas.Series`` per argument and must 
return a
+Series, so most of the lowerings above -- which were written against Python
+scalars -- do NOT carry over. Only the subset whose Python-scalar meaning
+coincides with pandas' element-wise meaning is reused, selected by the strict
+allowlist in :func:`_check_series_semantics`: parameter references, ``int`` /
+``float`` / ``str`` constants, ``+`` ``-`` ``*`` ``%``, unary ``+`` / ``-``, 
and
+``<param>.isnull()`` (with the ``.isna()`` / ``.notnull()`` / ``.notna()``
+aliases). Everything else falls back to interpreted Python. The exclusions are
+not conservatism for its own sake -- each one is a construct whose scalar
+lowering would be actively wrong on a Series:
+
+* ``if x:``, ``x and y``, ``not x`` -- pandas raises
+  ``ValueError: The truth value of a Series is ambiguous``. Lowering them to
+  ``CASE WHEN`` / ``AND`` / ``NOT`` would turn a UDF that raises today into one
+  that returns values.
+* ``x is None`` -- always ``False``, because the *Series object* is not None.
+  ``isnull(a)`` would answer a different question; ``x.isnull()`` is the
+  construct that means what ``x is None`` means for a scalar.
+* ``x < y`` and friends -- a missing value compares ``False`` under numpy
+  (never ``NULL``, and never a ``TypeError``, so the ``raise_error`` guard the
+  scalar lowering emits is wrong), and NaN compares ``False`` where Spark 
orders
+  it above every value.
+* a body that never references a parameter (``return 1``) -- the result is a
+  scalar, which the interpreted path rejects with ``UDF_RETURN_TYPE``.
+
+Two pandas-specific value rules are then reproduced explicitly:
+
+* NaN in the result is serialized as NULL -- but only in the default dtype 
regime,
+  where the result Series is numpy-backed and the return path masks it with
+  ``series.isnull()``. A pandas masked extension array (which is what
+  ``spark.sql.execution.pythonUDF.pandas.preferIntExtensionDtype=true`` 
produces,
+  for integral inputs and float arithmetic derived from them) is handed
+  to Arrow with ``mask=None`` instead, and its ``isnull()`` is False for NaN in
+  any case, so there the same NaN arrives as NaN. Catalyst keeps NaN, so a 
numeric
+  body with a fractional category is wrapped in an ``isnan -> NULL`` 
normalization for the
+  default regime -- and transpilation is refused outright when that conf is on,
+  since no single expression covers both. Modulo by zero returns NULL in this 
regime.
+* ``Series.isnull()`` is True for NaN on a numpy-backed Series -- by the time 
the
+  UDF runs, the Arrow-to-pandas conversion has already collapsed a NULL in a
+  fractional column into NaN and pandas cannot tell them apart -- so it lowers 
to
+  ``isnull(a) OR isnan(a)`` for fractional variants, and ``isnull(a)`` 
otherwise. (On a masked
+  extension array ``isnull()`` is the mask alone, but that regime is refused 
per
+  the previous point.)
+
+What remains divergent is numpy's fixed-width arithmetic, and it is documented
+rather than guarded because it cannot be detected without the runtime values.
+Every case is one where the transpiled expression raises or is exact and the
+interpreted one is lossy, silent, or inconsistent:
+
+* integer overflow wraps under numpy where ANSI raises ARITHMETIC_OVERFLOW. 
This
+  also covers the ``%`` boundaries the ``Mod`` lowering notes below

Review Comment:
   **Nit (P3):** `Long.MinValue % -1` does not belong under this bullet. numpy 
returns the exact remainder 0 there (the new 
`test_modulo_overflow_boundary_raises_where_numpy_wraps` itself pins `([0], 
None)` as the interpreted result), and Spark's native ANSI `%` returns 0 as 
well, because only integral division checks MIN / -1. The transpiled 
ARITHMETIC_OVERFLOW comes from the lowering's intermediate `sign(b) * a`, so in 
this case the transpiled side raises on a valid input while the interpreted one 
is exact. That is the reverse of what this paragraph says, and of the 
transpilePyUDFs doc ('it is because numpy arithmetic is fixed-width ... the 
transpiled expression is the exact or ANSI-correct one'), the test name and the 
`PandasUDFTranspileDivergenceTests` docstring. If the `%` lowering moves to 
Python-style modulo, the boundary goes away, and these sentences should drop it 
rather than be reworded.
   
   See **Shared repair plan 1** in the review body.



##########
python/pyspark/sql/transpile.py:
##########
@@ -1092,6 +1427,10 @@ def _transpile_from_ast(
                 UserWarning,
                 stacklevel=2,
             )
+        if series_semantics and body_cat in ("float", "numeric"):
+            # The default pandas return conversion masks NaN as NULL. Integral 
variants
+            # cannot produce NaN and must avoid duplicating their argument 
references.
+            converted = when(isnan(converted.cast("double")), 
lit(None)).otherwise(converted)

Review Comment:
   **Nit (P3):** The integral variants now skip this wrap, but the fractional 
ones still reference `converted` twice here, and the float-receiver null check 
at line 880 does the same with its parameter. ConvertToCatalyst counts both 
reads, so an argument that is not cheap to repeat is owed one evaluation 
(`mustPreEvaluate`), and where no pre-evaluation column fits (under a grouped 
aggregate, in a join condition, in a command, or above an aggregate) it keeps 
the Python UDF. By the plan rules, `df.groupBy('k').agg(F.sum(pudf(F.col('v') + 
1)))` with `pudf` returning `s + 1` over a double `v` stays an ArrowEvalPython, 
while the bigint version transpiles, as 
`test_integral_options_do_not_duplicate_noncheap_arguments` checks. Where the 
option is substituted with a cheap argument, subexpression elimination does not 
share this CASE WHEN's ELSE value with its condition, so the body runs twice 
per row. For a 'float'-category body, which is always Float or Double, 
`nanvl(converted, lit(None))` 
 gives the same values reading it once (NaNvl casts the NULL to the body's 
type), and `isnull(nanvl(subject.cast('double'), lit(None)))` does the same for 
the null check; only the 'numeric' catch-all still needs the CASE form.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59724#discussion_r4573104039).
   
   **Verification:**
   - **Behavior:** With transpilation and ANSI on, a scalar pandas UDF 
returning `s + 1` over a double column, called as pudf(F.col('v') + 1) inside a 
grouped sum and inside a join condition, runs with no Python evaluation in the 
plan and returns the interpreted results.
   - **Regression:** Over double columns holding NaN and NULL, `s + 1`, `s * 
1e400` and `s.isnull()` still give NULL for NaN results and True for NaN and 
NULL inputs, matching the interpreted pandas results.



##########
python/pyspark/sql/tests/arrow/test_arrow_python_udf_transpile.py:
##########
@@ -0,0 +1,1050 @@
+#
+# 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 (``python/pyspark/worker.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.
+        #
+        # Asserted on the PythonUDF expression count, not the operator count: 
the chain is
+        # evaluated as a pipeline inside a single ArrowEvalPythonExec, so the 
operator count
+        # is 1 whether or not the middle call was lowered. Three PythonUDF 
expressions means

Review Comment:
   **Nit (P3):** If the middle call were lowered, the plan would be 
`outer(cast(inner(id) + 1))`, and 
`ExtractPythonUDFs.shouldExtractUDFExpressionTree` 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. The 
one-operator, one-expression outcome described here belongs to the contrast 
query `outer(middle('id'))`; the assertions below still catch the regression, 
so only the comment needs fixing. Two other comments in this file are off in 
the same way: the module docstring (line 28) puts the Arrow `pa.array` build 
and its safe-cast fallback in `python/pyspark/worker.py`, but they are in 
`ArrowBatchedUDFArrowHandler.run` in `python/pyspark/eval_handlers/_arrow.py`; 
and the comment at lines 898-899 says `_category` lumps int and float into one 
'numeric' bucket, but `x + 0.5` is 'float', and the check passes because 
`cast_ok` accepts any numeric category for a non-decimal n
 umeric return type.
   
   **Verification:**
   - **Inspection:** The module docstring names 
python/pyspark/eval_handlers/_arrow.py for the Arrow return conversion, the 
chain test's comment states the two-operator, two-expression outcome of 
lowering the middle call, and the pickled-divergence comment attributes the 
pass to the within-numeric return-type policy.



##########
python/pyspark/sql/transpile.py:
##########
@@ -299,6 +384,177 @@ 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 a numeric COLUMN is refused under series 
semantics in
+# `_convert_chunk`, because a Series count is unsound in every batch shape: 
pandas raises
+# TypeError on any genuine float value (so `_masked_arith_op` only succeeds 
when the whole
+# batch is missing, yielding NULL), while the lowered `repeat(s, cast(n as 
int))` returns a
+# repeated string for a real value and raises CAST_OVERFLOW for a NaN -- so an 
all-missing
+# batch turns a NULL-returning query into an error. 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() | ast.IsNot(), *_]):

Review Comment:
   **Nit (P3):** This arm also matches `IsNot`, but the message only fits `is`: 
`s is not None` is always True, and its per-element form is `x.notnull()`, so a 
user who wrote it is pointed at the inverse check. The generic `Compare` arm 
below has the same problem for `==` and `!=`: under `!=` a missing value and 
NaN compare True (`pd.Series([float('nan')]) != 5` is `[True]`), and the scalar 
`==`/`!=` lowering that it contrasts with never raises on NULL; only the 
ordering comparisons do. Making both messages operator-aware, or limiting the 
ordering wording to `<` `<=` `>` `>=`, fixes it.
   
   **Verification:**
   - **Behavior:** Defining scalar pandas UDFs with transpilation on whose 
bodies are `s is not None`, `s != 0` and `s < 0` emits fallback warnings that 
name `x.notnull()`, pandas equality and the ordering behavior respectively, and 
each UDF still behaves as it does with transpilation off.



##########
python/pyspark/sql/tests/arrow/test_arrow_python_udf_transpile_type_canary.py:
##########
@@ -0,0 +1,651 @@
+#
+# 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.
+#
+"""
+A canary over every Spark data type, for UDF transpilation.
+
+Two allowlists decide what the transpiler rewrites: a return-type check in
+``python/pyspark/sql/transpile.py`` (numeric / string / boolean / binary), and 
an input-type
+category check in ``ResolveTranspiledPythonUDFOptions.scala`` with a ``case _ 
=> false``
+catch-all. Being allowlists, a data type added tomorrow falls back to 
interpreted Python
+automatically -- safe, but silent: nobody is told the new type was never 
considered.
+
+So this module enumerates the concrete ``DataType`` subclasses 
``pyspark.sql.types`` exports
+and demands an entry for each, making a new type fail
+``test_data_type_inventory_is_complete`` with instructions.
+
+Enumeration is introspective because ``pyspark.sql.types._atomic_types`` is 
NOT exhaustive
+(it omits ``TimeType``, ``GeometryType``, ``GeographyType``, 
``CalendarIntervalType``), so a
+canary keyed on it would stop covering new types -- the exact failure this 
file prevents.
+
+Triaging a new type
+-------------------
+1. Add an instance to ``_SAMPLES`` with the body category whose lowering could 
target it.
+2. Run this module; the verdict tests report the observed verdict.
+3. ``NO_TRANSPILE``, ``REJECTED_BY_ARROW`` or ``REJECTED_CHAR_VARCHAR``: 
record it and
+   stop.
+4. ``TRANSPILES``: verify parity against the interpreted path on all three 
eval types *before*
+   recording. The pickled path NULLs a mismatched return value where Arrow 
raises or
+   converts; the golden matrix in ``python/pyspark/sql/tests/coercion/`` is 
the authority. If
+   they disagree, tighten the body-vs-return-type check in ``transpile.py`` 
instead.
+
+The tables were derived by observation. They are expressed for the pickled 
eval type, with
+the Arrow expectations derived from them, which pins the property that 
matters: Arrow UDFs
+admit exactly the same types as pickled ones, except where Arrow cannot 
express the return
+type at all.
+"""
+
+import unittest
+
+from pyspark.errors import PySparkNotImplementedError
+from pyspark.sql import types as T
+from pyspark.sql.pandas.types import to_arrow_type
+from pyspark.sql.tests.arrow.test_arrow_python_udf_transpile import (
+    _TRANSPILE_OFF,
+    _TRANSPILE_ON,
+    ARROW_TRANSPILE_SUPPORTED,
+    ArrowUDFTranspileTestsMixin,
+    _eval_python_nodes,
+)
+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
+
+TRANSPILES = "TRANSPILES"
+NO_TRANSPILE = "NO_TRANSPILE"
+# The return type cannot be expressed as an Arrow type at all, so an 
Arrow-optimized UDF
+# declaring it fails in _check_return_type before transpilation is even a 
question.
+REJECTED_BY_ARROW = "REJECTED_BY_ARROW"
+# CHAR/VARCHAR are rejected at UDF construction for every eval type
+# (CHAR_VARCHAR_NOT_SUPPORTED_IN_PYTHON): Python has only unconstrained 
strings, so there
+# is no return verdict to have.
+REJECTED_CHAR_VARCHAR = "REJECTED_CHAR_VARCHAR"
+# The type cannot appear in a DataFrame schema, so there is no input-side 
verdict to have.
+NOT_A_COLUMN_TYPE = "NOT_A_COLUMN_TYPE"
+
+_PICKLED = PythonEvalType.SQL_BATCHED_UDF
+_ARROW = PythonEvalType.SQL_ARROW_BATCHED_UDF
+_PANDAS = PythonEvalType.SQL_SCALAR_PANDAS_UDF
+
+# Classes exported from pyspark.sql.types that are not usable column types: 
the abstract
+# root, StructField (a field descriptor rather than a type), and the bare 
UserDefinedType
+# base (its sqlType() raises NotImplementedError; real UDTs are user-authored 
subclasses
+# this module can't enumerate). None of these are in __all__, so 
_concrete_data_type_classes

Review Comment:
   **Nit (P3):** `pyspark.sql.types.__all__` does list `DataType` and 
`StructField` (only `UserDefinedType` is absent), and `StructField` subclasses 
`DataType`, so without this set `_concrete_data_type_classes` would return both 
and `test_data_type_inventory_is_complete` would demand samples for them; the 
function's own docstring says they need naming. The comment invites deleting a 
set the test depends on. Separately, the 'Verdict per INPUT column type' block 
at lines 218-222 sits directly above `_EXPECTED_PANDAS_RETURN_VERDICT`, a 
return-type table, and `_EXPECTED_INPUT_VERDICT` follows with no comment of its 
own.
   
   **Verification:**
   - **Inspection:** The canary's exclusion-set comment states that DataType 
and StructField are exported and must be excluded, and each verdict table's 
comment describes that table.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -706,7 +706,26 @@ object SQLConf {
         "UDF construction. Transpiled UDFS attempt to match the Python 
functionality but " +
         "may not be 100% equivalent. Some known differences include: overflows 
from input types " +
         "(you can precast to decimal to avoid), type coercion on comparison, 
and implicit " +
-        "returns. This initial version only works with non-Connect Spark; 
Spark Connect " +
+        "returns. Applies to regular Python UDFs whether or not they are 
Arrow-optimized, " +
+        "except when 
spark.sql.legacy.execution.pythonUDF.pandas.conversion.enabled is set, " +

Review Comment:
   **Nit (P3):** As written, the 'except when ... is set' clause qualifies 
'Applies to regular Python UDFs whether or not they are Arrow-optimized', so it 
reads as turning transpilation off for every regular Python UDF. Both refusals 
test only `SQL_ARROW_BATCHED_UDF` (`udf.py:318-324`, 
`Optimizer.scala:1356-1357`), and 
`test_legacy_pandas_conversion_does_not_disable_the_pickled_path` and the 
ConvertToCatalystSuite case 'still transpiles a pickled UDF when legacy pandas 
conversion is enabled' pin that pickled UDFs keep transpiling. Saying that the 
conf disables transpilation of Arrow-optimized UDFs only, as the 
preferIntExtensionDtype sentence below does for scalar pandas UDFs, removes the 
ambiguity.
   
   **Verification:**
   - **Inspection:** The transpilePyUDFs doc says the legacy pandas conversion 
conf disables transpilation of Arrow-optimized UDFs only, which matches the 
refusal in the UDF constructor and in ConvertToCatalyst.



##########
python/pyspark/sql/udf.py:
##########
@@ -274,8 +306,33 @@ def _conf_is_true(key: str, default: Optional[str] = None) 
-> bool:
         try:
             transpile_enabled = (
                 deterministic
-                and evalType == PythonEvalType.SQL_BATCHED_UDF
+                and evalType in _TRANSPILABLE_EVAL_TYPES
                 and 
_conf_is_true("spark.sql.experimental.optimizer.transpilePyUDFs", "false")
+                # The legacy pandas conversion regime routes an 
Arrow-optimized UDF's
+                # inputs and outputs through pandas, which changes what the 
Python
+                # function actually receives: an integer column containing 
NULL arrives
+                # as float64 NaN, so `x is None` is False where the transpiled
+                # `isnull(a)` is true. The transpiler models the non-legacy 
Arrow
+                # semantics only, so refuse to rewrite in that regime. This 
conf can also
+                # be flipped after construction, so ConvertToCatalyst repeats 
the check.
+                and not (
+                    evalType == PythonEvalType.SQL_ARROW_BATCHED_UDF
+                    and _conf_is_true(
+                        
"spark.sql.legacy.execution.pythonUDF.pandas.conversion.enabled",
+                        "false",
+                    )
+                )
+                # This conf makes integral inputs pandas masked extension 
arrays. Results
+                # derived from them can retain NaN, while the default 
numpy-backed return
+                # conversion masks NaN to NULL 
(PandasToArrowConversion._convert_column_legacy).
+                # Refuse this regime, and re-check in ConvertToCatalyst if it 
changes later.
+                and not (
+                    evalType == PythonEvalType.SQL_SCALAR_PANDAS_UDF

Review Comment:
   **Nit (P3):** Nothing on the Python side checks that this gate stays limited 
to scalar pandas UDFs. The Python suites set `preferIntExtensionDtype` only 
with scalar pandas UDFs, and ConvertToCatalystSuite's 'int extension dtype does 
not disable the pickled or Arrow-optimized paths' exercises only the JVM 
re-check, which never sees this constructor gate. If this `evalType == 
PythonEvalType.SQL_SCALAR_PANDAS_UDF` clause were dropped, every pickled and 
Arrow-optimized UDF built with the conf on would silently stop transpiling, and 
the only sign would be a missing speedup. The legacy pandas conversion gate 
above has `test_legacy_pandas_conversion_does_not_disable_the_pickled_path`; a 
matching test that builds a pickled and an Arrow-optimized UDF with this conf 
on and asserts that both carry options would close the gap.
   
   **Verification:**
   - **Regression:** With transpilation, ANSI and preferIntExtensionDtype on, a 
pickled UDF and an Arrow-optimized UDF returning `x + 1` both carry transpiled 
options, and the test fails if the gate refuses those eval types.



##########
python/pyspark/sql/tests/pandas/test_pandas_udf_transpile.py:
##########
@@ -0,0 +1,920 @@
+#
+# 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. They 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.
+
+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 is_none(s):
+    # Always False interpreted: the Series object is not None. `s.isnull()` is 
the
+    # construct that means per-element.
+    return s is 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_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 Series count makes `str * numeric` unsound in every batch shape: 
pandas raises
+        # TypeError on any genuine float (so it only succeeds, as NULL, for an 
all-missing
+        # batch), while the lowered repeat(s, cast(n as int)) returns a 
repeated string for a
+        # real value and CAST_OVERFLOW for a NaN. So an all-missing batch 
would turn a
+        # NULL-returning query into an error -- the cardinal sin. The 
transpiler must refuse.
+        df = self.spark.createDataFrame(
+            self.spark.sparkContext.parallelize([("ab", float("nan"))], 1), "a 
string, b double"
+        )
+        with self.sql_conf(_TRANSPILE_ON):
+            pudf = self._pandas_udf(repeat_by_column, StringType())
+            self.assertEqual([], pudf.transpiled, "string-repeat by a column 
must not transpile")
+            on = self._values_or_raised(df.select(pudf("a", "b")))
+        with self.sql_conf(_TRANSPILE_OFF):
+            off = self._values_or_raised(
+                df.select(self._pandas_udf(repeat_by_column, 
StringType())("a", "b"))
+            )
+        # The all-NaN batch: interpreted masks it to NULL, and falling back 
preserves that.
+        self.assertEqual(([None], None), off)

Review Comment:
   **Nit (P3):** This assertion holds only on pandas 2. On pandas 3 the string 
column reaches the UDF as the `str` dtype (the Arrow-to-pandas conversion 
passes strings through `to_pandas()`), and `Series(str) * Series(float64)` 
raises 'Can only string multiply by an integer.' even for an all-NaN batch 
(pandas 3.1.1 with pyarrow 26.0.1), so the scheduled pandas 3 job fails here. 
The fixture also cannot exercise the guard: a double count drops the (string, 
float) variant in `_category` before `_reject_series_string_repeat` runs, and 
the (string, integer) option binds only integral columns, so only the 
`pudf.transpiled == []` check would notice the guard's removal. The case the 
guard exists for is a bigint count in a batch that also holds a NULL: pandas 
then sees float64 and raises TypeError on both pandas lines, where the 
unguarded option would return `['abab', NULL]`. A NULL-free int64 batch repeats 
element-wise, so the hazard is batch dependence, not the NaN CAST_OVERFLOW that 
the co
 mments here, on `_SERIES_SAFE_BINOPS` and on `_reject_series_string_repeat` 
describe.
   
   **Verification:**
   - **Regression:** With transpilation and ANSI on, a scalar pandas UDF `s * 
n` over a string column and a bigint count column whose single batch holds a 
value and a NULL produces no transpiled option and raises TypeError both 
interpreted and with transpilation requested, on pandas 2.2 and on pandas 3; 
without the string-repeat guard the same query would return values, so the test 
fails.
   - **Inspection:** The refusal's comments state that an integral count 
repeats element-wise only in a batch without NULLs, and none of them mentions a 
CAST_OVERFLOW for a NaN count.



##########
python/pyspark/sql/tests/pandas/test_pandas_udf_transpile.py:
##########
@@ -0,0 +1,920 @@
+#
+# 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. They 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.
+
+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 is_none(s):
+    # Always False interpreted: the Series object is not None. `s.isnull()` is 
the
+    # construct that means per-element.
+    return s is 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_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 Series count makes `str * numeric` unsound in every batch shape: 
pandas raises
+        # TypeError on any genuine float (so it only succeeds, as NULL, for an 
all-missing
+        # batch), while the lowered repeat(s, cast(n as int)) returns a 
repeated string for a
+        # real value and CAST_OVERFLOW for a NaN. So an all-missing batch 
would turn a
+        # NULL-returning query into an error -- the cardinal sin. The 
transpiler must refuse.
+        df = self.spark.createDataFrame(
+            self.spark.sparkContext.parallelize([("ab", float("nan"))], 1), "a 
string, b double"
+        )
+        with self.sql_conf(_TRANSPILE_ON):
+            pudf = self._pandas_udf(repeat_by_column, StringType())
+            self.assertEqual([], pudf.transpiled, "string-repeat by a column 
must not transpile")
+            on = self._values_or_raised(df.select(pudf("a", "b")))
+        with self.sql_conf(_TRANSPILE_OFF):
+            off = self._values_or_raised(
+                df.select(self._pandas_udf(repeat_by_column, 
StringType())("a", "b"))
+            )
+        # The all-NaN batch: interpreted masks it to NULL, and falling back 
preserves that.
+        self.assertEqual(([None], None), off)
+        self.assertEqual(off, on)
+
+    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()]
+        with self.sql_conf(_TRANSPILE_OFF):
+            pudf = self._pandas_udf(combine, LongType())
+            off = [r[0] for r in df.select(pudf(b=df["b"], 
a=df["a"])).collect()]
+        self.assertEqual(off, on)
+        self.assertEqual([5, None], on)
+
+
+class PandasUDFTranspileRefusalTests(PandasUDFTranspileTestsMixin, 
ReusedSQLTestCase):
+    """Bodies outside the subset must fall back, preserving behavior 
exactly."""
+
+    def test_comparisons_fall_back(self):
+        self._assert_falls_back(
+            greater_than_zero,
+            BooleanType(),
+            self._longs(1, None, -1),
+            "a",
+            expect_reason="a comparison",
+        )
+        self._assert_falls_back(equals_five, BooleanType(), self._longs(5, 
None), "a")
+
+    def test_is_none_falls_back(self):
+        # Interpreted this returns False for every row (the Series object is 
not None), so a

Review Comment:
   **Nit (P3):** Interpreted, this body does not return False for every row: `s 
is None` is a Python bool, and `PandasScalarUDFHandler.run` rejects any result 
without `__len__` with UDF_RETURN_TYPE (`eval_handlers/_pandas.py:114-122`), so 
the query fails. The reason to refuse it is that a rewrite would turn that 
failure into values, which is what this suite protects; the `is_none` body 
comment at line 220 says the same wrong thing. Conversely, `ternary_none_guard` 
(`0 if s is None else s`) returns `s` unchanged and never raises, although 
`test_control_flow_falls_back_and_still_raises` lists it among the bodies whose 
failure must survive. Both tests pass because `_assert_falls_back` accepts 
either outcome.
   
   **Verification:**
   - **Inspection:** No comment in the scalar pandas transpile tests says that 
an interpreted `s is None` body returns False, and the control-flow test's 
comment matches each body's interpreted outcome.



##########
python/pyspark/sql/tests/pandas/test_pandas_udf_transpile.py:
##########
@@ -0,0 +1,920 @@
+#
+# 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. They 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.
+
+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 is_none(s):
+    # Always False interpreted: the Series object is not None. `s.isnull()` is 
the
+    # construct that means per-element.
+    return s is 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_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 Series count makes `str * numeric` unsound in every batch shape: 
pandas raises
+        # TypeError on any genuine float (so it only succeeds, as NULL, for an 
all-missing
+        # batch), while the lowered repeat(s, cast(n as int)) returns a 
repeated string for a
+        # real value and CAST_OVERFLOW for a NaN. So an all-missing batch 
would turn a
+        # NULL-returning query into an error -- the cardinal sin. The 
transpiler must refuse.
+        df = self.spark.createDataFrame(
+            self.spark.sparkContext.parallelize([("ab", float("nan"))], 1), "a 
string, b double"
+        )
+        with self.sql_conf(_TRANSPILE_ON):
+            pudf = self._pandas_udf(repeat_by_column, StringType())
+            self.assertEqual([], pudf.transpiled, "string-repeat by a column 
must not transpile")
+            on = self._values_or_raised(df.select(pudf("a", "b")))
+        with self.sql_conf(_TRANSPILE_OFF):
+            off = self._values_or_raised(
+                df.select(self._pandas_udf(repeat_by_column, 
StringType())("a", "b"))
+            )
+        # The all-NaN batch: interpreted masks it to NULL, and falling back 
preserves that.
+        self.assertEqual(([None], None), off)
+        self.assertEqual(off, on)
+
+    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()]
+        with self.sql_conf(_TRANSPILE_OFF):
+            pudf = self._pandas_udf(combine, LongType())
+            off = [r[0] for r in df.select(pudf(b=df["b"], 
a=df["a"])).collect()]
+        self.assertEqual(off, on)
+        self.assertEqual([5, None], on)
+
+
+class PandasUDFTranspileRefusalTests(PandasUDFTranspileTestsMixin, 
ReusedSQLTestCase):
+    """Bodies outside the subset must fall back, preserving behavior 
exactly."""
+
+    def test_comparisons_fall_back(self):
+        self._assert_falls_back(
+            greater_than_zero,
+            BooleanType(),
+            self._longs(1, None, -1),
+            "a",
+            expect_reason="a comparison",
+        )
+        self._assert_falls_back(equals_five, BooleanType(), self._longs(5, 
None), "a")
+
+    def test_is_none_falls_back(self):
+        # Interpreted this returns False for every row (the Series object is 
not None), so a
+        # rewrite to isnull(a) would change results rather than fix a bug.
+        self._assert_falls_back(
+            is_none,
+            BooleanType(),
+            self._longs(1, None),
+            "a",
+            expect_reason="`is` / `is not` test",
+        )
+
+    def test_control_flow_falls_back_and_still_raises(self):
+        # `if <series>:` raises ValueError interpreted. The rewrite must not 
turn that into a
+        # working query -- _assert_falls_back checks the failure survives.
+        for func in (branching, ternary_none_guard, logical_not, logical_and):
+            with self.subTest(func=func.__name__):
+                self._assert_falls_back(func, LongType(), self._longs(1, 
None), "a")
+
+    def test_unlowered_operator_falls_back(self):
+        # `**`, `/` and `//` all fail the same `isinstance(op, 
_SERIES_SAFE_BINOPS)` check, so
+        # one of them exercises the branch; `/` is the one users are most 
likely to write.
+        self._assert_falls_back(halved, LongType(), self._longs(4, None), "a")
+
+    def test_other_calls_fall_back(self):
+        for func in (absolute, filled):
+            with self.subTest(func=func.__name__):
+                self._assert_falls_back(
+                    func,
+                    LongType(),
+                    self._longs(-4, None),
+                    "a",
+                    expect_reason="function call other than",
+                )
+
+    def test_null_check_on_non_parameter_receiver_falls_back(self):
+        self._assert_falls_back(isnull_of_expression, BooleanType(), 
self._longs(1, None), "a")
+
+    def test_scalar_bodies_fall_back_and_still_raise(self):
+        # A body that never references a parameter produces a Python scalar, 
and the
+        # interpreted path rejects that with UDF_RETURN_TYPE. Returning a 
value per row would
+        # be a nicer outcome and a behavior change, so it must stay a failure. 
Three distinct
+        # refusal branches: no parameter reference, a bare `return`, and a 
bool constant.
+        for func in (constant_body, bare_return, bool_constant):
+            with self.subTest(func=func.__name__):
+                self._assert_falls_back(func, LongType(), self._longs(1), "a")
+
+    def test_free_variable_falls_back(self):
+        self._assert_falls_back(
+            free_variable,
+            LongType(),
+            self._longs(1),
+            "a",
+            expect_reason="free variable",
+        )
+
+    def test_early_return_reports_if_as_the_reason(self):
+        self._assert_falls_back(
+            branching, LongType(), self._longs(1, None), "a", 
expect_reason="an `if`"
+        )
+
+    def test_multi_statement_body_reports_the_accurate_reason(self):
+        # The Series allowlist walk only visits the first statement, so it 
must check the
+        # statement count first -- otherwise a two-statement body is refused 
as "an
+        # unsupported `Assign` node" (its first statement) rather than for the 
real reason,
+        # and that warning is the only place the user learns why the rewrite 
did not happen.
+        self._assert_falls_back(
+            two_statements,
+            LongType(),
+            self._longs(1, None),
+            "a",
+            expect_reason="more than one top-level statement",
+        )
+
+
+class PandasUDFTranspileDivergenceTests(PandasUDFTranspileTestsMixin, 
ReusedSQLTestCase):
+    """The known differences, pinned with values so a change fails a test.
+
+    Each is numpy computing in the input's fixed width where ANSI Catalyst is 
exact. They are
+    documented rather than guarded because detecting them needs the runtime 
values, not the
+    types. See the "Scalar pandas UDFs" section of 
python/pyspark/sql/transpile.py.
+    """
+
+    def _pin_divergence(self, func, return_type, df, *cols, conf=None):
+        """Return ``(interpreted, transpiled)``, each a value list or a raised 
exception.
+
+        Deliberately the inverse of ``_assert_matches_interpreted``: here the 
two sides are
+        expected to differ, and the point is to record how.
+        """
+        extra = conf or {}
+        with self.sql_conf({**_TRANSPILE_OFF, **extra}):
+            interpreted = self._values_or_raised(
+                df.select(self._pandas_udf(func, return_type)(*cols))
+            )
+        with self.sql_conf({**_TRANSPILE_ON, **extra}):
+            pudf = self._pandas_udf(func, return_type)
+            self._assert_transpiled(pudf, getattr(func, "__name__", 
repr(func)))
+            transpiled = self._values_or_raised(df.select(pudf(*cols)))
+        return interpreted, transpiled
+
+    def _mods(self, *pairs):
+        return self.spark.createDataFrame(
+            self.spark.sparkContext.parallelize(list(pairs), 1), "a bigint, b 
bigint"
+        )
+
+    def test_modulo_by_zero_matches_numpy_missing_value(self):
+        for schema, values, return_type in (
+            ("a bigint, b bigint", [(5, 0), (None, 0), (7, -3), (-7, 3)], 
LongType()),
+            ("a double, b double", [(5.0, 0.0), (5.0, -0.0), (7.0, -3.0)], 
DoubleType()),
+        ):
+            with self.subTest(schema=schema):
+                df = self.spark.createDataFrame(values, schema)
+                self._assert_matches_interpreted(modulo, return_type, df, "a", 
"b")
+
+    def test_modulo_overflow_boundary_raises_where_numpy_wraps(self):
+        # The lowering is `sign(b) * pmod(sign(b) * a, abs(b))`, whose 
intermediate negation
+        # overflows for a = Long.MinValue with b < 0. Same class as the 
arithmetic overflow
+        # above, and already noted on the Mod lowering for the scalar eval 
types.
+        interpreted, transpiled = self._pin_divergence(
+            modulo, LongType(), self._mods((LONG_MIN, -1)), "a", "b"
+        )
+        self.assertEqual(([0], None), interpreted)
+        self.assertIs(transpiled[0], _RAISED)
+        self.assertIn("ARITHMETIC_OVERFLOW", str(transpiled[1]))
+
+    def test_modulo_agrees_away_from_the_boundaries(self):
+        # The sign rule itself matches: numpy `%` takes the divisor's sign, 
like Python, which
+        # is what the pmod-based lowering reproduces. Pinned so the boundary 
tests above are
+        # not mistaken for "modulo is broken".
+        self._assert_matches_interpreted(
+            modulo,
+            LongType(),
+            self._mods((7, -3), (-7, 3), (7, 3), (-7, -3), (LONG_MIN, 3), 
(LONG_MAX, -1)),
+            "a",
+            "b",
+        )
+
+    def test_narrow_integer_overflow_and_wide_literal(self):
+        for dtype, maximum in (("tinyint", 127), ("smallint", 32767), ("int", 
2**31 - 1)):
+            df = self.spark.createDataFrame([(maximum,)], f"a {dtype}")
+            interpreted, transpiled = self._pin_divergence(add_one, 
LongType(), df, "a")
+            self.assertEqual(([-maximum - 1], None), interpreted)
+            if dtype == "int":
+                self.assertIs(transpiled[0], _RAISED)
+                self.assertIn("ARITHMETIC_OVERFLOW", str(transpiled[1]))
+            else:
+                self.assertEqual(([maximum + 1], None), transpiled)
+
+        df = self.spark.createDataFrame([(1,)], "a tinyint")
+        interpreted, transpiled = self._pin_divergence(add_wide_literal, 
LongType(), df, "a")
+        self.assertIs(interpreted[0], _RAISED)

Review Comment:
   **Nit (P3):** Only NumPy 2 raises here. Under NumPy 1.x value-based casting, 
an int8 Series plus 1000 widens to int16 and gives `[1001]` (NumPy 1.26.4 with 
pandas 2.2.0), which matches the transpiled `[1001]`; NumPy 2.5.4 raises 
'OverflowError: Python integer 1000 out of bounds for int8'. PySpark's minimum 
is NumPy 1.23.2, and the scheduled minimum-dependency job runs `pyspark-sql`, 
which now includes this module, so this assertion fails there although the 
transpiler is correct. The tinyint, smallint and int wraparound pins above hold 
on both NumPy lines; only this half, and the matching 'numpy raises 
OverflowError' clause in the transpile.py docstring, need to depend on the 
NumPy version.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59724#discussion_r4573104044).
   
   **Verification:**
   - **Compatibility:** With NumPy 1.x and pandas 2.2, the wide-literal part of 
the narrow-integer divergence test passes and asserts agreement on 1001; with 
NumPy 2 it asserts the interpreted OverflowError and the transpiled 1001.
   - **Inspection:** The transpile.py docstring qualifies the too-wide-literal 
OverflowError as NumPy 2 behavior.



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