holdenk commented on code in PR #59724:
URL: https://github.com/apache/spark/pull/59724#discussion_r4580922057
##########
python/pyspark/sql/transpile.py:
##########
@@ -90,6 +90,75 @@
expression. A draw is never inlined, because those rules check determinism.
An argument the body never reads is not computed at all.
+
+
+Scalar pandas UDFs
+------------------
+A scalar pandas UDF receives one ``pandas.Series`` per argument and must
return a
+Series, so most of the lowerings above -- which were written against Python
+scalars -- do NOT carry over. Only the subset whose Python-scalar meaning
+coincides with pandas' element-wise meaning is reused, selected by the strict
+allowlist in :func:`_check_series_semantics`: parameter references, ``int`` /
+``float`` / ``str`` constants, ``+`` ``-`` ``*`` ``%``, unary ``+`` / ``-``,
and
+``<param>.isnull()`` (with the ``.isna()`` / ``.notnull()`` / ``.notna()``
+aliases). Everything else falls back to interpreted Python. The exclusions are
+not conservatism for its own sake -- each one is a construct whose scalar
+lowering would be actively wrong on a Series:
+
+* ``if x:``, ``x and y``, ``not x`` -- pandas raises
+ ``ValueError: The truth value of a Series is ambiguous``. Lowering them to
+ ``CASE WHEN`` / ``AND`` / ``NOT`` would turn a UDF that raises today into one
+ that returns values.
+* ``x is None`` -- always ``False``, because the *Series object* is not None.
+ ``isnull(a)`` would answer a different question; ``x.isnull()`` is the
+ construct that means what ``x is None`` means for a scalar.
+* ``x < y`` and friends -- a missing value compares ``False`` under numpy
+ (never ``NULL``, and never a ``TypeError``, so the ``raise_error`` guard the
+ scalar lowering emits is wrong), and NaN compares ``False`` where Spark
orders
+ it above every value.
+* a body that never references a parameter (``return 1``) -- the result is a
+ scalar, which the interpreted path rejects with ``UDF_RETURN_TYPE``.
+
+Two pandas-specific value rules are then reproduced explicitly:
+
+* NaN in the result is serialized as NULL -- but only in the default dtype
regime,
+ where the result Series is numpy-backed and the return path masks it with
+ ``series.isnull()``. A pandas masked extension array (which is what
+ ``spark.sql.execution.pythonUDF.pandas.preferIntExtensionDtype=true``
produces,
+ for integral inputs and float arithmetic derived from them) is handed
+ to Arrow with ``mask=None`` instead, and its ``isnull()`` is False for NaN in
+ any case, so there the same NaN arrives as NaN. Catalyst keeps NaN, so a
numeric
+ body with a fractional category is wrapped in an ``isnan -> NULL``
normalization for the
+ default regime -- and transpilation is refused outright when that conf is on,
+ since no single expression covers both. Modulo by zero returns NULL in this
regime.
+* ``Series.isnull()`` is True for NaN on a numpy-backed Series -- by the time
the
+ UDF runs, the Arrow-to-pandas conversion has already collapsed a NULL in a
+ fractional column into NaN and pandas cannot tell them apart -- so it lowers
to
+ ``isnull(a) OR isnan(a)`` for fractional variants, and ``isnull(a)``
otherwise. (On a masked
+ extension array ``isnull()`` is the mask alone, but that regime is refused
per
+ the previous point.)
+
+What remains divergent is numpy's fixed-width arithmetic, and it is documented
+rather than guarded because it cannot be detected without the runtime values.
+Every case is one where the transpiled expression raises or is exact and the
+interpreted one is lossy, silent, or inconsistent:
+
+* integer overflow wraps under numpy where ANSI raises ARITHMETIC_OVERFLOW.
This
+ also covers the ``%`` boundaries the ``Mod`` lowering notes below
Review Comment:
Fixed in 1d0803209: `Long.MinValue % -1` (and `a % Long.MinValue`) moved out
of the numpy-wraps bullet into the 'runs the other way' paragraph of the module
docstring, the Mod lowering comment now says the interpreted side is the exact
one, and the test is renamed
`test_modulo_overflow_boundary_raises_where_numpy_is_exact` with its comment
and the `PandasUDFTranspileDivergenceTests` docstring corrected. The boundary
itself stays until the `%` lowering changes (Blocking thread), which will then
drop these sentences.
---
<sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of
@holdenk.</sub>
<!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk
-->
##########
python/pyspark/sql/transpile.py:
##########
@@ -1092,6 +1427,10 @@ def _transpile_from_ast(
UserWarning,
stacklevel=2,
)
+ if series_semantics and body_cat in ("float", "numeric"):
+ # The default pandas return conversion masks NaN as NULL. Integral
variants
+ # cannot produce NaN and must avoid duplicating their argument
references.
+ converted = when(isnan(converted.cast("double")),
lit(None)).otherwise(converted)
Review Comment:
Fixed in 1d0803209: a 'float' body now uses `nanvl(converted, NULL)` and a
'float' receiver `isnull(nanvl(subject.cast('double'), NULL))`, so each reads
its input once; only the 'numeric' catch-all keeps the CASE form. Added
`test_fractional_options_do_not_duplicate_noncheap_arguments` (grouped `max`
over `pudf(v + 1)` on a double column with NaN and NULL, for `s + 1` and
`s.isnull()`: no Python eval node left, same results as interpreted). It fails
on the previous code.
---
<sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of
@holdenk.</sub>
<!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk
-->
##########
python/pyspark/sql/transpile.py:
##########
@@ -299,6 +384,177 @@ def _null_narrowed(params: List[str], test_node: ast.AST)
-> Tuple[frozenset, fr
return frozenset(), frozenset()
+# ----------------------------------------------------------------------------
+# Scalar pandas UDF (Series in / Series out) support. See the module docstring
+# for why the subset below is an allowlist rather than a set of exclusions.
+# ----------------------------------------------------------------------------
+
+# ``pandas.Series`` methods meaning "is this element missing", mapped to
whether the method
+# is the positive form. All four are the same lowering up to a negation.
+_SERIES_NULL_METHODS = {"isnull": True, "isna": True, "notnull": False,
"notna": False}
+
+# Binary and unary operators pandas applies element-wise with the same result
Catalyst
+# produces, given operands of a matching category (`_category` still decides
add-vs-concat
+# and multiply-vs-repeat). `**` and `/` are absent because the scalar
transpiler does not
+# lower them either.
+#
+# `Mult` is in the allowlist for numeric multiply and for string-repeat by an
integer
+# LITERAL only (`s * 2`). Repeat by a numeric COLUMN is refused under series
semantics in
+# `_convert_chunk`, because a Series count is unsound in every batch shape:
pandas raises
+# TypeError on any genuine float value (so `_masked_arith_op` only succeeds
when the whole
+# batch is missing, yielding NULL), while the lowered `repeat(s, cast(n as
int))` returns a
+# repeated string for a real value and raises CAST_OVERFLOW for a NaN -- so an
all-missing
+# batch turns a NULL-returning query into an error. See
`_reject_series_string_repeat`.
+_SERIES_SAFE_BINOPS = (ast.Add, ast.Sub, ast.Mult, ast.Mod)
+_SERIES_SAFE_UNARYOPS = (ast.UAdd, ast.USub)
+
+
+def _is_int_literal(node: ast.AST) -> bool:
+ """True for an ``int`` constant that is not a ``bool`` (``bool``
subclasses ``int``).
+
+ This is the only repeat count that is safe under series semantics: it
cannot be NaN or
+ NULL, and it is fixed at transpile time so no column value can make it
fractional.
+ """
+ return (
+ isinstance(node, ast.Constant)
+ and isinstance(node.value, int)
+ and not isinstance(node.value, bool)
+ )
+
+
+# Raised from both the up-front ``_check_series_semantics`` call and
``_transpile_from_ast``
+# itself; a single constant keeps the two paths reporting the same reason.
+_MULTI_STATEMENT_ERROR = (
+ "functions with more than one top-level statement are not supported by the
transpiler"
+)
+
+
+def _match_series_null_check(node: ast.AST, params: List[str]) ->
Optional[Tuple[ast.Name, bool]]:
+ """Match ``<param>.isnull()`` and its aliases, returning ``(receiver,
positive)``.
+
+ ``None`` when ``node`` is any other call. The receiver must be a bare
parameter: on an
+ intermediate expression the ``isnan`` arm of the lowering would have to
reason about
+ which sub-expression can produce NaN, so those fall back to interpreted
Python instead.
+ Arguments are refused too (``isna()`` takes none, but a future keyword
should not be
+ silently ignored).
+ """
+ match node:
+ case ast.Call(
+ func=ast.Attribute(value=ast.Name(id=receiver_name) as receiver,
attr=attr),
+ args=[],
+ keywords=[],
+ ) if receiver_name in params and attr in _SERIES_NULL_METHODS:
+ return receiver, _SERIES_NULL_METHODS[attr]
+ case _:
+ return None
+
+
+def _describe_unsupported_series_node(node: ast.AST) -> str:
+ """A short user-facing label for a node refused by
:func:`_check_series_semantics`.
+
+ These end up in the ``Unable to transpile UDF ...`` warning, which is the
only place a
+ user learns why the rewrite did not happen, so name the pandas-specific
reason rather
+ than just the AST class. Only the constructs whose pandas divergence is
non-obvious
+ get a custom message; everything else falls through to a generic label.
+ """
+ match node:
+ case ast.Compare(ops=[ast.Is() | ast.IsNot(), *_]):
Review Comment:
Fixed in 1d0803209: the fallback reasons are now per operator. `is` points
at `x.isnull()`, `is not` at `x.notnull()`, `==` / `!=` say a missing value or
NaN is never equal on a Series (False for `==`, True for `!=`), and the
ordering wording is limited to `<` `<=` `>` `>=`. The module docstring bullet
notes `!=`. `test_comparisons_fall_back` and `test_is_none_falls_back` now
cover `s != 0`, `s is not None` and `s < 0` with their reasons.
---
<sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of
@holdenk.</sub>
<!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk
-->
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -706,7 +706,26 @@ object SQLConf {
"UDF construction. Transpiled UDFS attempt to match the Python
functionality but " +
"may not be 100% equivalent. Some known differences include: overflows
from input types " +
"(you can precast to decimal to avoid), type coercion on comparison,
and implicit " +
- "returns. This initial version only works with non-Connect Spark;
Spark Connect " +
+ "returns. Applies to regular Python UDFs whether or not they are
Arrow-optimized, " +
+ "except when
spark.sql.legacy.execution.pythonUDF.pandas.conversion.enabled is set, " +
Review Comment:
Fixed in 1d0803209: the transpilePyUDFs doc now says the legacy pandas
conversion conf disables transpilation of Arrow-optimized UDFs only.
---
<sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of
@holdenk.</sub>
<!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk
-->
##########
python/pyspark/sql/tests/arrow/test_arrow_python_udf_transpile.py:
##########
@@ -0,0 +1,1050 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""
+Transpilation of Arrow-optimized Python UDFs (``SQL_ARROW_BATCHED_UDF``).
+
+Arrow optimization is the default for regular Python UDFs, so a plain
+``functions.udf(f, "bigint")`` gets ``SQL_ARROW_BATCHED_UDF``. Until that eval
type was
+admitted to ``_TRANSPILABLE_EVAL_TYPES`` in ``python/pyspark/sql/udf.py``, the
transpilation
+flag did nothing on default configuration.
+
+This is a separate module from ``pyspark.sql.tests.test_udf_transpile_unit``
because the
+reference semantics differ. The pickled path coerces a UDF's return value
through
+``EvaluatePython.makeFromJava``, which NULLs a type mismatch; the Arrow path
builds a
+``pa.array`` and falls back to a cast (``python/pyspark/worker.py``), which
can raise or
+convert instead. So every differential here compares transpiled-Arrow against
+interpreted-**Arrow**: the question is whether the rewrite matches what this
UDF would have
+done in its own eval mode. The cell-by-cell matrix for both regimes lives in
the golden
+files under ``python/pyspark/sql/tests/coercion/``.
+
+Naming trap: ``SQL_ARROW_BATCHED_UDF`` (101) is the Arrow-*optimized* regular
UDF -- Arrow
+is only the transport, and the worker still calls the function once per row
with Python
+scalars. ``SQL_SCALAR_ARROW_UDF`` (250) is genuinely vectorized and must never
be
+transpiled. ``test_eval_type_allowlist_is_exhaustive`` guards the distinction.
+
+UDF bodies here are all named ``def``s. The transpiler recovers source with
+``inspect.getsource``, which for a lambda passed as a call argument returns
the enclosing
+statement -- whose top-level node is a call, not a lambda -- so transpilation
silently falls
+back and the test passes while asserting nothing. ``_assert_transpiled``
catches that.
+"""
+
+import unittest
+import warnings
+from collections import Counter
+
+from pyspark.errors import PythonException
+from pyspark.sql import Row
+from pyspark.sql.functions import udf
+from pyspark.sql.types import (
+ BinaryType,
+ BooleanType,
+ ByteType,
+ CalendarIntervalType,
+ DecimalType,
+ DoubleType,
+ IntegerType,
+ LongType,
+ StringType,
+)
+from pyspark.sql.udf import UserDefinedFunction
+from pyspark.testing.objects import ExamplePoint, ExamplePointUDT
+from pyspark.testing.sqlutils import ReusedSQLTestCase
+from pyspark.testing.utils import (
+ have_pandas,
+ have_pyarrow,
+ pandas_requirement_message,
+ pyarrow_requirement_message,
+)
+from pyspark.util import PythonEvalType, is_remote_only
+
+if have_pandas:
+ import pandas as pd
+
+
+# Kept as a constant so ``test_arrow_transpile_flag_matches_reality`` fails in
either
+# direction if the eval-type gate in python/pyspark/sql/udf.py and this file
disagree.
+ARROW_TRANSPILE_SUPPORTED = True
+
+# Transpilation requires both flags, at construction and again in
ConvertToCatalyst.
+_TRANSPILE_ON = {
+ "spark.sql.experimental.optimizer.transpilePyUDFs": True,
+ "spark.sql.ansi.enabled": True,
+}
+
+# ANSI stays on for the interpreted side so a differential isolates the
rewrite rather than
+# also flipping overflow semantics.
+_TRANSPILE_OFF = {
+ "spark.sql.experimental.optimizer.transpilePyUDFs": False,
+ "spark.sql.ansi.enabled": True,
+}
+
+# A differential that silently falls back compares interpreted against
interpreted and
+# passes for the wrong reason, so these warnings are fatal. These are exactly
the three
+# warnings udf.py emits when a rewrite does not happen ("Unable to transpile
UDF ...",
+# "Exception transpiling UDF ...", and the ANSI-disabled one); kept in sync
with the
+# identical tuple in pyspark.sql.tests.pandas.test_pandas_udf_transpile.
+_BAD_TRANSPILE_WARNING_MARKERS = (
+ "Unable to transpile",
+ "Exception transpiling",
+ "is only supported when ANSI mode is enabled",
+)
+
+# "This side raised instead of returning rows."
+_RAISED = object()
+
+# Eval types that hand the function a whole pandas.Series or pyarrow.Array and
are still
+# refused outright. SQL_SCALAR_PANDAS_UDF is deliberately absent: it is also
vectorized, but
+# it is transpiled for the element-wise subset of bodies covered by
+# ``pyspark.sql.tests.pandas.test_pandas_udf_transpile``.
+_VECTORIZED_SCALAR_EVAL_TYPES = (
+ PythonEvalType.SQL_SCALAR_PANDAS_ITER_UDF,
+ PythonEvalType.SQL_SCALAR_ARROW_UDF,
+ PythonEvalType.SQL_SCALAR_ARROW_ITER_UDF,
+)
+
+_GROUPED_AGG_EVAL_TYPES = (
+ PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF,
+ PythonEvalType.SQL_GROUPED_AGG_PANDAS_ITER_UDF,
+ PythonEvalType.SQL_GROUPED_AGG_ARROW_UDF,
+ PythonEvalType.SQL_GROUPED_AGG_ARROW_ITER_UDF,
+)
+
+
+# --- UDF bodies
------------------------------------------------------------------------
+
+
+def add_one(x):
+ return x + 1
+
+
+def add_four(x):
+ return x + 4
+
+
+def identity(x):
+ return x
+
+
+def constant_42(x):
+ return 42
+
+
+def gt_one(x):
+ return x > 1
+
+
+def is_null(x):
+ return x is None
+
+
+def square(x):
+ return x * x
+
+
+def mod_zero(x):
+ return x % 0
+
+
+def add_half(x):
+ return x + 0.5
+
+
+def times_thousand(x):
+ return x * 1000
+
+
+def floor_halve(x):
+ # Floor division is not lowered: the canonical "must stay interpreted"
body.
+ return x // 2
+
+
+def floor_third(x):
+ return x // 3
+
+
+def guarded_add_one(x):
+ # Single top-level statement; the transpiler rejects more than one. The
implicit
+ # else yields NULL, which is also what the interpreted path returns.
+ if x is not None:
+ return x + 1
+
+
+def num_add(x):
+ return x + 3
+
+
+def num_sub(x):
+ return x - 3
+
+
+def num_mul(x):
+ return x * 3
+
+
+def num_mod(x):
+ return x % 3
+
+
+def num_neg(x):
+ return -x
+
+
+def num_pos(x):
+ return +x
+
+
+_NUMERIC_ARITHMETIC = (num_add, num_sub, num_mul, num_mod, num_neg, num_pos)
+
+
+def cmp_lt(x):
+ return x < 2
+
+
+def cmp_le(x):
+ return x <= 2
+
+
+def cmp_gt(x):
+ return x > 2
+
+
+def cmp_ge(x):
+ return x >= 2
+
+
+def cmp_eq(x):
+ return x == 2
+
+
+def cmp_ne(x):
+ return x != 2
+
+
+_NUMERIC_COMPARISONS = (cmp_lt, cmp_le, cmp_gt, cmp_ge, cmp_eq, cmp_ne)
+
+
+# Annotations pin a parameter's input-type category; an unannotated parameter
is only tried
+# as numeric and string.
+def str_concat(x: str):
+ return x + x
+
+
+def repeat_negated(x):
+ return "ab" * -x
+
+
+def repeat_positive(x):
+ return "ab" * +x
+
+
+def repeat_negated_left(x, s: str):
+ return -x * s
+
+
+def repeat_negative_float(s: str):
+ return s * -1.5
+
+
+def negated_equals_two(x):
+ return -x == 2
+
+
+def guarded_negated_equals_two(x):
+ return False if x is None else -x == 2
+
+
+def str_repeat_right(x: str):
+ return x * 3
+
+
+def str_repeat_left(x: str):
+ return 3 * x
+
+
+_STRING_BODIES = (str_concat, str_repeat_right, str_repeat_left)
+
+
+def str_is_abc(x: str):
+ return x == "abc"
+
+
+def bool_identity(x: bool):
+ return x
+
+
+# `not`/`and`/`or` need a statically-boolean operand, which a bare parameter
is not (see
+# _is_definitely_boolean); those fall back, as
test_udf_transpile_{not,and_or}_bare_param_*
+# in the non-Arrow unit suite pin. Wrapping a comparison is what makes them
lowerable.
+def not_compare(x):
+ return not (x > 2)
+
+
+def and_compare(x):
+ return (x > 0) and (x < 10)
+
+
+def or_compare(x):
+ return (x < 0) or (x > 10)
+
+
+_BOOL_LOGIC_BODIES = (not_compare, and_compare, or_compare)
+
+
+def bytes_identity(x: bytes):
+ return x
+
+
+def _arrow_udf(func, return_type):
+ """Build a UDF pinned to the Arrow-optimized eval type.
+
+ ``UserDefinedFunction`` defaults to ``SQL_BATCHED_UDF``, and constructing
it directly
+ also bypasses ``_create_py_udf``'s type-hint eval-type inference -- which
matters for
+ the annotated bodies above, whose annotations are category hints rather
than a
+ vectorized signature.
+ """
+ return UserDefinedFunction(func, return_type,
evalType=PythonEvalType.SQL_ARROW_BATCHED_UDF)
+
+
+def _pickled_udf(func, return_type):
+ """Build a UDF pinned to the pickled eval type, for contrast with
``_arrow_udf``."""
+ return UserDefinedFunction(func, return_type,
evalType=PythonEvalType.SQL_BATCHED_UDF)
+
+
+def _eval_python_nodes(df):
+ """Count Python-eval physical operators in ``df``'s executed plan, by
class name.
+
+ Counting nodes rather than substring-matching the plan string matters
because
+ ``"ArrowEvalPython"`` contains ``"EvalPython"``. Traversal follows
+ ``_assert_columnar_arrow_eval`` in test_arrow_python_udf_cached.py.
+ """
+ counts: Counter = Counter()
+ stack = [df._jdf.queryExecution().executedPlan()]
+ while stack:
+ node = stack.pop()
+ name = node.getClass().getSimpleName()
+ if name == "AdaptiveSparkPlanExec":
+ stack.append(node.executedPlan())
+ continue
+ if name.endswith("EvalPythonExec"):
+ counts[name] += 1
+ children = node.children()
+ for i in range(children.size()):
+ stack.append(children.apply(i))
+ return counts
+
+
+def _python_udf_expr_count(df):
+ """Count PythonUDF expression nodes across every Python-eval operator in
``df``.
+
+ Operator counts alone no longer say whether a call was lowered: a chain of
UDFs is
+ evaluated as a pipeline inside ONE operator, so three chained UDFs and one
UDF both
+ show a single ArrowEvalPythonExec. What still distinguishes them is how
many PythonUDF
+ expressions that operator holds -- a lowered call is gone from the tree,
while the alias
+ naming it survives, so this counts nodes rather than matching the plan
string.
+ """
+ total = 0
+ stack = [df._jdf.queryExecution().executedPlan()]
+ while stack:
+ node = stack.pop()
+ name = node.getClass().getSimpleName()
+ if name == "AdaptiveSparkPlanExec":
+ stack.append(node.executedPlan())
+ continue
+ if name.endswith("EvalPythonExec"):
+ udfs = node.udfs()
+ for i in range(udfs.size()):
+ exprs = [udfs.apply(i)]
+ while exprs:
+ expr = exprs.pop()
+ if expr.getClass().getSimpleName() == "PythonUDF":
+ total += 1
+ expr_children = expr.children()
+ for j in range(expr_children.size()):
+ exprs.append(expr_children.apply(j))
+ children = node.children()
+ for i in range(children.size()):
+ stack.append(children.apply(i))
+ return total
+
+
[email protected](is_remote_only(), "UDF transpilation is only supported in
non-Connect Spark.")
[email protected](
+ not have_pandas or not have_pyarrow,
+ pandas_requirement_message or pyarrow_requirement_message, # type:
ignore[arg-type]
+)
+class ArrowUDFTranspileTestsMixin:
+ """Helpers shared by the suites in this module."""
+
+ def _assert_transpiled(self, pudf, what):
+ self.assertTrue(
+ pudf.transpiled,
+ f"expected {what} to transpile, but no Catalyst expression was
produced; "
+ "a parity assertion against the interpreted path would be vacuous",
+ )
+
+ def _values_or_raised(self, df):
+ try:
+ return [row[0] for row in df.collect()], None
+ except Exception as e: # the exception itself is what we compare
+ return _RAISED, e
+
+ def _differential(self, func, return_type, df, *cols, eval_type=None,
conf=None):
+ """Run ``func`` with transpilation on and off; return ``(values,
error)`` for each.
+
+ Both sides use the same eval type, so the reference is the interpreted
behavior of
+ the very UDF being rewritten. ``values`` is the produced list, or
``_RAISED``.
+ """
+ eval_type = eval_type or PythonEvalType.SQL_ARROW_BATCHED_UDF
+ extra = conf or {}
+ name = getattr(func, "__name__", repr(func))
+
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ with self.sql_conf({**_TRANSPILE_ON, **extra}):
+ pudf = UserDefinedFunction(func, return_type,
evalType=eval_type)
+ self._assert_transpiled(pudf, name)
+ on = self._values_or_raised(df.select(pudf(*cols)))
+ bad = [
+ str(w.message)
+ for w in caught
+ if any(m in str(w.message) for m in _BAD_TRANSPILE_WARNING_MARKERS)
+ ]
+ self.assertFalse(bad, f"unexpected transpile warnings for {name}:
{bad}")
+
+ with self.sql_conf({**_TRANSPILE_OFF, **extra}):
+ pudf = UserDefinedFunction(func, return_type, evalType=eval_type)
+ off = self._values_or_raised(df.select(pudf(*cols)))
+
+ return on, off
+
+ def _assert_matches_interpreted(self, func, return_type, df, *cols,
eval_type=None, conf=None):
+ """Assert transpiled and interpreted agree, including on whether they
raise."""
+ (on_values, on_error), (off_values, off_error) = self._differential(
+ func, return_type, df, *cols, eval_type=eval_type, conf=conf
+ )
+ name = getattr(func, "__name__", repr(func))
+ if off_values is _RAISED:
+ self.assertIs(
+ on_values,
+ _RAISED,
+ f"{name}: interpreted raised {off_error!r} but transpiled
returned {on_values!r}",
+ )
+ return
+ self.assertIsNot(
+ on_values,
+ _RAISED,
+ f"{name}: transpiled raised {on_error!r} but interpreted returned
{off_values!r}",
+ )
+ self.assertEqual(off_values, on_values, f"{name}: transpiled !=
interpreted")
+
+
+class ArrowUDFTranspileEvalTypeGateTests(ArrowUDFTranspileTestsMixin,
ReusedSQLTestCase):
+ """Which eval types may be transpiled at all."""
+
+ def test_arrow_transpile_flag_matches_reality(self):
+ with self.sql_conf(_TRANSPILE_ON):
+ pudf = _arrow_udf(add_one, LongType())
+ self.assertEqual(
+ bool(pudf.transpiled),
+ ARROW_TRANSPILE_SUPPORTED,
+ "ARROW_TRANSPILE_SUPPORTED disagrees with the eval-type gate
in "
+ "python/pyspark/sql/udf.py; update whichever one is wrong.",
+ )
+
+ def test_arrow_batched_eval_type_transpiles_and_computes(self):
+ with self.sql_conf(_TRANSPILE_ON):
+ pudf = _arrow_udf(add_four, LongType())
+ self._assert_transpiled(pudf, "an Arrow-optimized UDF")
+ df = self.spark.createDataFrame([Row(a=1)])
+ self.assertEqual([5], [r[0] for r in
df.select(pudf("a")).collect()])
+
+ def test_functions_udf_transpiles_on_default_configuration(self):
+ # The motivating case: no useArrow argument, so functions.udf picks the
+ # Arrow-optimized eval type from the default of
+ # spark.sql.execution.pythonUDF.arrow.enabled (true) -- what users
write. Only the
+ # experimental transpile flag is set; the arrow conf is left at its
default so this
+ # actually exercises it rather than pinning it.
+ with self.sql_conf(_TRANSPILE_ON):
+ wrapped = udf(add_four, LongType())
+ self.assertEqual(wrapped.evalType,
PythonEvalType.SQL_ARROW_BATCHED_UDF)
+ self._assert_transpiled(wrapped._unwrapped, "functions.udf on
default config")
+ df = self.spark.createDataFrame([Row(a=1)])
+ self.assertEqual([5], [r[0] for r in
df.select(wrapped("a")).collect()])
+
+ def test_pickled_eval_type_still_transpiles(self):
+ # Regression guard on rewriting the gate as set membership.
+ with self.sql_conf(_TRANSPILE_ON):
+ pudf = _pickled_udf(add_four, LongType())
+ self._assert_transpiled(pudf, "a pickled UDF")
+ df = self.spark.createDataFrame([Row(a=1)])
+ self.assertEqual([5], [r[0] for r in
df.select(pudf("a")).collect()])
+
+ def test_vectorized_scalar_eval_types_do_not_transpile(self):
+ # `x + 1` on a Series is a whole-batch operation, not the per-row
lowering the
+ # transpiler would emit.
+ with self.sql_conf(_TRANSPILE_ON):
+ for eval_type in _VECTORIZED_SCALAR_EVAL_TYPES:
+ with self.subTest(evalType=eval_type):
+ pudf = UserDefinedFunction(add_one, LongType(),
evalType=eval_type)
+ self.assertEqual([], pudf.transpiled)
+
+ def test_grouped_agg_eval_types_do_not_transpile(self):
+ with self.sql_conf(_TRANSPILE_ON):
+ for eval_type in _GROUPED_AGG_EVAL_TYPES:
+ with self.subTest(evalType=eval_type):
+ pudf = UserDefinedFunction(add_one, LongType(),
evalType=eval_type)
+ self.assertEqual([], pudf.transpiled)
+
+ def test_eval_type_allowlist_is_exhaustive(self):
+ # Enumerate every eval type Spark defines rather than listing the
excluded ones, so
+ # a newly added eval type shows up here instead of being silently
covered.
+ expected = {PythonEvalType.SQL_BATCHED_UDF}
+ if ARROW_TRANSPILE_SUPPORTED:
+ expected.add(PythonEvalType.SQL_ARROW_BATCHED_UDF)
+ # The one vectorized eval type that is transpiled, for the
element-wise subset only.
+ # ``add_one``'s body (`x + 1`) is inside that subset, which is why it
appears here;
+ # the subset itself is pinned by
+ # ``pyspark.sql.tests.pandas.test_pandas_udf_transpile``.
+ expected.add(PythonEvalType.SQL_SCALAR_PANDAS_UDF)
+
+ all_eval_types = {
+ name: value
+ for name, value in vars(PythonEvalType).items()
+ if name.startswith("SQL_") and isinstance(value, int)
+ }
+ recorded = {
+ "SQL_BATCHED_UDF",
+ "SQL_ARROW_BATCHED_UDF",
+ "SQL_ARROW_ELEMENTWISE_UDF",
+ "SQL_SCALAR_PANDAS_ELEMENTWISE_UDF",
+ "SQL_SCALAR_PANDAS_ITER_ELEMENTWISE_UDF",
+ "SQL_SCALAR_ARROW_ELEMENTWISE_UDF",
+ "SQL_SCALAR_ARROW_ITER_ELEMENTWISE_UDF",
+ "SQL_SCALAR_PANDAS_UDF",
+ "SQL_GROUPED_MAP_PANDAS_UDF",
+ "SQL_GROUPED_AGG_PANDAS_UDF",
+ "SQL_WINDOW_AGG_PANDAS_UDF",
+ "SQL_SCALAR_PANDAS_ITER_UDF",
+ "SQL_MAP_PANDAS_ITER_UDF",
+ "SQL_COGROUPED_MAP_PANDAS_UDF",
+ "SQL_MAP_ARROW_ITER_UDF",
+ "SQL_GROUPED_MAP_PANDAS_UDF_WITH_STATE",
+ "SQL_GROUPED_MAP_ARROW_UDF",
+ "SQL_COGROUPED_MAP_ARROW_UDF",
+ "SQL_TRANSFORM_WITH_STATE_PANDAS_UDF",
+ "SQL_TRANSFORM_WITH_STATE_PANDAS_INIT_STATE_UDF",
+ "SQL_TRANSFORM_WITH_STATE_PYTHON_ROW_UDF",
+ "SQL_TRANSFORM_WITH_STATE_PYTHON_ROW_INIT_STATE_UDF",
+ "SQL_GROUPED_MAP_ARROW_ITER_UDF",
+ "SQL_GROUPED_MAP_PANDAS_ITER_UDF",
+ "SQL_GROUPED_AGG_PANDAS_ITER_UDF",
+ "SQL_SCALAR_ARROW_UDF",
+ "SQL_SCALAR_ARROW_ITER_UDF",
+ "SQL_GROUPED_AGG_ARROW_UDF",
+ "SQL_WINDOW_AGG_ARROW_UDF",
+ "SQL_GROUPED_AGG_ARROW_ITER_UDF",
+ "SQL_GROUPED_AGG_ARROW_INCREMENTAL_PARTIAL_UDF",
+ "SQL_GROUPED_AGG_ARROW_INCREMENTAL_FINAL_UDF",
+ "SQL_WINDOW_AGG_ARROW_INCREMENTAL_UDF",
+ "SQL_SCALAR_ARROW_INPROCESS_UDF",
+ "SQL_TABLE_UDF",
+ "SQL_ARROW_TABLE_UDF",
+ "SQL_ARROW_UDTF",
+ }
+ self.assertEqual(
+ recorded,
+ set(all_eval_types),
+ "An eval type needs triage: update the recorded inventory and
admission tests.",
+ )
+ self.assertGreater(len(all_eval_types), 20, "eval-type introspection
found almost none")
+
+ transpiling = {}
+ with self.sql_conf(_TRANSPILE_ON):
+ for name, value in sorted(all_eval_types.items(), key=lambda kv:
kv[1]):
+ pudf = UserDefinedFunction(add_one, LongType(), evalType=value)
+ if pudf.transpiled:
+ transpiling[name] = value
+
+ self.assertEqual(
+ expected,
+ set(transpiling.values()),
+ f"the set of transpiling eval types changed:
{sorted(transpiling.items())}. "
+ "A per-row scalar Python UDF belongs in _TRANSPILABLE_EVAL_TYPES
in "
+ "python/pyspark/sql/udf.py and in this test. An eval type that
hands the "
+ "function a pandas.Series or pyarrow.Array needs more than that:
the lowerings "
+ "are written against Python scalars, so admitting one means
auditing every "
+ "construct for batch semantics first (see the 'Scalar pandas UDFs'
section of "
+ "python/pyspark/sql/transpile.py for how that was done for "
+ "SQL_SCALAR_PANDAS_UDF).",
+ )
+
+ def test_annotated_vectorized_function_via_functions_udf_transpiles(self):
+ # ``functions.udf`` infers SQL_SCALAR_PANDAS_UDF from the pandas
annotations, and
+ # `s + 1` is inside the element-wise subset, so this is transpiled.
The pandas
+ # semantics are covered in
pyspark.sql.tests.pandas.test_pandas_udf_transpile; what
+ # matters here is that arriving via ``functions.udf`` rather than
``pandas_udf``
+ # reaches the same gate.
+ def series_add_one(s: pd.Series) -> pd.Series:
+ return s + 1
+
+ with self.sql_conf(_TRANSPILE_ON):
+ wrapped = udf(series_add_one, LongType())
+ self.assertEqual(wrapped.evalType,
PythonEvalType.SQL_SCALAR_PANDAS_UDF)
+ self._assert_transpiled(wrapped._unwrapped, "an annotated pandas
UDF")
+ df = self.spark.createDataFrame([Row(a=1)])
+ self.assertEqual([2], [r[0] for r in
df.select(wrapped("a")).collect()])
+
+ def test_scalar_annotations_warn_about_eval_type_inference(self):
+ # Pins a pre-existing wart rather than endorsing it: a scalar
annotation is not a
+ # vectorized signature, so inference raises and degrades to a warning.
Annotations
+ # are how callers pin an input-type category, so users will hit this
and read it as
+ # a transpiler bug.
+ def scalar_add_one(x: int) -> int:
+ return x + 1
+
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ with self.sql_conf({"spark.sql.execution.pythonUDF.arrow.enabled":
True}):
+ wrapped = udf(scalar_add_one, LongType())
+ self.assertEqual(wrapped.evalType,
PythonEvalType.SQL_ARROW_BATCHED_UDF)
+ self.assertTrue(
+ any("Cannot infer the eval type from type hints" in str(w.message)
for w in caught),
+ f"expected the eval-type inference warning, got {[str(w.message)
for w in caught]}",
+ )
+
+ def test_nondeterministic_arrow_udf_does_not_transpile(self):
+ # A plain Catalyst expression could be folded, reordered or
duplicated, discarding
+ # the nondeterminism barrier.
+ with self.sql_conf(_TRANSPILE_ON):
+ pudf = _arrow_udf(add_one, LongType()).asNondeterministic()
+ self.assertEqual([], pudf.transpiled)
+
+ def test_ansi_disabled_warns_and_does_not_transpile(self):
+ for build in (_pickled_udf, _arrow_udf):
+ with self.subTest(build=build.__name__):
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ with self.sql_conf(
+ {
+
"spark.sql.experimental.optimizer.transpilePyUDFs": True,
+ "spark.sql.ansi.enabled": False,
+ }
+ ):
+ pudf = build(add_one, LongType())
+ self.assertEqual([], pudf.transpiled)
+ self.assertTrue(
+ any("ANSI mode" in str(w.message) for w in caught),
+ f"expected the ANSI-mode warning, got {[str(w.message) for
w in caught]}",
+ )
+
+ def test_return_type_unrepresentable_in_arrow_raises_cleanly(self):
+ # The transpile block reads self.returnType, which runs
_check_return_type inside a
+ # broad `except Exception`. Without a narrower handler the real error
would surface
+ # as a bogus "Exception transpiling UDF" warning first.
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ with self.sql_conf(_TRANSPILE_ON):
+ with self.assertRaises(Exception) as ctx:
+ _arrow_udf(identity, CalendarIntervalType())
+ self.assertIn("Invalid return type with Arrow-optimized Python UDF",
str(ctx.exception))
+ spurious = [str(w.message) for w in caught if "Exception transpiling"
in str(w.message)]
+ self.assertFalse(spurious, f"spurious transpilation warning:
{spurious}")
+
+
+class ArrowUDFTranspilePlanShapeTests(ArrowUDFTranspileTestsMixin,
ReusedSQLTestCase):
+ """What the executed plan looks like once a UDF is (or is not)
rewritten."""
+
+ def test_transpiled_arrow_udf_leaves_no_python_eval_operator(self):
+ with self.sql_conf(_TRANSPILE_ON):
+ pudf = _arrow_udf(add_one, LongType())
+ self._assert_transpiled(pudf, "an Arrow-optimized UDF")
+ df = self.spark.range(3).select(pudf("id").alias("v"))
+ self.assertEqual(Counter(), _eval_python_nodes(df))
+ self.assertEqual([1, 2, 3], [r[0] for r in df.collect()])
+
+ def test_untranspilable_arrow_udf_keeps_arrow_eval_python(self):
+ # Must stay interpreted, and stay on the Arrow operator rather than
degrading to
+ # the pickled one.
+ with self.sql_conf(_TRANSPILE_ON):
+ pudf = _arrow_udf(floor_halve, LongType())
+ self.assertEqual([], pudf.transpiled)
+ counts = _eval_python_nodes(self.spark.range(4).select(pudf("id")))
+ self.assertEqual(1, counts["ArrowEvalPythonExec"])
+ self.assertEqual(0, counts["BatchEvalPythonExec"])
+
+ def test_untranspilable_pickled_udf_keeps_batch_eval_python(self):
+ with self.sql_conf(_TRANSPILE_ON):
+ pudf = _pickled_udf(floor_halve, LongType())
+ self.assertEqual([], pudf.transpiled)
+ counts = _eval_python_nodes(self.spark.range(4).select(pudf("id")))
+ self.assertEqual(1, counts["BatchEvalPythonExec"])
+ self.assertEqual(0, counts["ArrowEvalPythonExec"])
+
+ def test_transpiled_arrow_udf_in_filter_has_no_python_eval(self):
+ with self.sql_conf(_TRANSPILE_ON):
+ pudf = _arrow_udf(gt_one, BooleanType())
+ self._assert_transpiled(pudf, "a boolean Arrow-optimized UDF")
+ df = self.spark.range(4).filter(pudf("id"))
+ self.assertEqual(Counter(), _eval_python_nodes(df))
+ self.assertEqual([2, 3], [r[0] for r in df.collect()])
+
+ def test_middle_of_arrow_udf_chain_is_not_elided(self):
+ # ConvertToCatalyst keeps a transpilable UDF whose inputs are all
Python UDFs,
+ # because UDF -> UDF -> UDF pipelines into one Arrow batch.
+ #
+ # Asserted on the PythonUDF expression count, not the operator count:
the chain is
+ # evaluated as a pipeline inside a single ArrowEvalPythonExec, so the
operator count
+ # is 1 whether or not the middle call was lowered. Three PythonUDF
expressions means
Review Comment:
Fixed in 1d0803209: the chain test comment now describes the two-operator,
two-expression plan (checked: `outer(cast(inner(id) + 1))` gives 2
ArrowEvalPythonExec and 2 PythonUDF expressions); the module docstring points
at `ArrowBatchedUDFArrowHandler.run` in `eval_handlers/_arrow.py`; and the
pickled-divergence comment attributes the pass to the return-type check
accepting any numeric body, not to a 'numeric' bucket.
---
<sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of
@holdenk.</sub>
<!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk
-->
##########
python/pyspark/sql/tests/arrow/test_arrow_python_udf_transpile_type_canary.py:
##########
@@ -0,0 +1,651 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""
+A canary over every Spark data type, for UDF transpilation.
+
+Two allowlists decide what the transpiler rewrites: a return-type check in
+``python/pyspark/sql/transpile.py`` (numeric / string / boolean / binary), and
an input-type
+category check in ``ResolveTranspiledPythonUDFOptions.scala`` with a ``case _
=> false``
+catch-all. Being allowlists, a data type added tomorrow falls back to
interpreted Python
+automatically -- safe, but silent: nobody is told the new type was never
considered.
+
+So this module enumerates the concrete ``DataType`` subclasses
``pyspark.sql.types`` exports
+and demands an entry for each, making a new type fail
+``test_data_type_inventory_is_complete`` with instructions.
+
+Enumeration is introspective because ``pyspark.sql.types._atomic_types`` is
NOT exhaustive
+(it omits ``TimeType``, ``GeometryType``, ``GeographyType``,
``CalendarIntervalType``), so a
+canary keyed on it would stop covering new types -- the exact failure this
file prevents.
+
+Triaging a new type
+-------------------
+1. Add an instance to ``_SAMPLES`` with the body category whose lowering could
target it.
+2. Run this module; the verdict tests report the observed verdict.
+3. ``NO_TRANSPILE``, ``REJECTED_BY_ARROW`` or ``REJECTED_CHAR_VARCHAR``:
record it and
+ stop.
+4. ``TRANSPILES``: verify parity against the interpreted path on all three
eval types *before*
+ recording. The pickled path NULLs a mismatched return value where Arrow
raises or
+ converts; the golden matrix in ``python/pyspark/sql/tests/coercion/`` is
the authority. If
+ they disagree, tighten the body-vs-return-type check in ``transpile.py``
instead.
+
+The tables were derived by observation. They are expressed for the pickled
eval type, with
+the Arrow expectations derived from them, which pins the property that
matters: Arrow UDFs
+admit exactly the same types as pickled ones, except where Arrow cannot
express the return
+type at all.
+"""
+
+import unittest
+
+from pyspark.errors import PySparkNotImplementedError
+from pyspark.sql import types as T
+from pyspark.sql.pandas.types import to_arrow_type
+from pyspark.sql.tests.arrow.test_arrow_python_udf_transpile import (
+ _TRANSPILE_OFF,
+ _TRANSPILE_ON,
+ ARROW_TRANSPILE_SUPPORTED,
+ ArrowUDFTranspileTestsMixin,
+ _eval_python_nodes,
+)
+from pyspark.sql.udf import UserDefinedFunction
+from pyspark.testing.sqlutils import ReusedSQLTestCase
+from pyspark.testing.utils import (
+ have_pandas,
+ have_pyarrow,
+ pandas_requirement_message,
+ pyarrow_requirement_message,
+)
+from pyspark.util import PythonEvalType, is_remote_only
+
+TRANSPILES = "TRANSPILES"
+NO_TRANSPILE = "NO_TRANSPILE"
+# The return type cannot be expressed as an Arrow type at all, so an
Arrow-optimized UDF
+# declaring it fails in _check_return_type before transpilation is even a
question.
+REJECTED_BY_ARROW = "REJECTED_BY_ARROW"
+# CHAR/VARCHAR are rejected at UDF construction for every eval type
+# (CHAR_VARCHAR_NOT_SUPPORTED_IN_PYTHON): Python has only unconstrained
strings, so there
+# is no return verdict to have.
+REJECTED_CHAR_VARCHAR = "REJECTED_CHAR_VARCHAR"
+# The type cannot appear in a DataFrame schema, so there is no input-side
verdict to have.
+NOT_A_COLUMN_TYPE = "NOT_A_COLUMN_TYPE"
+
+_PICKLED = PythonEvalType.SQL_BATCHED_UDF
+_ARROW = PythonEvalType.SQL_ARROW_BATCHED_UDF
+_PANDAS = PythonEvalType.SQL_SCALAR_PANDAS_UDF
+
+# Classes exported from pyspark.sql.types that are not usable column types:
the abstract
+# root, StructField (a field descriptor rather than a type), and the bare
UserDefinedType
+# base (its sqlType() raises NotImplementedError; real UDTs are user-authored
subclasses
+# this module can't enumerate). None of these are in __all__, so
_concrete_data_type_classes
Review Comment:
Fixed in 1d0803209: the `_NOT_COLUMN_TYPES` comment now says DataType and
StructField are exported and must stay excluded (UserDefinedType is not
exported and is named for completeness). The return-type comment sits on
`_EXPECTED_PANDAS_RETURN_VERDICT`, the input-type one on
`_EXPECTED_INPUT_VERDICT`, and `_EXPECTED_PANDAS_INPUT_VERDICT` has its own.
---
<sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of
@holdenk.</sub>
<!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk
-->
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]