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


##########
python/pyspark/sql/transpile.py:
##########
@@ -940,7 +1276,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):** Besides the LongType boundaries that the comment above 
names, this lowering also overflows at the minimum value of each narrower 
integral type. Each `_udf_param_N` keeps the type of the column it stands for, 
and `sb` is an int. So `_abs(right_col)` runs in tinyint, smallint or int and, 
under ANSI, raises ARITHMETIC_OVERFLOW when the divisor is that type's minimum, 
and `sb * left_col` raises for an int dividend of -2147483648 with a negative 
divisor. By the review's reading of the code, with transpilation and ANSI on, 
an Arrow-optimized `udf(rem, 'int')` with `def rem(a, b): return a % b` fails 
the query on tinyint columns holding (7, -128), where the interpreted UDF 
returns -121. (7, -32768) over smallint and (7, -2147483648) or (-2147483648, 
-1) over int fail the same way, where Python returns -32761, -2147483641 and 0, 
and a scalar pandas UDF with the same body fails where numpy returns those 
values. The narrow-width tests divide by the literal 3 and the bound
 ary tests use only bigint, so none of them reaches these rows.
   
   This also covers the still-open part of the previous review's note on the 
int64 boundary docs. The transpilePyUDFs doc still attributes every pandas 
difference to numpy's fixed width, and the PandasUDFTranspileDivergenceTests 
docstring still says that each pinned case is numpy computing in the input's 
fixed width where Catalyst is exact.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59724#discussion_r4576761141).
   
   **Recommended change:** Lower `a % b` to the internal pandas_mod function 
(PandasMod over MathUtils.pythonMod), which pandas API on Spark already uses 
for Python-style modulo, instead of `sign(b) * pmod(sign(b) * a, abs(b))`. 
Under Series semantics use it as it is, since it already returns NULL for a 
zero divisor. On the pickled and Arrow-optimized eval types keep Spark's 
remainder-by-zero error for a zero divisor by testing only the divisor, so the 
dividend is still read once. Keep the result type the current lowering gives 
each operand pair. Then drop the `%` boundary from the Mod lowering comment and 
from the 'run the other way' paragraph of the transpile.py module docstring, 
turn test_modulo_overflow_boundary_raises_where_numpy_is_exact into an 
agreement test, and add `%` differentials on all three eval types for infinite 
and absorbing opposite-sign divisors and for each integral type's minimum 
value. The author's reply on the int64 boundary thread already plans to drop 
those 
 sentences once the `%` lowering changes.
   
   **Why this works:** pandas_mod applies CPython's rule directly: it adds the 
divisor to a nonzero remainder whose sign differs from the divisor's and gives 
a zero result the divisor's sign. It needs no sign flip or abs and cannot 
overflow, because the remainder is smaller than the divisor in magnitude, so an 
infinite or much larger divisor keeps Python's answer and every integral width 
is exact at its minimum value. It evaluates the divisor first and returns NULL 
for a zero or NULL divisor, which is the pandas rule, so only the row-at-a-time 
eval types need an extra guard, and that guard reads only the divisor. With no 
`%` difference left, the docs and the former boundary test can describe 
agreement.
   
   **Scope:** Replace the shared `%` lowering with Python-style modulo on all 
three eval types, keep each eval type's zero-divisor outcome and each operand 
pair's result type, and update the `%` docs and tests to match.
   
   **Compatibility:** Every `%` result that already matches Python keeps its 
value and data type on all three eval types, and a zero divisor with a non-null 
dividend keeps today's outcome: NULL for a scalar pandas UDF and Spark's 
remainder-by-zero error on the pickled and Arrow-optimized eval types.
   
   **Risks:** The plan of every transpiled `%` changes from pmod to pandas_mod, 
including for inputs whose result was already right; reverting the lowering 
restores the old plan. Pickled UDFs, which 4.3.0 already transpiles, change 
results for opposite-sign infinite or absorbing divisors, at the integral 
minimum values, and in the sign of some zero results (`-6.0 % 3.0` becomes 0.0 
instead of -0.0), each toward what the UDF returns interpreted; turning the 
experimental flag off still gives interpreted Python, which returns the same 
values. Because the row-at-a-time zero-divisor guard reads only the divisor, a 
NULL dividend with a zero divisor raises where it returned NULL; Python raises 
there too.
   
   **Constraints:** Read the dividend at most once in the lowered expression, 
as today, so ConvertToCatalyst still transpiles a call with a computed dividend 
under aggregates, joins and commands. Keep the data type the current lowering 
gives each `%` operand pair, which is IntegerType when both operands are byte 
or short columns: pandas_mod keeps its operands' common type, and a narrower 
result would change the width and overflow behavior of any expression that uses 
the `%` and the type a stateful streaming checkpoint recorded for it. Keep the 
NaN-to-NULL normalization of fractional pandas results working on the new 
expression, since a NaN operand still yields NaN.
   
   **Exclusions:**
   - A `%` between two plain numbers in a scalar pandas UDF, which returns NULL 
for a zero divisor where Python raises, is fixed separately in the pandas 
allowlist; this change keeps the NULL for every `%` that reaches the pandas 
lowering.
   - The other documented arithmetic differences (overflow on `+`, `-` and `*`, 
NULL arithmetic and float32 literal promotion) and the final return-type cast 
stay as they are.
   
   **Success:** For float and double operands whose divisor has the opposite 
sign of a nonzero remainder and is infinite or large enough to absorb it, a 
transpiled `%` returns what Python returns on the pickled and Arrow-optimized 
eval types and what pandas returns on the scalar pandas eval type. For tinyint, 
smallint, int and bigint operands, a transpiled `%` returns Python's and 
numpy's value when the divisor is the type's minimum value or the dividend is 
the minimum with a negative divisor, instead of raising ARITHMETIC_OVERFLOW. A 
zero divisor still gives NULL for a scalar pandas UDF `%` with a Series operand 
and still raises a remainder-by-zero error on the pickled and Arrow-optimized 
eval types. The Mod lowering comment, the transpile.py module docstring and the 
pandas divergence tests no longer describe a `%` boundary as raising or as 
differing from Python or numpy.
   
   **Verification:**
   - **Regression:** With transpilation and ANSI on, Arrow-optimized and 
pickled UDFs returning `a % b` match the interpreted result over double 
columns, and over float columns with a float return type, for rows whose 
divisor has the opposite sign of a nonzero remainder and is infinite or large 
enough to absorb it, such as (-3.0, inf), (3.0, -inf) and (-1e-20, 1e20), where 
the interpreted double results are inf, -inf and 1e20; a scalar pandas UDF with 
the same body and types matches the interpreted pandas result for those rows 
and returns NULL for a row with a NaN operand.
   - **Regression:** On all three eval types, a transpiled `a % b` matches the 
interpreted result over tinyint, smallint, int and bigint columns at (7, the 
type's minimum value) and at (the type's minimum value, -1), and no test pins 
the int64 boundary as a divergence any more.
   - **Compatibility:** A zero divisor gives NULL for a scalar pandas UDF 
returning `s % t` and raises a remainder-by-zero error for the pickled and 
Arrow-optimized eval types, and a grouped sum over a transpiled `%` with a 
computed dividend such as `(v + 1) % 3` still leaves no Python evaluation in 
the plan.
   - **Compatibility:** On the Arrow-optimized eval type, a transpiled `(a % b) 
+ c` over three tinyint columns whose result exceeds 127 returns the 
interpreted result instead of overflowing, showing that a `%` of two narrow 
columns keeps its current result type.
   - **Inspection:** The Mod lowering comment, the transpile.py module 
docstring and the pandas divergence tests contain no claim that a `%` boundary 
raises or differs from Python or numpy.



##########
python/pyspark/sql/transpile.py:
##########
@@ -940,7 +1276,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))
+                            if self._series_semantics:
+                                return when(right_col == 0, 
lit(None)).otherwise(result)

Review Comment:
   **Blocking (P1):** This NULL matches pandas only when the `%` has a Series 
operand, but it is applied to every `%` in the body, and 
`_check_series_semantics` also admits a `%` whose operands are both constants. 
Python evaluates such a `%` on plain numbers before pandas is involved, and 
CPython leaves `1 % 0` to run time rather than folding it, so it raises 
ZeroDivisionError. By the review's reading of the code, with transpilation and 
ANSI on, `def f(s: pd.Series) -> pd.Series: return s + 1 % 0` as `udf(f, 
'long')` lowers to `s + CASE WHEN 0 = 0 THEN NULL ELSE ... END`, which folds to 
NULL. The query therefore returns NULL for every row, where the interpreted UDF 
raises on its first batch, and `s * (1.0 % 0.0)` behaves the same way. That 
hides a bug in the UDF and breaks the rule the refusal tests enforce, that a 
rewrite must not make a failing UDF return values. The guard an earlier review 
asked for is right for `s % 0` and `1 % s`; only a `%` between constants is 
affected.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59724#discussion_r4573104035).
   
   **Recommended change:** In the scalar pandas allowlist, refuse a `%` neither 
of whose operands references a parameter, with a fallback reason saying that 
Python computes that `%` on plain numbers, so a zero divisor raises 
ZeroDivisionError instead of giving a missing value. List the refusal with the 
other exclusions in the transpile.py module docstring, and add a refusal test 
for `s + 1 % 0` and `s * (1.0 % 0.0)`. The zero-divisor NULL that ba9349560d2 
added to the `%` lowering then applies only to a `%` with a Series operand, 
which is the case pandas answers with a missing value.
   
   **Why this works:** With the allowlist's operators, a subexpression that 
references no parameter is built only from constants, so Python evaluates it to 
a plain number before any pandas operation runs, and `1 % 0` raises 
ZeroDivisionError. Refusing such a `%` before any lowering keeps the UDF 
interpreted, where it raises on its first batch exactly as on the base branch, 
while every `%` that still reaches the Series lowering has a Series operand, 
for which pandas does give a missing value.
   
   **Scope:** One more refusal in the scalar pandas allowlist, with its 
fallback reason, docstring entry and refusal test.
   
   **Compatibility:** A `%` with a pandas Series operand keeps transpiling and 
returning NULL for a zero divisor, and the pickled and Arrow-optimized eval 
types keep their `%` behavior.
   
   **Risks:** Bodies that compute a `%` between constants with a nonzero 
divisor, such as `s + 7 % 3`, also stay interpreted and lose a rewrite whose 
result was right; folding the constant by hand restores it, and removing the 
new refusal rolls this back.
   
   **Constraints:** Decide from the AST alone in the up-front allowlist check, 
so the reason appears once in the warning rather than once per input-type 
variant. Count a `.isnull()`-family call on a parameter as a Series operand, as 
the allowlist already does when it checks that the body references a parameter.
   
   **Exclusions:**
   - Constant arithmetic with `+`, `-` and `*` keeps transpiling, since only 
`%` has a pandas-specific rule, the zero-divisor NULL, that does not hold for 
plain numbers.
   
   **Success:** With transpilation and ANSI on, a scalar pandas UDF whose body 
has a `%` between plain numbers, such as `s + 1 % 0` or `s * (1.0 % 0.0)`, gets 
no transpiled option, raises ZeroDivisionError as it does with transpilation 
off, and its fallback warning names that `%`. A scalar pandas `%` with a Series 
operand, such as `s % 0`, `1 % s` or `s % t`, still transpiles and returns NULL 
for a zero divisor, matching the interpreted pandas result.
   
   **Verification:**
   - **Regression:** With transpilation and ANSI on, scalar pandas UDFs 
returning `s + 1 % 0` over a bigint column and `s * (1.0 % 0.0)` over a double 
column produce no transpiled option, raise the same exception with 
transpilation on and off, and warn with a reason that names the `%` between 
numbers.
   - **Behavior:** Scalar pandas UDFs returning `s % 0`, `1 % s` and `s % t` 
still transpile and match the interpreted pandas results over columns that hold 
zero divisors, giving NULL for each of those rows.



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

Review Comment:
   **Nit (P3):** This label is chosen by node type alone. Every `if` and 
conditional expression, like every `and`, `or` and `not` labeled just above, is 
reported as raising ValueError even when the value tested is a plain bool. For 
`def f(s): return 0 if s is None else s`, the warning says that testing a 
Series for truth raises ValueError. But `s is None` is False, so the 
interpreted UDF returns `s` unchanged, as test_none_guard_ternary_falls_back 
itself notes, and `not (s is None)` fails with UDF_RETURN_TYPE rather than 
ValueError. Users porting a None-guarded scalar UDF are told the wrong reason 
and are not pointed at `.isnull()`. Separately, the message for a body that 
never references a parameter (lines 562-566) names UDF_RETURN_TYPE. 
`PandasScalarUDFHandler` raises that only for a result without `__len__`, so a 
string body such as `return 'ab'` fails the row-count check with 
RESULT_ROWS_MISMATCH instead.
   
   Suggested fix: when the first value an `if`, conditional expression, `not`, 
`and` or `or` tests is an `is` or `is not` comparison, report the existing `is` 
or `is not` reason. Also reword the no-parameter message to say that the result 
is a Python scalar, without naming UDF_RETURN_TYPE for every scalar.
   
   **Verification:**
   - **Behavior:** With transpilation on, the fallback warnings for `0 if s is 
None else s`, `not (s is None)` and `s is not None and s` name the `is` or `is 
not` test with its `.isnull()` or `.notnull()` hint, the warnings for `if s > 
0`, `not s` and `s and s` keep the ValueError reason, and each of these UDFs 
still behaves as it does with transpilation off.
   - **Behavior:** The fallback warnings for the parameter-free bodies `return 
1` and `return 'ab'` describe a failure consistent with each UDF's interpreted 
error, and neither names UDF_RETURN_TYPE for the string body.



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

Review Comment:
   **Nit (P3):** The two `.schema` reads in 
test_output_schema_is_identical_with_and_without_transpilation (lines 734 and 
736) come from the analyzed plan. Classic `Dataset.schema` is 
`queryExecution.analyzed.schema`, and in that plan TranspiledPythonUDF reports 
the wrapped Python UDF's data type. Neither query is optimized or executed, so 
ConvertToCatalyst, whose substitution the test's comment says it guards, never 
runs. If `_transpile_from_ast` stopped casting to the declared return type, the 
ByteType and IntegerType cases would substitute a bigint option, and this test 
would still pass.
   
   Suggested fix: compare each declared return type with the schema of the 
optimized plan, where the option has replaced the Python UDF, and assert that 
no Python evaluation is left.
   
   **Verification:**
   - **Regression:** The output-schema test passes at the current head, 
confirms for each return type that the plan it reads has no Python evaluation 
left, and fails when the transpiler's final cast to the declared return type is 
removed.



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

Review Comment:
   **Nit (P3):** This call can lose its rewrite, or bind its keywords to the 
wrong positions, without failing the test. If `UserDefinedFunction.__call__` 
stopped resolving keywords to `_udf_param_N` order, the builder would see 
NamedArgumentExpression children and drop every transpiled option, and the 
interpreted pandas UDF would return the same [5, None]. `combine` is `a * b - 
1`, which is symmetric, so a swapped binding returns the same rows as well. The 
comment above says this is the only coverage of that resolution for any eval 
type.
   
   Suggested fix: assert that the keyword call leaves no Python evaluation in 
the executed plan, using the `_eval_python_nodes` helper this module already 
imports, and use a body whose result changes when its arguments swap, such as 
`a * 10 + b`.
   
   **Verification:**
   - **Regression:** With transpilation and ANSI on, the keyword-call test 
asserts that a scalar pandas UDF called with its keywords in swapped order 
leaves no Python evaluation in the plan and returns the interpreted result of a 
body that is not symmetric in its arguments, and it fails when keyword 
resolution is skipped or binds the keywords in the wrong order.



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