spark-test commented on code in PR #59724:
URL: https://github.com/apache/spark/pull/59724#discussion_r4573103993
##########
python/pyspark/sql/udf.py:
##########
@@ -152,6 +152,38 @@ def _create_py_udf(
return _create_udf(f, returnType, eval_type)
+# Eval types the transpiler is allowed to rewrite.
+#
+# The first two are per-row scalar Python UDFs, where the function receives
one Python scalar
+# per argument per row and returns one Python scalar. SQL_ARROW_BATCHED_UDF is
the
+# Arrow-OPTIMIZED regular Python UDF; Arrow is only the transport there -- the
worker still
+# calls the function once per row with Python scalars -- so its Python-level
semantics are
+# exactly what the transpiler reproduces. Mind the naming collision:
SQL_SCALAR_ARROW_UDF
+# (250) is a genuinely vectorized UDF that receives a pyarrow.Array, and
+# SQL_ARROW_BATCHED_UDF (101) is not.
+#
+# SQL_SCALAR_PANDAS_UDF is genuinely vectorized: the function receives a
pandas.Series per
+# argument and must return a Series. It is admitted because a Series applies
the arithmetic
+# and text operators element-wise with the same result Catalyst produces --
but only those.
+# Everything the scalar transpiler lowers around control flow and comparison
would be wrong
+# on a Series (`if s:` raises, `s is None` is always False, `s < 0` treats a
missing value as
+# False), so pyspark.sql.transpile gates the body on a strict allowlist and
reproduces
+# pandas' NaN-is-missing rule explicitly. Read that module's "Scalar pandas
UDFs" section
+# before widening this set.
+#
+# Membership rather than a negation, deliberately: a newly added eval type
must be admitted
+# here consciously rather than inheriting transpilation because it failed to
match an
+# exclusion. pyspark.sql.tests.arrow.test_arrow_python_udf_transpile has a
canary over every
+# PythonEvalType that fails until a new one is triaged.
+_TRANSPILABLE_EVAL_TYPES = frozenset(
+ {
+ PythonEvalType.SQL_BATCHED_UDF,
+ PythonEvalType.SQL_ARROW_BATCHED_UDF,
Review Comment:
**Blocking (P1):** This admission sends the default `functions.udf` eval
type through every scalar lowering, including one that returns a value where
Python raises. `_category_uncached` has no arm for unary `+` or `-`, so `-x`
falls to the catch-all `'numeric'` category even under the `'float'` variant
(transpile.py:1015-1019), and the Mult rule accepts `'string' * 'numeric'` as a
repeat (transpile.py:944-951) although it refuses `'ab' * x` for a float `x`.
Reading the code, `def f(x): return 'ab' * -x` applied as `udf(f,
StringType())` to a double column holding -2.5 and 1.5 is lowered to
`repeat('ab', cast(-x as int))` and returns `'abab'` and `''`, while the
interpreted UDF fails every row with `TypeError: can't multiply sequence by
non-int of type 'float'`. The same applies to `+x`, `-x * s` and a negated
float literal such as `s * -1.5`. Pickled UDFs already had this gap; with this
change it reaches the default UDFs of everyone who turns the flag on.
**Recommended change:** Add an arm to CatalystTranspiler._category_uncached
for unary + and -. It returns the operand's category when that category is
numeric and refuses the variant otherwise, instead of falling to the 'numeric'
catch-all. Add differential tests on the Arrow-optimized and pickled eval types
for a string repeated by a unary + or - of a float operand, and an equality
case on a negated integral parameter.
**Why this works:** With the arm, `-x` under the 'float' variant is 'float',
so the repeat rule's integral-count check refuses `'ab' * -x` exactly as it
already refuses `'ab' * x`, and that variant produces no option. The JVM then
finds no option for a Float or Double column, and the UDF runs interpreted,
raising as Python does. Under the 'integer' variant `-x` is 'integer', so the
repeat is still lowered.
**Scope:** One category arm in the shared scalar category inference, with
differential tests on the Arrow-optimized and pickled eval types.
**Compatibility:** Apart from string repeat by a unary float count, the new
arm changes no transpiled result on any eval type.
**Risks:** Unary expressions over integral operands become 'integer' instead
of 'numeric'. As a result, the equality lowering drops its NaN guard for
comparisons such as `-x == 2` on integer columns, and arithmetic categories
become more precise. Results do not change, because integral values cannot be
NaN, but the emitted plans do. Reverting the arm rolls this back.
**Constraints:** The arm must refuse a non-numeric operand, so that `-x`
under the string variant is still dropped instead of lowered.
**Exclusions:**
- The other catch-all categories (unsupported calls and subscripts) stay as
they are, because the lowering refuses those nodes before any rule uses their
category.
**Success:** Under the float variant, `'ab' * -x`, `'ab' * +x`, `-x * s` and
`s * -1.5` produce no transpiled option, so an Arrow-optimized or pickled UDF
over a Float or Double column runs interpreted and raises TypeError, as Python
does. Under the integer variant, `'ab' * -x` is still transpiled to a repeat
and matches the interpreted result. Unary arithmetic and comparisons over
numeric parameters still transpile, with unchanged results, on every eval type.
**Verification:**
- **Regression:** With transpilation and ANSI on, an Arrow-optimized UDF
returning `'ab' * -x` over a double column fails the same way the interpreted
UDF does instead of returning strings. The same holds for the pickled eval
type, for `+x`, and for a negated float literal count.
- **Behavior:** The same body over an integer column still transpiles,
leaving no Python evaluation in the plan, and matches the interpreted result,
including the empty string for a negative count.
- **Compatibility:** An equality comparison on a negated parameter, such as
`-x == 2`, still matches the interpreted result over integer and double
columns, including NaN and NULL values on the double column.
##########
python/pyspark/sql/udf.py:
##########
@@ -274,8 +307,39 @@ 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
Review Comment:
**Nit (P3):** With `SQL_ARROW_BATCHED_UDF` (the `functions.udf` default) and
`SQL_SCALAR_PANDAS_UDF` now members, this check passes on the default
construction path, so every flag-off definition of those UDFs makes the
`session.conf.get` round trip on the next line. The base branch checked
`evalType == SQL_BATCHED_UDF` first and skipped it, yet the comment above
(lines 288-292) still says the default construction path stays cheap. The cost
is one driver-side call per UDF definition, not per row or per query, so
keeping the read is reasonable, but the comment should say that it happens and
why. Suggested fix: reword the comment to say that defining a deterministic UDF
of any transpilable eval type, including the default Arrow-optimized one, reads
the flag once even when it is off, and why that read stays.
**Verification:**
- **Inspection:** The gate comment states that constructing a deterministic
UDF of any transpilable eval type, including the default Arrow-optimized one,
makes one JVM read of the transpile flag even when the flag is off, and gives
the reason the read is kept.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -706,7 +706,25 @@ 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, " +
+ "which changes the values an Arrow-optimized UDF receives and so
disables " +
+ "transpilation. Scalar pandas UDFs are transpiled only for
element-wise bodies " +
+ "built from `+` `-` `*` `%`, unary `+`/`-` and `Series.isnull()` (and
its aliases); " +
+ "a `*` repeating a string Series requires a literal repeat count.
Anything else, " +
+ "including comparisons and any use of `if`, `and`, `or`, `not` or `is
None`, falls " +
+ "back to interpreted Python, because those do not mean the same thing
on a Series. " +
+ "Where a transpiled pandas UDF does differ, it is because numpy " +
+ "arithmetic is fixed-width: it wraps on integer overflow, keeps
float32 through a " +
+ "float literal, loses precision above 2^53 for an integral column
carrying " +
+ "NULLs (see
spark.sql.execution.pythonUDF.pandas.preferIntExtensionDtype), and " +
Review Comment:
**Non-blocking (P2):** This sentence points readers to
`spark.sql.execution.pythonUDF.pandas.preferIntExtensionDtype` for the
precision loss above 2^53, but the doc never says that setting that conf to
true disables transpilation of every scalar pandas UDF (udf.py:336-342,
re-checked in ConvertToCatalyst at Optimizer.scala:1369-1383). The refusal is
silent when the conf is on at definition: there is no RuntimeWarning like the
ANSI gate's and no 'Unable to transpile UDF' warning, and without options there
is no TranspiledPythonUDF for ConvertToCatalyst to log about. A user who
follows the pointer therefore silently loses every scalar pandas rewrite, and
this published doc is the only place that could tell them. Suggested fix: state
that preferIntExtensionDtype=true disables scalar pandas transpilation, and
drop the pointer from the precision divergence.
See **Shared repair plan 1** in the review body.
##########
python/pyspark/sql/udf.py:
##########
@@ -152,6 +152,38 @@ def _create_py_udf(
return _create_udf(f, returnType, eval_type)
+# Eval types the transpiler is allowed to rewrite.
+#
+# The first two are per-row scalar Python UDFs, where the function receives
one Python scalar
+# per argument per row and returns one Python scalar. SQL_ARROW_BATCHED_UDF is
the
+# Arrow-OPTIMIZED regular Python UDF; Arrow is only the transport there -- the
worker still
+# calls the function once per row with Python scalars -- so its Python-level
semantics are
+# exactly what the transpiler reproduces. Mind the naming collision:
SQL_SCALAR_ARROW_UDF
+# (250) is a genuinely vectorized UDF that receives a pyarrow.Array, and
+# SQL_ARROW_BATCHED_UDF (101) is not.
+#
+# SQL_SCALAR_PANDAS_UDF is genuinely vectorized: the function receives a
pandas.Series per
+# argument and must return a Series. It is admitted because a Series applies
the arithmetic
+# and text operators element-wise with the same result Catalyst produces --
but only those.
+# Everything the scalar transpiler lowers around control flow and comparison
would be wrong
+# on a Series (`if s:` raises, `s is None` is always False, `s < 0` treats a
missing value as
+# False), so pyspark.sql.transpile gates the body on a strict allowlist and
reproduces
+# pandas' NaN-is-missing rule explicitly. Read that module's "Scalar pandas
UDFs" section
+# before widening this set.
+#
+# Membership rather than a negation, deliberately: a newly added eval type
must be admitted
+# here consciously rather than inheriting transpilation because it failed to
match an
+# exclusion. pyspark.sql.tests.arrow.test_arrow_python_udf_transpile has a
canary over every
Review Comment:
**Nit (P3):** This comment promises a canary that fails until a new eval
type is triaged, but `test_eval_type_allowlist_is_exhaustive` only asserts that
the set of eval types whose UDFs transpile equals the three members. A new
`PythonEvalType` constant is not in `_TRANSPILABLE_EVAL_TYPES`, so line 310
never transpiles it, the set stays the same, and the test passes with no
triage. Membership keeps a new type safe, so the cost is a missed triage
prompt, but the guarantee stated here does not hold. Suggested fix: have the
test compare the enumerated `SQL_*` members against an explicit recorded
inventory, as `test_data_type_inventory_is_complete` does for data types.
**Verification:**
- **Behavior:** The eval-type canary passes for the current PythonEvalType
members and fails, naming the untriaged type, when the enumerated SQL_* members
differ from its recorded inventory.
##########
python/pyspark/sql/transpile.py:
##########
@@ -299,6 +389,169 @@ 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)
Review Comment:
**Blocking (P1):** Admitting `ast.Mod` for Series reuses the scalar `sb *
pmod(sb * a, abs(b))` lowering (lines 1240-1259), which under ANSI raises
REMAINDER_BY_ZERO for a zero divisor with a non-null dividend. The interpreted
pandas UDF answers `x % 0` with NaN for integer and float operands, and the
numpy-backed return path masks it to NULL; the PR's own
`test_modulo_by_zero_raises_where_numpy_yields_a_missing_value` pins
interpreted `[None]` against transpiled REMAINDER_BY_ZERO. So with the flag and
ANSI on, `def modulo(a, b): return a % b` over a row holding (5, 0) now fails
the whole query where it returned NULL. The reason given for keeping this, that
the extension-dtype regime answers 0, does not apply here: this change refuses
every scalar pandas UDF under `preferIntExtensionDtype` (udf.py:336-342,
Optimizer.scala:1369-1383), so the only regime that is transpiled answers NULL.
Turning a NULL-returning query into an error is also what the PR avoids
elsewhere by refusing str
ing repeat by a column. This review asks for NULL: under Series semantics,
wrap the lowering in `when(right_col == 0, lit(None))`, keep the row-at-a-time
eval types raising (Python raises there too), and drop `a % 0` and its
extension-dtype rationale from the documented divergences.
**Verification:**
- **Behavior:** With transpilation and ANSI on, a scalar pandas UDF
returning `a % b` transpiles and returns the interpreted pandas results over
bigint columns holding (5, 0), (NULL, 0), (7, -3) and (-7, 3), and over double
columns holding (5.0, 0.0) and (5.0, -0.0): NULL for every zero divisor and the
sign-adjusted remainder otherwise.
- **Regression:** The Long.MinValue % -1 boundary still raises
ARITHMETIC_OVERFLOW when transpiled, and a pickled or Arrow-optimized UDF
returning `x % 0` still raises on both the transpiled and the interpreted path.
- **Inspection:** The transpilePyUDFs doc, the transpile.py module docstring
and the pandas transpile test module list no `a % 0` divergence, and no comment
cites the extension-dtype regime as the reason for a zero-divisor outcome.
##########
python/pyspark/sql/tests/arrow/test_arrow_python_udf_transpile_type_canary.py:
##########
@@ -0,0 +1,585 @@
+#
+# 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 both 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
Review Comment:
**Nit (P3):** Every verdict and parity test in this canary iterates only
`_PICKLED` and `_ARROW`, and the runbook asks for parity 'on both eval types'
before a type is recorded as TRANSPILES. But this change also admits
`SQL_SCALAR_PANDAS_UDF` through the same return-type allowlist and the same JVM
input check, which ignores the eval type. If a later change made a type
TRANSPILES and the checks passed on the two row-at-a-time eval types, scalar
pandas UDFs would start transpiling it with no parity check on the eval type
whose per-type semantics differ most (numpy dtypes and NaN masking). Today no
pandas test with transpilation on exercises tinyint, smallint or `string_lcase`
returns, and int returns only through identity UDFs. Suggested fix: record
pandas verdicts beside the existing ones and run parity with Series-valid
bodies for every TRANSPILES type.
**Verification:**
- **Behavior:** For the scalar pandas eval type, the canary's observed
return and input verdicts match its recorded tables, and each return type
recorded as TRANSPILES returns the interpreted pandas result for a matching
fixture.
##########
python/pyspark/sql/tests/pandas/test_pandas_udf_transpile.py:
##########
@@ -0,0 +1,892 @@
+#
+# 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, and it answers ``a % 0``
with a missing
+ value. In every case the transpiled expression is the exact or
ANSI-correct one. Two are
+ worse than merely different interpreted, which is the argument for the
rewrite rather
+ than against it: the precision one is *batch-dependent* (move the NULL to
another
+ partition and the answer changes, so it is pinned with an explicit
single-partition
+ DataFrame), and ``a % 0`` answers NULL or ``0`` depending on one conf.
+
+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.functions import pandas_udf
+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 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_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):
+ 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):
+ # The isnan-to-NULL normalization models the default dtype regime,
where the result
+ # Series is numpy-backed and masked with isnull(). Under this conf the
Series is a
+ # pandas masked extension array, handed to Arrow with mask=None and
whose isnull() is
+ # False for NaN anyway, so a NaN result arrives as NaN rather than
NULL and the
+ # normalization would be exactly backwards. No single expression
covers both regimes,
+ # so the whole eval type is refused here -- in udf.py and again in
ConvertToCatalyst,
+ # since the conf can be flipped after the UDF is built.
+ 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_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_raises_where_numpy_yields_a_missing_value(self):
+ # pandas promotes int64 to float64 for `% 0` and yields NaN, which the
return path
+ # masks to NULL. ANSI raises REMAINDER_BY_ZERO, and there is no single
interpreted answer
+ # to reproduce anyway -- see the extension-dtype case below.
+ interpreted, transpiled = self._pin_divergence(
+ modulo, LongType(), self._mods((5, 0)), "a", "b"
+ )
+ self.assertEqual(([None], None), interpreted)
+ self.assertIs(transpiled[0], _RAISED)
+ self.assertIn("REMAINDER_BY_ZERO", str(transpiled[1]))
+
+ def test_modulo_by_zero_yields_zero_under_int_extension_dtype(self):
+ # The same body and data, one conf apart, and pandas answers 0 rather
than NULL. That
+ # inconsistency is the reason `% 0` is documented rather than
reproduced -- a guard
+ # emitting NULL would match one regime and contradict the other, as
well as ANSI.
+ # Nothing is transpiled under this conf (see
+ # test_int_extension_dtype_disables_transpilation), so this pins the
interpreted side
+ # only; the transpiled REMAINDER_BY_ZERO is pinned by the
default-regime test above.
+ with self.sql_conf(
+ {
+ **_TRANSPILE_OFF,
+
"spark.sql.execution.pythonUDF.pandas.preferIntExtensionDtype": True,
+ }
+ ):
+ interpreted = self._values_or_raised(
+ self._mods((5, 0)).select(self._pandas_udf(modulo,
LongType())("a", "b"))
+ )
+ self.assertEqual(([0], None), interpreted)
+
+ 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_integer_overflow_raises_where_numpy_wraps(self):
Review Comment:
**Nit (P3):** This test pins the overflow divergence only at 64 bits, and
every integral fixture in this module is bigint, so no case binds a ByteType,
ShortType or IntegerType column, although ResolveTranspiledPythonUDFOptions
binds the same `'integer'` option to them. Those columns reach the UDF as int8,
int16 or int32 Series, and numpy keeps that width. Reading the code, `s + 1`
keeps an int column at 32 bits, so ANSI raises at the int maximum as it does
here, but it widens tinyint and smallint to int: `s + 1` on tinyint 127 gives
128 transpiled where numpy wraps to -128. The documented case of a literal too
wide for the column's dtype has no test either, and the parity rerun of
`ScalarPandasUDFTestsMixin` reaches narrow columns only through identity UDFs
over int. Suggested fix: add tinyint, smallint and int differentials away from
the type bounds, and pin both narrow-width divergences with their values.
**Verification:**
- **Behavior:** Over tinyint, smallint and int columns with and without
NULLs, `s + 1`, `s - 2`, `s * 3`, `-s` and `s % 3`, away from the type bounds,
return the interpreted pandas results when transpiled.
- **Regression:** `s + 1` at the tinyint and smallint maximum is pinned with
the interpreted wrapped value and the transpiled widened value, and at the int
maximum with the interpreted wrapped value and the transpiled
ARITHMETIC_OVERFLOW. A literal wider than the column's dtype is pinned with the
interpreted outcome for the installed numpy and the transpiled exact value.
##########
python/pyspark/sql/udf.py:
##########
@@ -274,8 +307,39 @@ 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",
+ )
+ )
+ # A scalar pandas UDF's NaN handling depends on this conf, and
not in a way
+ # any single expression can cover. The return path masks with
+ # ``series.isnull()`` only for a numpy-backed Series; a pandas
masked
+ # extension array is handed to Arrow with ``mask=None``
instead (see
+ # ``PandasToArrowConversion.convert``), and its ``isnull()``
is False for NaN
+ # anyway. So with this conf off a NaN result arrives as NULL,
and with it on
Review Comment:
**Nit (P3):** Under `preferIntExtensionDtype`, `ArrowToPandasConversion`
switches only Byte, Short, Integer and Long inputs to `Int8` through `Int64`
(conversion.py:2127-2146); Float and Double inputs still go through
`arr.to_pandas()`. Reading that code, `def f(s): return s * 1e400` over a
double column holding 0.0 returns a numpy float64 Series, and its NaN is still
masked to NULL, so 'the same NaN arrives as NaN' holds only for results derived
from integral inputs. The comment also cites `PandasToArrowConversion.convert`,
which does not exist; the mask line is in `_convert_column_legacy`
(conversion.py:539), reached through `from_pandas`. Refusing every scalar
pandas UDF under the conf is still safe, but this comment, the Optimizer.scala
re-check comment, the ConvertToCatalystSuite case and
`test_int_extension_dtype_disables_transpilation` should say that the conf
makes integral inputs masked arrays, so results derived from them keep NaN.
See **Shared repair plan 1** in the review body.
##########
python/pyspark/sql/tests/arrow/test_arrow_python_udf_transpile_type_canary.py:
##########
@@ -0,0 +1,585 @@
+#
+# 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 both 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
+
+# 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
+# never sees them anyway -- named here only so a reader doesn't wonder why
they're missing.
+_NOT_COLUMN_TYPES = frozenset({T.DataType, T.StructField, T.UserDefinedType})
+
+
+#
--------------------------------------------------------------------------------------
+# UDF bodies. Named defs because the transpiler recovers source via
inspect.getsource and
+# cannot extract a lambda that appears as a call argument.
+#
--------------------------------------------------------------------------------------
+
+
+def numeric_body(x):
+ return x + 1
+
+
+def string_body(x: str):
+ return x
+
+
+def bool_body(x: bool):
+ return x
+
+
+def binary_body(x: bytes):
+ return x
+
+
+def null_probe(x):
+ # Deliberately unannotated: this is the realistic default, and an
unannotated parameter
+ # is only tried as numeric and string, which is what the input-type table
records.
+ return 1 if x is None else 2
+
+
+_BODIES = {
+ "numeric": numeric_body,
+ "string": string_body,
+ "bool": bool_body,
+ "binary": binary_body,
+ # For a return type no lowering can category-match, the body is
irrelevant: the
+ # return-type allowlist refuses before any lowering is attempted.
+ "other": numeric_body,
+}
+
+
+# (label, instance, body category whose lowering could plausibly target this
return type)
+_SAMPLES = (
+ ("void", T.NullType(), "other"),
+ ("char", T.CharType(10), "string"),
+ ("string", T.StringType(), "string"),
+ ("string_lcase", T.StringType("UTF8_LCASE"), "string"),
+ ("varchar", T.VarcharType(10), "string"),
+ ("binary", T.BinaryType(), "binary"),
+ ("boolean", T.BooleanType(), "bool"),
+ ("date", T.DateType(), "other"),
+ ("time", T.TimeType(6), "other"),
+ ("timestamp", T.TimestampType(), "other"),
+ ("timestamp_ntz", T.TimestampNTZType(), "other"),
+ ("timestamp_ltz_nanos", T.TimestampLTZNanosType(), "other"),
+ ("timestamp_ntz_nanos", T.TimestampNTZNanosType(), "other"),
+ ("decimal", T.DecimalType(10, 2), "numeric"),
+ ("double", T.DoubleType(), "numeric"),
+ ("float", T.FloatType(), "numeric"),
+ ("tinyint", T.ByteType(), "numeric"),
+ ("smallint", T.ShortType(), "numeric"),
+ ("int", T.IntegerType(), "numeric"),
+ ("bigint", T.LongType(), "numeric"),
+ ("day_time_interval", T.DayTimeIntervalType(), "other"),
+ ("year_month_interval", T.YearMonthIntervalType(), "other"),
+ ("calendar_interval", T.CalendarIntervalType(), "other"),
+ ("array", T.ArrayType(T.LongType()), "other"),
+ ("map", T.MapType(T.StringType(), T.LongType()), "other"),
+ ("struct", T.StructType([T.StructField("f", T.LongType())]), "other"),
+ ("variant", T.VariantType(), "other"),
+ ("geography", T.GeographyType(4326), "other"),
+ ("geometry", T.GeometryType(4326), "other"),
+)
+
+# Verdict per RETURN type, pickled eval type, with the body category paired
above.
+# Two refusals have non-obvious reasons: `decimal` is inside the return-type
allowlist (a
+# NumericType) but refused by the body-vs-return-type check, because Python
receives
+# decimal.Decimal with different precision semantics; `void` is outside the
allowlist even
+# though Arrow can express it, so widening the allowlist to follow Arrow would
let it in.
+_EXPECTED_RETURN_VERDICT = {
+ "void": NO_TRANSPILE,
+ "char": REJECTED_CHAR_VARCHAR,
+ "string": TRANSPILES,
+ "string_lcase": TRANSPILES,
+ "varchar": REJECTED_CHAR_VARCHAR,
+ "binary": TRANSPILES,
+ "boolean": TRANSPILES,
+ "date": NO_TRANSPILE,
+ "time": NO_TRANSPILE,
+ "timestamp": NO_TRANSPILE,
+ "timestamp_ntz": NO_TRANSPILE,
+ "timestamp_ltz_nanos": NO_TRANSPILE,
+ "timestamp_ntz_nanos": NO_TRANSPILE,
+ "decimal": NO_TRANSPILE,
+ "double": TRANSPILES,
+ "float": TRANSPILES,
+ "tinyint": TRANSPILES,
+ "smallint": TRANSPILES,
+ "int": TRANSPILES,
+ "bigint": TRANSPILES,
+ "day_time_interval": NO_TRANSPILE,
+ "year_month_interval": NO_TRANSPILE,
+ "calendar_interval": NO_TRANSPILE,
+ "array": NO_TRANSPILE,
+ "map": NO_TRANSPILE,
+ "struct": NO_TRANSPILE,
+ "variant": NO_TRANSPILE,
+ "geography": NO_TRANSPILE,
+ "geometry": NO_TRANSPILE,
+}
+
+# Return types Arrow cannot express, so an Arrow-optimized UDF declaring one
fails at
+# _check_return_type regardless of transpilation. Derived from to_arrow_type
and pinned
+# independently by
test_transpiler_return_allowlist_is_a_subset_of_arrow_support.
+# CHAR/VARCHAR are absent even though to_arrow_type rejects them too: UDF
construction
+# now refuses them for every eval type (REJECTED_CHAR_VARCHAR) before the
Arrow check
+# is reached.
+_ARROW_REJECTED_RETURN_TYPES = frozenset({"year_month_interval",
"calendar_interval"})
+
+# Verdict per INPUT column type, pickled eval type, with the unannotated
`null_probe` body.
+# boolean and binary are NO_TRANSPILE here but TRANSPILES as return types: an
unannotated
+# parameter is only tried as numeric and string, so those columns match no
category (see
+# test_annotated_parameters_widen_input_coverage). string_lcase is refused
because the check
+# requires UTF8_BINARY -- under UTF8_LCASE 'abc' == 'ABC' is true where Python
says False.
+_EXPECTED_INPUT_VERDICT = {
+ "void": NO_TRANSPILE,
+ "char": NOT_A_COLUMN_TYPE,
+ "string": TRANSPILES,
+ "string_lcase": NO_TRANSPILE,
+ "varchar": NOT_A_COLUMN_TYPE,
+ "binary": NO_TRANSPILE,
+ "boolean": NO_TRANSPILE,
+ "date": NO_TRANSPILE,
+ "time": NO_TRANSPILE,
+ "timestamp": NO_TRANSPILE,
+ "timestamp_ntz": NO_TRANSPILE,
+ "timestamp_ltz_nanos": NO_TRANSPILE,
+ "timestamp_ntz_nanos": NO_TRANSPILE,
+ "decimal": NO_TRANSPILE,
+ "double": TRANSPILES,
+ "float": TRANSPILES,
+ "tinyint": TRANSPILES,
+ "smallint": TRANSPILES,
+ "int": TRANSPILES,
+ "bigint": TRANSPILES,
+ "day_time_interval": NO_TRANSPILE,
+ "year_month_interval": NOT_A_COLUMN_TYPE,
+ "calendar_interval": NOT_A_COLUMN_TYPE,
+ "array": NO_TRANSPILE,
+ "map": NO_TRANSPILE,
+ "struct": NO_TRANSPILE,
+ "variant": NO_TRANSPILE,
+ "geography": NO_TRANSPILE,
+ "geometry": NO_TRANSPILE,
+}
+
+# Parity fixture per TRANSPILES return type: an input column whose body result
already
+# matches the declared return type. Pairing them avoids a known, accepted
divergence -- a
+# bigint column with `x + 1` declared DoubleType() gives the pickled path a
Python int, which
+# it NULLs, while the transpiled cast returns 8.0 (see
+# test_udf_transpile_casts_to_return_type) -- masquerading as a canary failure.
+_PARITY_FIXTURES = {
+ "string": (T.StringType(), "ab", string_body),
+ "string_lcase": (T.StringType(), "ab", string_body),
+ "binary": (T.BinaryType(), b"ab", binary_body),
+ "boolean": (T.BooleanType(), True, bool_body),
+ "tinyint": (T.LongType(), 7, numeric_body),
+ "smallint": (T.LongType(), 7, numeric_body),
+ "int": (T.LongType(), 7, numeric_body),
+ "bigint": (T.LongType(), 7, numeric_body),
+ "double": (T.DoubleType(), 7.0, numeric_body),
+ "float": (T.DoubleType(), 7.0, numeric_body),
+}
+
+# Column type + value + matching annotated body, per body category, to show
that annotating a
+# parameter is what unlocks the bool and binary columns.
+_ANNOTATED_CATEGORY_FIXTURES = {
+ "numeric": (T.LongType(), 7, numeric_body),
+ "string": (T.StringType(), "ab", string_body),
+ "bool": (T.BooleanType(), True, bool_body),
+ "binary": (T.BinaryType(), b"ab", binary_body),
+}
+
+
+def _concrete_data_type_classes():
+ """Every concrete ``DataType`` subclass exported from
``pyspark.sql.types``.
+
+ Introspective rather than a hand-written list: see the module docstring on
why
+ ``_atomic_types`` is not a safe basis. Abstract bases are excluded
implicitly -- they are
+ not in ``__all__`` -- so only ``DataType`` itself and ``StructField`` need
naming.
+ """
+ classes = set()
+ for name in T.__all__:
+ obj = getattr(T, name)
+ if isinstance(obj, type) and issubclass(obj, T.DataType) and obj not
in _NOT_COLUMN_TYPES:
+ classes.add(obj)
+ return classes
+
+
[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 ArrowUDFTranspileTypeCanaryTests(ArrowUDFTranspileTestsMixin,
ReusedSQLTestCase):
+ """Every Spark data type is either refused by the transpiler or verified
against it."""
+
+ # -- inventory
----------------------------------------------------------------------
+
+ def test_data_type_inventory_is_complete(self):
+ # The tripwire for a newly added Spark type.
+ sampled = {type(dt) for _label, dt, _cat in _SAMPLES}
+ missing = sorted(cls.__name__ for cls in _concrete_data_type_classes()
- sampled)
+ self.assertEqual(
+ [],
+ missing,
+ f"pyspark.sql.types now exports {missing}, which this canary has
never "
+ "considered. Add an instance to _SAMPLES in this file, then follow
the "
+ "'Triaging a new type' runbook in this module's docstring. Falling
back to "
+ "interpreted Python is the safe default and is probably the right
answer, but "
+ "it should be a recorded decision rather than an accident.",
+ )
+
+ def test_sample_tables_are_complete(self):
+ # Adding a sample must force a verdict to be recorded for it, in both
directions.
+ labels = {label for label, _dt, _cat in _SAMPLES}
+ self.assertEqual(
+ set(),
+ labels - set(_EXPECTED_RETURN_VERDICT),
+ "these samples have no entry in _EXPECTED_RETURN_VERDICT",
+ )
+ self.assertEqual(
+ set(),
+ labels - set(_EXPECTED_INPUT_VERDICT),
+ "these samples have no entry in _EXPECTED_INPUT_VERDICT",
+ )
+ self.assertEqual(
+ set(),
+ set(_EXPECTED_RETURN_VERDICT) - labels,
+ "these verdicts refer to samples that no longer exist",
+ )
+ self.assertEqual(
+ set(),
+ set(_EXPECTED_INPUT_VERDICT) - labels,
+ "these verdicts refer to samples that no longer exist",
+ )
+ self.assertEqual(
+ set(),
+ _ARROW_REJECTED_RETURN_TYPES - labels,
+ "these Arrow-rejected labels refer to samples that no longer
exist",
+ )
+
+ # -- static invariant
---------------------------------------------------------------
+
+ def test_transpiler_return_allowlist_is_a_subset_of_arrow_support(self):
+ # Why the existing return-type allowlist can be reused unchanged for
the Arrow eval
+ # type: everything it admits, Arrow can express. If this ever fails,
widening
+ # transpilation to Arrow UDFs would start producing return types the
Arrow worker
+ # cannot serialize.
+ for label, dt, _cat in _SAMPLES:
+ with self.subTest(label=label):
+ in_allowlist = isinstance(
+ dt, (T.NumericType, T.StringType, T.BooleanType,
T.BinaryType)
+ )
+ if not in_allowlist:
+ continue
+ try:
+ to_arrow_type(dt, timezone="UTC")
+ except Exception as e: # any failure is the finding
+ self.fail(
+ f"{label} is inside the transpiler's return-type
allowlist "
+ "(python/pyspark/sql/transpile.py) but to_arrow_type "
+ f"(python/pyspark/sql/pandas/types.py) rejects it:
{e!r}. Either "
+ "narrow the transpiler's allowlist or teach
to_arrow_type about "
+ "this type; until then Arrow-optimized UDFs must not
transpile it."
+ )
+
+ # -- return-type verdicts
-----------------------------------------------------------
+
+ def _return_verdict(self, dt, body, eval_type):
+ try:
+ pudf = UserDefinedFunction(body, dt, evalType=eval_type)
+ # Force _check_return_type, which only runs when returnType is
read. Doing it
+ # explicitly keeps the verdict stable regardless of whether the
transpile block
+ # happens to have read it during construction.
+ _ = pudf.returnType
+ except Exception as e: # classified below
+ if (
+ isinstance(e, PySparkNotImplementedError)
+ and e.getCondition() == "CHAR_VARCHAR_NOT_SUPPORTED_IN_PYTHON"
+ ):
+ return REJECTED_CHAR_VARCHAR
+ if "Invalid return type with Arrow-optimized Python UDF" in str(e):
+ return REJECTED_BY_ARROW
+ raise
+ return TRANSPILES if pudf.transpiled else NO_TRANSPILE
+
+ def _assert_verdicts(self, expected, observed, table_name, guidance):
+ """Compare verdict maps, showing the observed table in copy-pasteable
form."""
+ self.maxDiff = None
+ if expected == observed:
+ return
+ changed = {
+ label: (expected.get(label), observed.get(label))
+ for label in sorted(set(expected) | set(observed))
+ if expected.get(label) != observed.get(label)
+ }
+ rendered = "\n".join(f' "{label}": {verdict},' for label, verdict
in observed.items())
+ self.fail(
+ f"{table_name} disagrees with what the transpiler now does.\n"
+ f"changed (label: expected -> observed): {changed}\n\n"
+ f"{guidance}\n\n"
+ f"observed table, if the change is intended and
verified:\n{rendered}"
+ )
+
+ def test_return_type_verdicts_pickled(self):
+ with self.sql_conf(_TRANSPILE_ON):
+ observed = {}
+ for label, dt, cat in _SAMPLES:
+ observed[label] = self._return_verdict(dt, _BODIES[cat],
_PICKLED)
+ self._assert_verdicts(
+ _EXPECTED_RETURN_VERDICT,
+ observed,
+ "_EXPECTED_RETURN_VERDICT",
+ "See 'Triaging a new type' in this module's docstring: if
something now "
+ "TRANSPILES, verify parity against the interpreted path BEFORE
updating the "
+ "table, using the golden matrix in
python/pyspark/sql/tests/coercion/ as the "
+ "authority. A Cast that is analysis-valid but that the interpreted
path would "
+ "never perform is a silent divergence, not a feature.",
+ )
+
+ def test_return_type_verdicts_arrow(self):
+ # Correct in both states: before the gate flip nothing transpiles on
the Arrow eval
+ # type, and afterwards the verdicts must equal the pickled ones --
except for the
+ # return types Arrow cannot express at all, which fail earlier and
either way.
+ expected = {}
+ for label, verdict in _EXPECTED_RETURN_VERDICT.items():
+ if label in _ARROW_REJECTED_RETURN_TYPES:
+ expected[label] = REJECTED_BY_ARROW
+ elif verdict == REJECTED_CHAR_VARCHAR:
+ # Rejected at UDF construction for every eval type, gate or no
gate.
+ expected[label] = REJECTED_CHAR_VARCHAR
+ elif ARROW_TRANSPILE_SUPPORTED:
+ expected[label] = verdict
+ else:
+ expected[label] = NO_TRANSPILE
+
+ with self.sql_conf(_TRANSPILE_ON):
+ observed = {}
+ for label, dt, cat in _SAMPLES:
+ observed[label] = self._return_verdict(dt, _BODIES[cat],
_ARROW)
+ self._assert_verdicts(
+ expected,
+ observed,
+ "the Arrow return verdicts derived from _EXPECTED_RETURN_VERDICT",
+ "Transpilation should admit exactly the same return types on both
eval types; "
+ "the only Arrow-specific difference is the return types Arrow
cannot express, "
+ "listed in _ARROW_REJECTED_RETURN_TYPES.",
+ )
+
+ # -- input-type verdicts
------------------------------------------------------------
+
+ def _null_row_df(self, dt):
+ schema = T.StructType([T.StructField("a", dt)])
+ return self.spark.createDataFrame([(None,)], schema=schema)
+
+ def _input_verdict(self, dt, eval_type):
+ try:
+ df = self._null_row_df(dt)
+ df.count()
+ except Exception: # the type simply cannot be a column
+ return NOT_A_COLUMN_TYPE
+ pudf = UserDefinedFunction(null_probe, T.LongType(),
evalType=eval_type)
+ # Plan only: whether an option survived JVM-side pruning shows up as
the presence
+ # or absence of a Python-eval operator, and needs no Python execution.
+ counts = _eval_python_nodes(df.select(pudf("a")))
+ return NO_TRANSPILE if sum(counts.values()) else TRANSPILES
+
+ def test_input_type_verdicts_pickled(self):
+ with self.sql_conf(_TRANSPILE_ON):
+ observed = {label: self._input_verdict(dt, _PICKLED) for label,
dt, _cat in _SAMPLES}
+ self._assert_verdicts(
+ _EXPECTED_INPUT_VERDICT,
+ observed,
+ "_EXPECTED_INPUT_VERDICT",
+ "The input-type check is
ResolveTranspiledPythonUDFOptions.optionMatchesTypes; "
+ "its `case _ => false` is what makes an unrecognised column type
fall back. If a "
+ "type now TRANSPILES, verify parity for it before updating the
table.",
+ )
+
+ def test_input_type_verdicts_arrow(self):
+ expected = {
+ label: (
+ verdict
+ if (ARROW_TRANSPILE_SUPPORTED or verdict == NOT_A_COLUMN_TYPE)
+ else NO_TRANSPILE
+ )
+ for label, verdict in _EXPECTED_INPUT_VERDICT.items()
+ }
+ with self.sql_conf(_TRANSPILE_ON):
+ observed = {label: self._input_verdict(dt, _ARROW) for label, dt,
_cat in _SAMPLES}
+ self._assert_verdicts(
+ expected,
+ observed,
+ "the Arrow input verdicts derived from _EXPECTED_INPUT_VERDICT",
+ "The set of column types a transpiled option can bind to is
decided on the JVM "
+ "side and must not depend on the eval type.",
+ )
+
+ def test_no_transpile_input_types_still_compute_correctly(self):
+ # The point of a fallback: a column type the transpiler cannot bind to
must still
+ # produce the interpreted answer rather than an error or a wrong value.
+ for label, dt, _cat in _SAMPLES:
+ if _EXPECTED_INPUT_VERDICT[label] != NO_TRANSPILE:
+ continue
+ with self.subTest(label=label):
+ df = self._null_row_df(dt)
+ pudf = UserDefinedFunction(null_probe, T.LongType(),
evalType=_PICKLED)
Review Comment:
**Nit (P3):** `pudf` is built here, before `self.sql_conf(_TRANSPILE_ON)` is
entered. Transpilation is decided at construction, as this module notes at
lines 568-569, and `spark.sql.experimental.optimizer.transpilePyUDFs` defaults
to false, so the UDF carries no options and the `on` and `off` collects run the
same interpreted plan. `assertEqual(off, on)` therefore cannot fail: if
ConvertToCatalyst stopped falling back when every option is pruned for a date
or decimal column, this test would still pass. Suggested fix: build the `on`
UDF inside the transpile-on block and assert that it carries options before
collecting.
**Verification:**
- **Regression:** For each NO_TRANSPILE scalar input type, a UDF built with
transpilation on carries options, its executed query keeps the Python
evaluation, and it returns the interpreted value for a NULL row.
##########
python/pyspark/sql/transpile.py:
##########
@@ -299,6 +389,169 @@ 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(), *_]):
+ return (
+ "an `is` / `is not` 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():
+ return (
+ "a 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)"
+ case ast.Name(id=name):
+ return f"the free variable {name!r}"
+ case ast.Call():
+ return "a function call other than the `.isnull()` family"
+ case _:
+ return f"an unsupported `{type(node).__name__}` node"
+
+
+def _check_series_semantics(function_ast: ast.FunctionDef, params: List[str])
-> None:
+ """Raise unless the body is element-wise-equivalent for a scalar pandas
UDF.
+
+ Two properties are checked together because both are about the body as a
whole:
+
+ * every node is in the allowlist, so no lowering written for Python
scalars is reused
+ where pandas would raise or answer differently;
+ * the body references at least one parameter. With only the allowlisted
operators, an
+ expression containing a parameter is a Series and one without is a
Python scalar --
+ and returning a scalar makes the interpreted UDF fail with
``UDF_RETURN_TYPE``, so a
+ rewrite that returned a value per row would not be a faithful
reproduction.
+ """
+ # Match the statement-count guard in ``_transpile_from_ast`` first, and
with the same
+ # message (shared constant): this walk only visits ``body[0]``, so without
this a
+ # multi-statement body would be rejected as "an unsupported `Assign` node"
(its first
+ # statement) rather than for the real reason, and the warning is the only
place the user
+ # learns why.
+ if len(function_ast.body) != 1:
Review Comment:
**Nit (P3):** This count runs on the raw body, but `_transpile_from_ast`
first folds the two-statement early-return form (`if <test>: return y` followed
by `return z`) into one if/else and only then counts statements (lines
1364-1375). So the comment's claim that this matches that guard does not hold,
and a scalar pandas UDF like `branching` (`if s > 0: return 1` then `return 0`)
is refused with 'functions with more than one top-level statement are not
supported by the transpiler'. That reason is false for this shape, and a user
who rewrites it as the single statement `return 1 if s > 0 else 0` is refused
again, this time for the `if`. Since this warning is the only place users learn
why the rewrite did not happen, it should name the `if`. Suggested fix: share
the early-return fold with this pre-check, so the folded body is refused for
its `if` while a genuine multi-statement body keeps this reason.
**Verification:**
- **Regression:** With transpilation and ANSI on, defining the early-return
pandas UDF emits an 'Unable to transpile UDF' warning that mentions the `if`
and not 'more than one top-level statement', and the UDF still raises as it
does when interpreted.
- **Behavior:** A pandas UDF with an assignment followed by a return still
falls back with the multi-statement reason.
##########
python/pyspark/sql/transpile.py:
##########
@@ -1092,6 +1429,21 @@ def _transpile_from_ast(
UserWarning,
stacklevel=2,
)
+ if series_semantics and body_cat is not None and
_is_numeric_cat(body_cat):
Review Comment:
**Non-blocking (P2):** This wrap is emitted for every numeric body category,
including options whose parameters are all `'integer'`, on the stated premise
that the bound column's width is unknown until the JVM prunes options. It is
known: each option carries its variant's per-parameter categories (lines
1954-1956), and ResolveTranspiledPythonUDFOptions binds an `'integer'` option
only to IntegralType columns, where NaN is impossible. On those options the
`isnan` test never fires, but the CASE WHEN still references the body twice, so
it is computed twice per row, and `mustPreEvaluate` counts the second
`_udf_param_N` read. Reading the code, `F.sum(plus_one(F.col('v') + 1))` under
a `groupBy` therefore keeps the Python UDF, because `v + 1` is not cheap to
repeat and an Aggregate cannot hold a pre-evaluation column, where the option
without the wrap would transpile. The `isnan` arm of `_lower_series_null_check`
(lines 879-880) has the same effect. Results do not change, but the 'plan
-size cost only' and 'one extra node' comments understate the cost. Suggested
fix: emit the normalization only when some parameter of the variant is
`'float'` (or `'numeric'`) or the body has a float constant, and the `isnan`
arm only for such a receiver.
**Verification:**
- **Regression:** A scalar pandas UDF returning `s + 1`, called with a
non-cheap integral argument such as `v + 1` inside a grouped sum and inside a
join condition, runs with no Python evaluation left in the plan and returns the
interpreted results.
- **Behavior:** Over integral columns with NULLs, `s + 1`, `-s`, `s % 3` and
`s.isnull()` still match the interpreted pandas results. Over double columns
with NaN and NULL, `s + 1`, `-s`, `s * 1e400` and `s.isnull()` still map NaN to
NULL, or to True for the null check, as before.
- **Inspection:** The optimized plan of an integer-variant pandas option has
no isnan test wrapping its body, and the comments state the variant-based rule
instead of the width premise.
--
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]