spark-test commented on code in PR #59730:
URL: https://github.com/apache/spark/pull/59730#discussion_r4583397552
##########
python/pyspark/sql/transpile.py:
##########
@@ -132,26 +275,211 @@
from pyspark.sql import SparkSession
from pyspark.sql._typing import DataTypeOrString
-# Categories that represent numeric (non-string) scalar types.
-_NUMERIC_CATS = frozenset(("numeric", "integer", "float"))
+# Input-type categories. "numeric" spans every numeric column type that has a
+# faithful Python counterpart -- Byte/Short/Integer/Long/DoubleType, so neither
+# DecimalType nor FloatType (see the module docstring); "integral" and
+# "fractional" narrow it for the lowerings that are only exact on one kind of
+# number, and "integral32" narrows "integral" further to the widths whose
values
+# are all exactly representable as a double. The JVM side of this vocabulary
+# lives in ResolveTranspiledPythonUDFOptions.
+_INTEGRAL_CATEGORIES = frozenset({"integral", "integral32"})
+_NUMERIC_CATEGORIES = frozenset({"numeric", "fractional"}) |
_INTEGRAL_CATEGORIES
+# Categories a lowering may tighten (see ``CatalystTranspiler._narrow``), in
+# increasing narrowness, so a later entry matches strictly fewer column types
than
+# an earlier one. Requirements from different lowerings in one option are
+# conjunctive -- every one of them has to hold for the option to be exact -- so
+# when two apply to the same parameter the narrowest wins.
+#
+# Only the numeric categories spanning more than one kind of number are in
here:
+# narrowing "fractional" to an integral category would change the assumption
rather
+# than tighten it, and the non-numeric categories have nothing to narrow to.
+_NARROWING_ORDER = ("numeric", "integral", "integral32")
+_NARROWABLE_CATEGORIES = frozenset(_NARROWING_ORDER)
+# Python builtins the transpiler can lower. Only reached after the name is
proven
+# to still refer to the builtin (see ``_resolvable_builtins``).
+_SUPPORTED_BUILTINS = frozenset({"abs", "min", "max", "round"})
+# `x ** k` expands to k-1 multiplications, so cap k to keep plans small.
Raising
+# the cap buys little: past it, all but the smallest bases overflow LongType.
+_MAX_POW_EXPANSION = 8
+# An int literal past this is conservatively treated as too wide for
IntegerType,
+# so Spark would promote the expression to LongType and the int32 exactness
+# argument for `/` stops holding. (-2**31 does fit; we don't bother.)
+_INT32_MAX = 2**31 - 1
+# Shifts widen their operand to a long, so this is the count at which Python
has
+# shifted every bit out -- and the point at which Spark's masked shift stops
+# agreeing with it.
+_LONG_BITS = 64
+
+
+def _promoting_if_numeric(
+ op: str, categories: List[Optional[str]], plain: Callable[[], Column],
*cols: Column
+) -> Column:
+ """``_promoting(op, ...)`` when every operand is a number, else
``plain()``.
+
+ The gate is on *numeric* rather than *integral* deliberately, and getting
that wrong is worth
+ a note. An unannotated parameter's category is plain ``"numeric"`` -- it
could be an int
+ column or a double one, and only the JVM finds out which. Gating on
``_INTEGRAL_CATEGORIES``
+ therefore refuses promotion for exactly the common case, `udf(lambda x, y:
x + y)` over two
+ int columns, which is the shape this whole exercise is about. It has to be
the coarse
+ category here and the concrete type over there.
+
+ Nothing is lost by handing a double to the promoting operator:
``PythonNumericPromotion``
+ declines to widen a fractional type (IEEE arithmetic saturates to
infinity, which is what
+ Python does too), and aligns the operands so the replacement still
resolves.
+ """
+ if all(_is_numeric_cat(c) for c in categories):
+ return _promoting(op, *cols)
+ return plain()
+
+
+def _promoting(op: str, *cols: Column) -> Column:
+ """Emit the operand-widening version of ``op``.
+
+ Python integers have no width, so `x * 100` on a tinyint column is fine
there and
+ ARITHMETIC_OVERFLOW here -- `Multiply` keeps its operands' type. The JVM
side widens the
+ operands far enough that the worst case the *column types* allow cannot
overflow; see
+ ``PythonNumericPromotion``. It has to happen over there rather than in
this file, because
+ only the analyzer knows the concrete column widths -- we only ever see a
category, and
+ "integral" spans tinyint through bigint.
+
+ Reached through ``InternalFunction`` rather than ``call_function``: these
are registered as
+ internal expressions, so they are invisible to ``SHOW FUNCTIONS`` and to
SQL. That is the
+ right side of the line -- for a SQL user `a + b` overflowing is the
documented ANSI contract,
+ and a public registration would additionally owe an
``@ExpressionDescription`` and a row in
+ ``sql-expression-schema.md``, for a function nobody should call by name.
+ """
+ return
InternalFunction._invoke_internal_function_over_columns(f"python_promoting_{op}",
*cols)
-def _is_numeric_cat(cat: str) -> bool:
- """True for any numeric sub-category (``"numeric"``, ``"integer"``,
``"float"``)."""
- return cat in _NUMERIC_CATS
+def _raise_on_null_operand(op_repr: str, result: Column, *cols: Column) ->
Column:
+ """``result``, but raising where CPython gets a ``None`` operand.
+ Spark's arithmetic propagates NULL (``x + 1`` on NULL is NULL) where Python
+ raises ``TypeError`` (``None + 1``), and a row that should have failed
+ coming back silently missing is worse than any wrong answer, so every
+ lowered operator guards the way the comparisons and ``min`` / ``max`` do:
+ NULL in, ``raise_error`` out. A caller that already proved non-null (``if x
+ is not None: return x + 1``) takes the otherwise branch and never trips it.
+ """
+ err = lit(
+ f"Python UDF transpiler: cannot apply `{op_repr}` to NULL; "
+ "Python would raise TypeError here. Add an `is not None` guard or "
+ "filter NULLs upstream."
+ )
+ any_null = cols[0].isNull()
+ for c in cols[1:]:
+ any_null = any_null | c.isNull()
+ return when(any_null, raise_error(err)).otherwise(result)
Review Comment:
**Non-blocking (P2):** This guard is emitted even when every operand is
already proven non-NULL: a non-None literal, or a parameter narrowed by an
enclosing `is not None` test, which `_is_nonnull_node` (1121-1137) recognizes
and which `_lower_value_compare` and `len` use to skip their own guard. Here
the `raise_error` can never fire, but it still makes the expression throwable
(misc.scala:87, Expression.scala:169), and PushPredicateThroughJoin only moves
deterministic, non-throwable conditions (Optimizer.scala:3212-3214).
So `f = udf(lambda x: x * 2 if x is not None else None, LongType())`, the
shape the transpiler's own NULL error message recommends, used in
`orders.join(customers, 'cid').filter(f(orders.amount) > 1000)` no longer gets
its filter pushed onto the orders scan. The base branch lowered `CASE WHEN
isnotnull(amount) THEN amount * 2 END`, which was pushed; the head nests `CASE
WHEN isnull(amount) THEN raise_error(...)` inside that branch, and no rule
folds it for a nullable column. The join then shuffles or hashes every orders
row instead of the filtered ones, and that side stops qualifying as a
runtime-filter source. Results are unchanged.
**Recommended change:** Guard each operand once, and only where it can be
NULL. Replace the CASE WHEN that `_raise_on_null_operand` builds around a
finished lowering, and the open-coded concatenation guard, with a guard applied
to the operands before the lowering is built: an operand that
`_is_nonnull_node` proves non-NULL is passed through as is, and any other
operand is passed as `coalesce(operand, raise_error(...))` with the same
message. Where a lowering does not read an operand on every row -- `x ** 0`, or
the string repeat's empty-string branch -- keep a single null test on that
operand in a position every row evaluates. Update the helper's docstring and
the module docstring's evaluation-count entry to match, and add transpiler unit
tests for option size, native placement and pushdown.
**Why this works:** A coalesced operand is read once, so every operand
occurrence in the body appears once in the converted option and the option
grows linearly with the body; ConvertToCatalyst sees one read of a parameter
the body uses once and owes it no evaluation; and a body whose operands are all
literals or `is not None`-narrowed parameters contains no raise_error, so it is
not throwable and its filters move below joins again. A NULL operand still
raises the same 'cannot apply ... to NULL' error when that operand is
evaluated, and because the guard sits on the operands rather than on the
result, min and max, whose results can be non-NULL for a NULL operand, need no
special case.
**Scope:** Rework the transpiler's shared NULL guard so it reads each
operand once and only where a NULL can occur, with coverage for option size,
native placement and pushdown.
**Risks:** Every transpiled option changes shape, so plans and EXPLAIN
output that showed the old CASE WHEN change while results and the raised error
stay the same; options are rebuilt each time a UDF is applied and nothing
persists their shape, so the change can be rolled back by restoring the old
helper.
**Constraints:** A NULL operand must still raise the transpiler's error for
every lowered operator, in either operand position. No branch of a lowering may
skip evaluating a guarded operand, so a short-circuit such as the empty-string
repeat cannot swallow the raise.
**Exclusions:**
- The comparison and len lowerings keep their own NULL handling, which is
separate from this guard and already skips operands proven non-NULL.
- A compound operand, such as the product in `x * 2 + 1` under an `is not
None` test, keeps one coalesce even when its own operands are proven non-NULL;
the option stays linear, but such a body remains throwable.
- The repeated operand references inside the `%`, `//` and shift lowerings
stay until the decision on implementing those operators as internal expressions
is made.
**Success:** A left-nested chain of n guarded operators, such as a 20-term
sum or a 10-field string concatenation, produces an option whose size grows
linearly in n. A transpiled `x + 1` applied to a compound argument inside an
aggregate or a join condition runs with no Python UDF in the executed plan. A
filter on `x * 2 if x is not None else None` above a join is pushed below the
join, and the optimized plan contains no raise_error. Every lowered operator
still raises the transpiler's NULL error for a NULL operand, and results for
non-NULL inputs are unchanged.
**Verification:**
- **Regression:** A 20-term sum over untyped parameters and a 10-field
string concatenation produce options whose expression size grows linearly with
the body, analyze promptly, and return CPython's results natively.
- **Regression:** A transpiled `x + 1` applied to a compound argument inside
a groupBy aggregate and inside a join condition runs with no Python UDF in the
executed plan and returns CPython's results.
- **Regression:** A filter on `x * 2 if x is not None else None` above a
join is pushed below the join, and the optimized plan contains no raise_error.
- **Behavior:** Every arithmetic, bitwise, shift, power (including `x **
0`), abs, min, max, round, string repeat (including an empty string with a NULL
count) and concatenation lowering raises the transpiler's NULL error for a NULL
operand in either position.
##########
.github/workflows/build_and_test.yml:
##########
@@ -627,6 +629,7 @@ jobs:
pyspark-pandas-slow-connect
exclude:
- modules: ${{ fromJson(needs.precondition.outputs.required).pyspark
!= 'true' && 'pyspark-sql, pyspark-resource, pyspark-testing, pyspark-core,
pyspark-errors, pyspark-logger' }}
+ - modules: ${{ fromJson(needs.precondition.outputs.required).pyspark
!= 'true' && 'pyspark-sql-slow' }}
Review Comment:
**Nit (P3):** This exclude only checks the PySpark flag, but the module's
only goal, test_udf_transpile_hypothesis (modules.py:909-916), skips its
differential class unless RUN_HYPOTHESIS is set, and on fork builds
RUN_HYPOTHESIS is the precondition's `transpile` flag (line 655). So a fork PR
that changes only python/pyspark/sql/functions/builtin.py still schedules this
job, which sets up the container, fetches the precompiled build and runs just
the three UDFTranspileHypothesisGatingTests smoke tests. Also excluding the
entry when `transpile` is not `'true'` loses no coverage, since apache/spark's
scheduled builds set it to true (build_main.yml:60).
**Verification:**
- **Inspection:** For a PySpark change without a transpile path the expanded
matrix has no pyspark-sql-slow combination, and for a transpile change, or a
sampled apache/spark build, it has one with the 3600-second test timeout and 20
examples.
##########
python/pyspark/sql/transpile.py:
##########
@@ -132,26 +275,211 @@
from pyspark.sql import SparkSession
from pyspark.sql._typing import DataTypeOrString
-# Categories that represent numeric (non-string) scalar types.
-_NUMERIC_CATS = frozenset(("numeric", "integer", "float"))
+# Input-type categories. "numeric" spans every numeric column type that has a
+# faithful Python counterpart -- Byte/Short/Integer/Long/DoubleType, so neither
+# DecimalType nor FloatType (see the module docstring); "integral" and
+# "fractional" narrow it for the lowerings that are only exact on one kind of
+# number, and "integral32" narrows "integral" further to the widths whose
values
+# are all exactly representable as a double. The JVM side of this vocabulary
+# lives in ResolveTranspiledPythonUDFOptions.
+_INTEGRAL_CATEGORIES = frozenset({"integral", "integral32"})
+_NUMERIC_CATEGORIES = frozenset({"numeric", "fractional"}) |
_INTEGRAL_CATEGORIES
+# Categories a lowering may tighten (see ``CatalystTranspiler._narrow``), in
+# increasing narrowness, so a later entry matches strictly fewer column types
than
+# an earlier one. Requirements from different lowerings in one option are
+# conjunctive -- every one of them has to hold for the option to be exact -- so
+# when two apply to the same parameter the narrowest wins.
+#
+# Only the numeric categories spanning more than one kind of number are in
here:
+# narrowing "fractional" to an integral category would change the assumption
rather
+# than tighten it, and the non-numeric categories have nothing to narrow to.
+_NARROWING_ORDER = ("numeric", "integral", "integral32")
+_NARROWABLE_CATEGORIES = frozenset(_NARROWING_ORDER)
+# Python builtins the transpiler can lower. Only reached after the name is
proven
+# to still refer to the builtin (see ``_resolvable_builtins``).
+_SUPPORTED_BUILTINS = frozenset({"abs", "min", "max", "round"})
+# `x ** k` expands to k-1 multiplications, so cap k to keep plans small.
Raising
+# the cap buys little: past it, all but the smallest bases overflow LongType.
+_MAX_POW_EXPANSION = 8
+# An int literal past this is conservatively treated as too wide for
IntegerType,
+# so Spark would promote the expression to LongType and the int32 exactness
+# argument for `/` stops holding. (-2**31 does fit; we don't bother.)
+_INT32_MAX = 2**31 - 1
+# Shifts widen their operand to a long, so this is the count at which Python
has
+# shifted every bit out -- and the point at which Spark's masked shift stops
+# agreeing with it.
+_LONG_BITS = 64
+
+
+def _promoting_if_numeric(
+ op: str, categories: List[Optional[str]], plain: Callable[[], Column],
*cols: Column
+) -> Column:
+ """``_promoting(op, ...)`` when every operand is a number, else
``plain()``.
+
+ The gate is on *numeric* rather than *integral* deliberately, and getting
that wrong is worth
+ a note. An unannotated parameter's category is plain ``"numeric"`` -- it
could be an int
+ column or a double one, and only the JVM finds out which. Gating on
``_INTEGRAL_CATEGORIES``
+ therefore refuses promotion for exactly the common case, `udf(lambda x, y:
x + y)` over two
+ int columns, which is the shape this whole exercise is about. It has to be
the coarse
+ category here and the concrete type over there.
+
+ Nothing is lost by handing a double to the promoting operator:
``PythonNumericPromotion``
+ declines to widen a fractional type (IEEE arithmetic saturates to
infinity, which is what
+ Python does too), and aligns the operands so the replacement still
resolves.
+ """
+ if all(_is_numeric_cat(c) for c in categories):
+ return _promoting(op, *cols)
+ return plain()
+
+
+def _promoting(op: str, *cols: Column) -> Column:
+ """Emit the operand-widening version of ``op``.
+
+ Python integers have no width, so `x * 100` on a tinyint column is fine
there and
+ ARITHMETIC_OVERFLOW here -- `Multiply` keeps its operands' type. The JVM
side widens the
+ operands far enough that the worst case the *column types* allow cannot
overflow; see
+ ``PythonNumericPromotion``. It has to happen over there rather than in
this file, because
+ only the analyzer knows the concrete column widths -- we only ever see a
category, and
+ "integral" spans tinyint through bigint.
+
+ Reached through ``InternalFunction`` rather than ``call_function``: these
are registered as
+ internal expressions, so they are invisible to ``SHOW FUNCTIONS`` and to
SQL. That is the
+ right side of the line -- for a SQL user `a + b` overflowing is the
documented ANSI contract,
+ and a public registration would additionally owe an
``@ExpressionDescription`` and a row in
+ ``sql-expression-schema.md``, for a function nobody should call by name.
+ """
+ return
InternalFunction._invoke_internal_function_over_columns(f"python_promoting_{op}",
*cols)
-def _is_numeric_cat(cat: str) -> bool:
- """True for any numeric sub-category (``"numeric"``, ``"integer"``,
``"float"``)."""
- return cat in _NUMERIC_CATS
+def _raise_on_null_operand(op_repr: str, result: Column, *cols: Column) ->
Column:
+ """``result``, but raising where CPython gets a ``None`` operand.
+ Spark's arithmetic propagates NULL (``x + 1`` on NULL is NULL) where Python
+ raises ``TypeError`` (``None + 1``), and a row that should have failed
+ coming back silently missing is worse than any wrong answer, so every
+ lowered operator guards the way the comparisons and ``min`` / ``max`` do:
+ NULL in, ``raise_error`` out. A caller that already proved non-null (``if x
+ is not None: return x + 1``) takes the otherwise branch and never trips it.
+ """
+ err = lit(
+ f"Python UDF transpiler: cannot apply `{op_repr}` to NULL; "
+ "Python would raise TypeError here. Add an `is not None` guard or "
+ "filter NULLs upstream."
+ )
+ any_null = cols[0].isNull()
+ for c in cols[1:]:
+ any_null = any_null | c.isNull()
+ return when(any_null, raise_error(err)).otherwise(result)
-def _wider_numeric(lc: str, rc: str) -> str:
- """Return the wider of two numeric categories (numeric > float >
integer)."""
- if not (_is_numeric_cat(lc) and _is_numeric_cat(rc)):
- raise UnsupportedOperationException(
- f"_wider_numeric called with non-numeric categories: {lc!r},
{rc!r}"
- )
- if "numeric" in (lc, rc):
+
+def _is_numeric_cat(category: Optional[str]) -> bool:
+ """True for every category that denotes a number column."""
+ return category in _NUMERIC_CATEGORIES
+
+
+def _coarse_category(category: Optional[str]) -> Optional[str]:
+ """Collapse the numeric refinements back to plain ``"numeric"``.
+
+ Comparability doesn't care which kind of number it is -- Python is happy
+ with ``1 < 1.5`` and ``2 == 2.0`` -- so the comparison lowerings gate on
+ this instead of the refined category, which would refuse mixed int/float
+ comparisons that used to transpile.
+ """
+ return "numeric" if _is_numeric_cat(category) else category
+
+
+def _unify_numeric(left: str, right: str) -> Optional[str]:
+ """Merge two numeric categories the way Python promotes, or ``None`` when
+ either side isn't a number.
+
+ ``int op float`` is a float so "fractional" wins, and an unrefined
+ "numeric" operand keeps the result unrefined.
+ """
+ if not (_is_numeric_cat(left) and _is_numeric_cat(right)):
+ return None
+ if "fractional" in (left, right):
+ return "fractional"
+ if "numeric" in (left, right):
return "numeric"
- if "float" in (lc, rc):
- return "float"
- return "integer"
+ return "integral"
+
+
+def _int_constant(node: ast.AST) -> Optional[int]:
+ """The value of an integer literal, or ``None`` for anything else.
+
+ Handles the unary forms too, since ``x ** -1`` parses as ``Pow`` over
+ ``UnaryOp(USub, Constant(1))`` rather than a negative constant. ``bool`` is
+ excluded even though it subclasses ``int``: ``x ** True`` is legal Python
+ with no faithful lowering.
+ """
+ match node:
+ case ast.Constant(value=v) if isinstance(v, int) and not isinstance(v,
bool):
+ return v
+ case ast.UnaryOp(op=ast.USub(), operand=operand):
+ inner = _int_constant(operand)
+ return None if inner is None else -inner
+ case ast.UnaryOp(op=ast.UAdd(), operand=operand):
+ return _int_constant(operand)
+ case _:
+ return None
+
+
+def _is_negative_int_constant(node: ast.AST) -> bool:
+ value = _int_constant(node)
+ return value is not None and value < 0
+
+
+def _resolvable_builtins(func: Optional[Callable], params: List[str]) ->
Set[str]:
+ """The ``_SUPPORTED_BUILTINS`` that ``func`` still resolves to the builtin.
+
+ ``abs`` / ``min`` / ``max`` / ``round`` are ordinary names a UDF can rebind
+ (``from mymath import round``, a closure variable, a parameter, a module
+ global). Lowering builtin semantics for a rebound name would run different
+ code than the UDF does, so we drop those and refuse the call. No ``func``
+ means no lowered calls, which is just a missed optimization.
+ """
+ if func is None:
+ return set()
+ shadowed = set(params)
+ # Resolve the callable Python actually dispatches, matching
`_transpile_func`:
+ # `getattr(func, "__call__")` finds an instance attribute when one exists,
+ # but Python ignores it and calls the type's `__call__` instead. Reading
the
+ # wrong code object here would miss a free variable and lower a shadowed
+ # builtin (e.g. `round`) as the builtin -- a silent wrong result.
+ if inspect.isfunction(func) or inspect.ismethod(func):
+ target: Any = func
+ else:
+ target = _call_impl(_call_dunder(func))
+ code = getattr(target, "__code__", None)
+ if code is not None:
+ # Closures and locals: a name bound anywhere in the function shadows
the
+ # builtin for the whole body, regardless of statement order.
+ shadowed.update(code.co_freevars)
+ shadowed.update(code.co_varnames)
+ globals_dict = getattr(target, "__globals__", None) or {}
Review Comment:
**Blocking (P1):** These `__globals__` are read when `udf(...)` runs,
because `UserDefinedFunction.__init__` transpiles right away (udf.py:297-311).
The interpreted function is pickled only at first use, in `_create_judf`
(udf.py:529-547), and cloudpickle captures the globals it references at that
moment (cloudpickle.py:727-728). A name bound in between is invisible to this
check but is what the UDF calls.
Tracing a notebook: cell 1 defines `clip = udf(lambda x: max(x, 0),
LongType())`, which passes the check and lowers to `greatest(x, 0)`; cell 2
runs `from pyspark.sql.functions import *`, binding `max` in `__main__`; cell 3
runs `df.select(clip('a'))`. The interpreted UDF, pickled at cell 3, would call
`pyspark.sql.functions.max(x, 0)` and raise TypeError, while the transpiled
query returns `greatest(x, 0)`. With `max = lambda a, b: a * 100` instead, the
UDF returns -500 for -5 and the option returns 0. The base branch lowered none
of these builtins, so this is new.
Rerunning `_resolvable_builtins` in `_create_judf`, where the function is
pickled, and building the JVM function with `include_transpiled=False` when a
lowered name no longer resolves to the builtin, would check exactly the globals
the interpreted UDF carries; the cached JVM function then keeps that decision.
**Verification:**
- **Regression:** Defining a transpilable UDF that calls round or max,
rebinding that name in the defining module's globals, and then applying the UDF
gives the interpreted UDF's result, with a Python UDF in the executed plan.
- **Behavior:** Without a rebinding, the same UDF still runs natively.
##########
python/pyspark/sql/transpile.py:
##########
@@ -891,56 +1783,219 @@ def _convert_chunk(self, params: List[str], body:
ast.AST | None) -> Column:
# (str+int, str-str, ...) raise so this variant is dropped and
# the JVM picks another option or falls back to the Python UDF.
#
- # `**` is intentionally NOT lowered: Spark's `pow` is DOUBLE
and
- # loses precision for large integers, so it would silently
return
- # wrong results. TODO (SPARK-55210): add an exact integer-power
- # lowering and re-enable it.
- #
- # Value-level divergences remain documented (need runtime value
- # info, not type): overflow raises ARITHMETIC_OVERFLOW under
ANSI
- # where Python promotes to a big int; arithmetic is not
- # NULL-guarded (`x + 1` on NULL -> NULL vs Python TypeError).
- # TODO (SPARK-55210): map overflow / divide-by-zero precisely.
+ # `//`, `**` and the bitwise operators also need *integral*
+ # operands; `/` needs a fractional or int32-exact one. The
module
+ # docstring has the reasoning and the resulting fall-backs;
+ # SPARK-55220 tracks the strictness knob for the value-level
ones.
lc = self._category(params, left)
rc = self._category(params, right)
+ both_numeric = _unify_numeric(lc, rc) is not None
+ both_integral = lc in _INTEGRAL_CATEGORIES and rc in
_INTEGRAL_CATEGORIES
left_col = self._convert_chunk(params, left)
right_col = self._convert_chunk(params, right)
match op:
case ast.Add():
if lc == rc == "string":
- return concat(left_col, right_col)
- if _is_numeric_cat(lc) and _is_numeric_cat(rc):
- return left_col.__add__(right_col)
+ # `concat` propagates NULL where Python raises
+ # TypeError on `'a' + None`, so guard rather than
+ # return a value Python never would -- the same
+ # guard every numeric lowering carries.
+ concat_null = lit(
+ "Python UDF transpiler: cannot concatenate
NULL; "
+ "Python would raise TypeError here. Add an `is
not "
+ "None` guard or filter NULLs upstream."
+ )
+ return when(
+ left_col.isNull() | right_col.isNull(),
+ raise_error(concat_null),
+ ).otherwise(concat(left_col, right_col))
+ if both_numeric:
+ return _raise_on_null_operand(
+ "+",
+ _promoting_if_numeric(
+ "add",
+ [lc, rc],
+ lambda: left_col.__add__(right_col),
+ left_col,
+ right_col,
+ ),
+ left_col,
+ right_col,
+ )
case ast.Sub():
- if _is_numeric_cat(lc) and _is_numeric_cat(rc):
- return left_col.__sub__(right_col)
+ if both_numeric:
+ return _raise_on_null_operand(
+ "-",
+ _promoting_if_numeric(
+ "subtract",
+ [lc, rc],
+ lambda: left_col.__sub__(right_col),
+ left_col,
+ right_col,
+ ),
+ left_col,
+ right_col,
+ )
case ast.Mult():
- if _is_numeric_cat(lc) and _is_numeric_cat(rc):
- return left_col.__mul__(right_col)
- if lc == "string" and rc in ("integer", "numeric"):
- return repeat(left_col, right_col.cast("int"))
- if lc in ("integer", "numeric") and rc == "string":
- return repeat(right_col, left_col.cast("int"))
+ if both_numeric:
+ return _raise_on_null_operand(
+ "*",
+ _promoting_if_numeric(
+ "multiply",
+ [lc, rc],
+ lambda: left_col.__mul__(right_col),
+ left_col,
+ right_col,
+ ),
+ left_col,
+ right_col,
+ )
+ # The repeat count has to be an int -- `"ab" * 2.5` is
a
+ # TypeError, not a truncation. A float literal shows
up as
+ # "fractional" here; for a parameter only the JVM
knows, so
+ # narrow the count and let a double column drop the
option.
+ # Clamp negative counts before narrowing to int,
preserving NULL.
+ if lc == "string" and _is_numeric_cat(rc) and rc !=
"fractional":
+ self._narrow(params, "integral", right)
+ count = when(right_col < lit(0),
lit(0)).otherwise(right_col)
+ return _raise_on_null_operand(
+ "*",
+ when(left_col == lit(""), lit("")).otherwise(
+ repeat(left_col, count.cast("int"))
+ ),
+ left_col,
+ right_col,
+ )
+ if _is_numeric_cat(lc) and lc != "fractional" and rc
== "string":
+ self._narrow(params, "integral", left)
+ count = when(left_col < lit(0),
lit(0)).otherwise(left_col)
+ return _raise_on_null_operand(
+ "*",
+ when(right_col == lit(""), lit("")).otherwise(
+ repeat(right_col, count.cast("int"))
+ ),
+ left_col,
+ right_col,
+ )
case ast.Mod():
- if _is_numeric_cat(lc) and _is_numeric_cat(rc):
- # Python's `%` takes the sign of the divisor;
Spark's
- # takes the dividend's. `sign(b) * pmod(sign(b) *
a,
- # abs(b))` reproduces Python for every non-zero
divisor
- # except at the LongType overflow boundaries -- `a
=
- # Long.MinValue` with `b < 0` (the `sign(b) * a`
negate
- # overflows) and `b = Long.MinValue` (the `abs(b)`
- # overflows) -- where this raises
ARITHMETIC_OVERFLOW
- # under ANSI while Python returns a value. That
matches
- # the documented overflow caveat for `+`/`-`/`*`
above.
- # Use a CASE-based integer sign rather than sign()
to
- # avoid promoting operands to DoubleType, which
loses
- # precision near LongType boundaries.
- sb = (
- when(right_col > 0, lit(1))
- .when(right_col < 0, lit(-1))
- .otherwise(lit(0))
+ if both_numeric:
+ return self._python_mod(left_col, right_col)
+ case ast.Div():
+ # `/` is always float division in Python, and ANSI's
+ # DIVIDE_BY_ZERO lines up with ZeroDivisionError. A
+ # fractional operand makes it exact, since Python
converts
+ # the other side to double just as we do -- but both
sides
+ # still have to be numbers, or ANSI string promotion
would
+ # compute `10.0 / '2'` where Python raises. Two
integers
+ # only match while every value stays in IntegerType:
past
+ # 2^53 Spark rounds on the cast to double before
dividing,
+ # where Python divides the exact integers. Narrow to
int32
+ # so a bigint column drops the option rather than
using it.
+ if both_numeric and (lc == "fractional" or rc ==
"fractional"):
+ return _raise_on_null_operand(
+ "/", left_col.__div__(right_col), left_col,
right_col
+ )
+ if both_numeric:
+ int32_params: Set[int] = set()
+ if not (
+ self._int32_exact(params, left, int32_params)
+ and self._int32_exact(params, right,
int32_params)
+ ):
+ raise UnsupportedOperationException(
+ "`/` on integers is only lowered when both
"
+ "operands provably stay within
IntegerType; a "
+ "bigint operand above 2^53 would round
before "
+ "dividing and diverge from Python, so the
UDF "
+ "falls back to interpreted Python"
+ )
+ self._narrow_indexes(int32_params, "integral32")
+ return _raise_on_null_operand(
+ "/", left_col.__div__(right_col), left_col,
right_col
+ )
+ case ast.FloorDiv():
+ # Python floors toward -inf where `div` truncates
toward
+ # zero, so subtract one when the remainder is non-zero
and
+ # its sign differs from the divisor's -- the cases
where
+ # truncation went the wrong way. `%` is Spark's
Remainder
+ # (dividend's sign), which is what makes that test
work.
+ #
+ # `div` returns LongType and rejects fractional input,
so
+ # integral only: a float `//` would need `floor(a /
b)`,
+ # which can land on the far side of an integer when `a
/ b`
+ # rounds up. Divide-by-zero raises, as it does in
Python.
+ if both_integral:
+ quotient = call_function("div", left_col,
right_col)
Review Comment:
**Blocking (P1):** `div` and `%` here are resolved by ResolveFunctions
during analysis, and IntegralDivide, Remainder, Divide, Abs and the promoting
expressions take their eval mode from the session conf at that point. ANSI is
checked only when the UDF is defined (udf.py:286-296) and when
ConvertToCatalyst optimizes the plan (Optimizer.scala:1339-1351);
ResolveTranspiledPythonUDFOptions types and keeps the options without looking
at it.
Tracing the code: with `f = udf(lambda a, b: a // b, LongType())` defined
under ANSI, a DataFrame built while `spark.sql.ansi.enabled` is off (classic
DataFrames are analyzed when `select` runs) and collected after ANSI is turned
back on gets the transpiled option. LEGACY `div` and `%` return NULL for a zero
divisor, the floor correction keeps that NULL, and the NULL guard only tests
the operands, so the row comes back NULL where the interpreted UDF raises
ZeroDivisionError. `x ** 3` and `abs(x)` on a bigint wrap instead of raising in
the same sequence. The base branch's `+`, `-`, `*` and `%` lowerings already
had this gap; the new `/`, `//`, `**`, abs and round lowerings bring bodies
that used to run as Python into it.
Clearing a call's options in `pruneByCategoryAndTypeParameters`, which both
analyzer rules share, when ANSI is off at analysis would keep the Python UDF
for such a call however the conf changes afterward.
**Verification:**
- **Regression:** A DataFrame that applies a transpiled floor division,
power or abs, analyzed with ANSI off and executed with ANSI on, runs the Python
UDF and matches CPython, including raising for a zero divisor.
- **Behavior:** A transpiled call analyzed with ANSI off carries no options,
and one analyzed with ANSI on is pruned as before.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/pythonNumericPromotion.scala:
##########
@@ -0,0 +1,410 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.catalyst.expressions
+
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{ByteType, DataType, DoubleType, FloatType,
IntegerType, LongType, ShortType}
+
+/**
+ * Widening rules that give transpiled Python UDF arithmetic Python's overflow
behaviour.
+ *
+ * A Python `int` has no width -- it is a digit array that grows per value, so
`x * 100` on a
+ * tinyint column returns 12700 and thinks nothing of it. Catalyst picks one
type per column
+ * before it sees any data, and `Multiply` keeps its operands' type, so the
same expression
+ * raises ARITHMETIC_OVERFLOW under ANSI. The interpreted Python UDF path does
not have this
+ * problem, because it converts each row's result to the UDF's declared return
type
+ * individually -- input widths never enter into it.
+ *
+ * We cannot reproduce "per value" with a static type, but we do not need to.
Python needs
+ * unbounded integers because a Python int is unbounded; a Spark column is 8,
16, 32 or 64 bits,
+ * and that bound propagates through the expression. So the worst case over
every row the column
+ * could possibly hold is computable from the input types alone, with no data:
+ *
+ * tinyint + tinyint -> 256 -> ShortType
+ * abs(smallint) -> 32768 -> IntegerType
+ * int32 + int32 -> 2**32 -> LongType
+ * int32 * int32 -> 2**62 -> LongType
+ * int64 + int64 -> 2**64 -> nothing fits; left alone (see
narrowestFor)
+ *
+ * Widening the *operands* to that type is what makes the difference; widening
the result does
+ * not, and is what the lowerings did before. `a + b` on two int columns
already reported
+ * LongType, because the transpiler casts to the declared return type at the
end -- but the
+ * addition happened in IntegerType and overflowed long before that cast was
reached.
+ *
+ * Two deliberate limits:
+ *
+ * - `LongType` is the ceiling, so anything whose worst case needs more than
64 bits is left
+ * alone and raises on overflow exactly as it did before this rule existed
-- no worse, and
+ * never a wrong answer. `narrowestFor` explains why decimal is not an
option here. In practice
+ * this means bigint operands: every narrower width promotes cleanly.
+ * - Only integral inputs are promoted. Doubles need nothing: they saturate
to infinity, which
+ * is what Python does too, so there is no overflow to avoid.
+ *
+ * Note what this deliberately does NOT do. Once the result reaches the UDF's
declared return
+ * type, `EvaluatePython.makeFromJava` narrows it with
`.toByte`/`.toShort`/`.toInt` -- two's
+ * complement truncation, so an interpreted UDF declared `-> ByteType` turns
500 into -12 without
+ * a word. Matching the interpreted path there would mean reproducing silent
data corruption, so
+ * the transpiled path keeps raising instead. Promotion is about not failing
on an intermediate
+ * that Python would have carried; it is not licence to invent a wrong answer.
+ */
+object PythonNumericPromotion {
+
+ /** Spark's numeric precedence, for `widestOf`. A val, not a local --
`widestOf` is hot. */
+ private val rank: Seq[DataType] =
+ Seq(ByteType, ShortType, IntegerType, LongType, FloatType, DoubleType)
+
+ /**
+ * The largest magnitude a value of `dt` can have, or None if `dt` is not an
integral type we
+ * promote. Note these are magnitudes, not maxima -- two's complement
reaches one further in
+ * the negative direction, and `abs(Byte.MinValue)` is the case that cares.
+ */
+ private def magnitude(dt: DataType): Option[BigInt] = dt match {
+ case ByteType => Some(BigInt(1) << 7)
+ case ShortType => Some(BigInt(1) << 15)
+ case IntegerType => Some(BigInt(1) << 31)
+ case LongType => Some(BigInt(1) << 63)
+ // Decimal is refused outright rather than half-supported. Ranking it by
precision looked
+ // honest but was worse than declining: a decimal(18,0) pair promoted to
bigint, silently
+ // losing the decimal type, while decimal(19,0) and any non-zero scale
fell through to an
+ // unaligned replacement and INTERNAL_ERROR. Returning None sends every
decimal to `plain`,
+ // which keeps its type. Decimal columns are excluded from transpiled UDF
options;
+ // this fallback also supports internally constructed expressions.
+ case _ => None
+ }
+
+ /**
+ * The narrowest integral type that holds every value up to `m` in
magnitude, or None when
+ * nothing does.
+ *
+ * `LongType` is the ceiling, and that is a limitation of how this is built
rather than of
+ * Spark. `DecimalType(38, 0)` would reach further and would cover a single
bigint multiply
+ * exactly, 2**126 being 38 digits. An earlier version of this comment
claimed a decimal
+ * replacement could not resolve because `DecimalPrecision` coercion is what
caps a product's
+ * precision at 38; that is wrong. `Multiply` caps it itself, in
`resultDecimalType`, and
+ * `Multiply(cast(a, decimal(38,0)), cast(b, decimal(38,0)))` resolves
standalone. What actually
+ * failed was `Add(decimal, int_literal)`, because the hand-rolled alignment
in `widestOf` does
+ * not rank DecimalType -- a gap in this file, not in Catalyst.
+ *
+ * Ranking decimal here would then have to reproduce Spark's decimal type
coercion by hand,
+ * which is the wrong trade. The right shape is to widen in an analyzer rule
instead of inside
+ * the expression: `ResolveTranspiledPythonUDFOptions` already runs in the
Resolution batch
+ * alongside `typeCoercionRules`, so a rewrite there is coerced on the next
fixed-point
+ * iteration and needs none of `plain`, `widestOf`, or a lazily-computed
replacement. Until
+ * then `x * y` on two bigints raises on overflow exactly as it did before
promotion existed.
+ */
+ private def narrowestFor(m: BigInt): Option[DataType] = {
+ if (m <= Byte.MaxValue) Some(ByteType)
+ else if (m <= Short.MaxValue) Some(ShortType)
+ else if (m <= Int.MaxValue) Some(IntegerType)
+ else if (m <= Long.MaxValue) Some(LongType)
+ else None
+ }
+
+ /**
+ * The type to evaluate `worst`-bounded arithmetic in, given the operand
types. Returns None
+ * when nothing needs to change: a non-integral operand, or a worst case too
wide for any
+ * Catalyst type, both of which leave the operator alone.
+ */
+ private def promote(inputs: Seq[DataType], worst: Seq[BigInt] => BigInt):
Option[DataType] = {
+ val magnitudes = inputs.map(magnitude)
+ if (magnitudes.exists(_.isEmpty)) {
+ None
+ } else {
+ // Whatever comes back is always strictly wider than every input, so
there is nothing to
+ // filter out: `narrowestFor(m)` answers T only when m <= T.MaxValue,
which is one below
+ // `magnitude(T)`, and `worst` is at least the widest input's magnitude
for all three
+ // functions below. `PythonNumericPromotionSuite` pins that down.
+ narrowestFor(worst(magnitudes.map(_.get)))
+ }
+ }
+
+ /** Promotion target for `a + b` / `a - b`: the operands' magnitudes can
only add. */
+ def forAddition(left: DataType, right: DataType): Option[DataType] =
+ promote(Seq(left, right), ms => ms(0) + ms(1))
+
+ /** Promotion target for `a * b`: the magnitudes multiply. */
+ def forMultiplication(left: DataType, right: DataType): Option[DataType] =
+ promote(Seq(left, right), ms => ms(0) * ms(1))
+
+ /**
+ * Promotion target for `abs(a)` and unary minus. Both need exactly one more
value than the
+ * type holds, because two's complement has no positive counterpart for the
minimum -- which
+ * is why `abs(x)` on a smallint holding -32768 raises where Python answers
32768.
+ */
+ def forNegation(child: DataType): Option[DataType] = promote(Seq(child), ms
=> ms(0))
+
+ /**
+ * The operator over its operands as given -- what we report before the
children resolve and a
+ * width can be chosen. The one thing it must do is align the operand types:
a replacement never
+ * goes through type coercion (`InheritAnalysisRules` is what normally
arranges that, and we
+ * cannot use it, since building ours needs the children's types), so an
unaligned `Add(bigint,
+ * int)` does not resolve and CheckAnalysis reports INTERNAL_ERROR -- a
broken query rather than
+ * a fallback. `x + 1` on a bigint column is enough to reach it, the literal
being an int.
+ */
+ def plain(
+ left: Expression,
+ right: Expression,
+ context: NumericEvalContext,
+ op: (Expression, Expression) => Expression): Expression = {
+ // Align the operand types ourselves rather than emitting `Add(bigint,
int)` and hoping. A
+ // replacement has to be resolvable *as written*: `InheritAnalysisRules`
is what normally
+ // hands a replacement to type coercion, and we cannot use it (building
ours needs the
+ // children's types, which are not known in the constructor). So an
unaligned replacement
+ // never gets coerced and CheckAnalysis rejects it with INTERNAL_ERROR --
which is a broken
+ // query, not a fallback. `x + 1` on a bigint column is enough to hit it,
since the literal
+ // is an int.
+ //
+ // Widest-of-two is the whole rule here, and it is safe because these
operators are only
+ // emitted for numeric operands (see `_promoting_if_numeric` on the Python
side), and it is
+ // Spark's own numeric precedence, so it agrees with what coercion would
have done. Note the
+ // gate really is *numeric* and not *integral*: an unannotated parameter's
category is plain
+ // "numeric", so an integral-only gate would refuse the commonest body of
all.
+ // Read each operand's type once: `dataType` on a RuntimeReplaceable child
builds its
+ // replacement to answer, so asking twice does the work twice.
+ val (lt, rt) = (left.dataType, right.dataType)
+ widestOf(lt, rt) match {
+ case Some(t) if lt != t || rt != t => op(cast(left, t, context),
cast(right, t, context))
+ case _ => op(left, right)
+ }
+ }
+
+ /**
+ * A widening cast carrying the caller's eval mode rather than reading the
ambient conf.
+ *
+ * Behaviour is the same either way -- every cast we emit widens (tinyint to
smallint and so on),
+ * so there is no value to overflow and nothing for ANSI to raise about.
What it buys is a stable
+ * canonical form: `Cast`'s `evalMode` defaults from `SQLConf.get`, and
because our replacement is
+ * built lazily, two identical nodes forced under different conf would
otherwise disagree and
+ * stop sharing.
+ */
+ private def cast(child: Expression, target: DataType, context:
NumericEvalContext): Expression =
+ Cast(child, target, None, context.evalMode)
+
+ /**
+ * The wider of two numeric types, or None if either is not one we rank.
+ *
+ * This is Spark's own numeric precedence, and it covers the float types as
well as the integral
+ * ones on purpose: `plain` uses it to make a replacement resolvable, and `x
/ 2.0 + 1` needs
+ * aligning just as much as `x + 1` on a bigint does. DecimalType is absent
because a decimal
+ * column never reaches these expressions --
ResolveTranspiledPythonUDFOptions keeps it out of
+ * every numeric category -- and because we never produce one ourselves.
+ */
+ private def widestOf(left: DataType, right: DataType): Option[DataType] = {
+ (rank.indexOf(left), rank.indexOf(right)) match {
+ case (l, r) if l >= 0 && r >= 0 => Some(rank(math.max(l, r)))
+ case _ => None
+ }
+ }
+
+ /**
+ * `op(cast(left, t), cast(right, t))` for the promoted `t`, or `plain` when
nothing needs
+ * widening. Lives here so the "cast both sides, then delegate" step exists
once rather than in
+ * each operator below.
+ */
+ def widened(
+ left: Expression,
+ right: Expression,
+ target: (DataType, DataType) => Option[DataType],
+ context: NumericEvalContext,
+ op: (Expression, Expression) => Expression): Expression = {
+ target(left.dataType, right.dataType) match {
+ case Some(t) => op(cast(left, t, context), cast(right, t, context))
+ // No promotion to apply, but the operands may still disagree, and an
unaligned replacement
+ // does not resolve -- so fall through to `plain`, which aligns them.
+ case None => plain(left, right, context, op)
+ }
+ }
+
+}
+
+/**
+ * Arithmetic that evaluates at a width wide enough for Python's semantics, per
+ * [[PythonNumericPromotion]]. Only meant to be emitted by the Python UDF
transpiler, which
+ * reaches them through InternalFunction. They are registered as internal
expressions,
+ * so neither SQL nor call_function resolves them. Promotion stops at LongType.
+ *
+ * These are [[RuntimeReplaceable]] rather than hand-written arithmetic
because the whole point is
+ * to run the *existing* operator at a wider type -- writing fresh `eval` and
`doGenCode` bodies
+ * would be a second implementation of Add to keep in step with the first.
Because the replacement
+ * depends on the children's types, when it may be cached is subtle -- see
`replacement` below.
+ */
+trait PythonPromotingArithmetic extends RuntimeReplaceable {
Review Comment:
**Blocking (P1):** This trait computes `replacement` from the children's
types but overrides neither `checkInputDataTypes` nor `resolved`, and
RuntimeReplaceable forwards neither, so the node reports resolved as soon as
its children do, even when the replacement cannot resolve. The transpiler can
hand it such operands: `_category` labels a comparison whose operands are
themselves comparisons with the catch-all "numeric" (transpile.py:1562-1566),
so `(x > 0) == (y > 0)` counts as a number and `abs`, `+`, `-`, `*` and unary
minus over it emit python_promoting_* over a boolean.
Tracing `udf(lambda x, y: abs((x > 0) == (y > 0)), LongType())` on two
bigint columns: `forNegation(BooleanType)` is None, so the replacement is `Abs`
over a boolean, which never resolves. The option's boolean-to-bigint cast is
allowed under ANSI, so the option itself resolves, the drop rule keeps it, and
CheckAnalysis fails the query with INTERNAL_ERROR 'Cannot resolve the runtime
replaceable expression ... The replacement is unresolved'. On the base branch
abs was not lowered and this UDF ran as Python, returning 0 or 1. `((x > 0) ==
(y > 0)) + 1`, `* 10` and unary minus reach the same internal error, where the
base branch failed with the DATATYPE_MISMATCH that the drop rule is meant to
turn into a fallback.
Overriding `checkInputDataTypes` here to report the replacement's own
type-check failure once the children are resolved would make such an option
unresolved, so the drop rule removes it and the call falls back; numeric
operands still resolve, because `plain` aligns every pair the promotion rule
declines to widen.
**Verification:**
- **Behavior:** A promoting expression over operand types its replacement
rejects reports unresolved with that replacement's type-check error, while one
over numeric operands still resolves and keeps its widened replacement.
- **Regression:** With transpilation on, bare and aliased calls of UDFs
applying abs, +, * and unary minus to a comparison of comparisons analyze, fall
back to interpreted Python and return CPython's results.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveTranspiledPythonUDFOptions.scala:
##########
@@ -117,3 +177,91 @@ object ResolveTranspiledPythonUDFOptions extends
Rule[LogicalPlan] {
}
}
}
+
+/**
+ * Drops any transpiled option that analysis left unresolved, so the call
falls back to interpreted
+ * Python instead of failing the query.
+ *
+ * An option is a child of [[TranspiledPythonUDF]], so one that is still
unresolved when analysis
+ * finishes reaches `CheckAnalysis`, which reports on an expression the user
never wrote. For the
+ * common shape that is a type-check failure: an option of `cast(binary as
bigint)` is measured as
+ * [[DATATYPE_MISMATCH.CAST_WITHOUT_SUGGESTION]], "cannot cast BINARY to
BIGINT", naming a cast the
+ * transpiler invented. The honest answer is the one a category miss already
gets: run the Python.
+ *
+ * Matching categories does not rule any of this out -- the transpiler picks a
lowering per operator
+ * rather than per exact type, so `cast(binary as bigint)` matches "binary"
and never resolves.
+ *
+ * Separate from [[ResolveTranspiledPythonUDFOptions]], and in a batch after
the Resolution batch,
+ * because inside that batch `!resolved` does not mean unresolvable. Every
option starts unresolved
+ * by design: its `_udf_param_N` references carry no type until
ResolveTranspiledPythonUDFOptions
+ * reads one off each bound argument, and the node staying unresolved is what
brings the analyzer
+ * back to coerce the body. Dropping on `!resolved` from inside the batch
would throw away every
+ * option that reads a parameter and turn transpilation off without saying so.
Once the batch is at
+ * a fixed point, nothing is going to resolve one.
+ *
+ * Dropping an option resolves the UDF, but the Resolution batch has already
converged, so whatever
+ * was waiting on the UDF stays unresolved on its own: the enclosing
`UnresolvedAlias` of
+ * `SELECT udf(a)`, or a parent held by name such as the `r` of `SELECT r + 1
FROM (SELECT udf(a)
+ * AS r ...)`. `CheckAnalysis` would then report the fall-back itself as an
error, so after
+ * dropping, this rule re-runs the resolution rules that finish those parents
off -- and only on
+ * plans it changed, so queries without a dropped option never pay for this.
The re-run is a single
+ * pass of each rule in Resolution-batch order; each walks bottom-up, which
covers the parents of
+ * every dropped UDF at any nesting depth. `resolveAggregateFunctions` comes
along because
+ * `resolveReferences` wraps ORDER BY/HAVING references over an Aggregate in
`TempResolvedColumn`,
+ * and only `ResolveAggregateFunctions` marks the invalid ones `hasTried` for
the later
+ * `RemoveTempResolvedColumn` batch to turn back into an unresolved attribute
-- without it, an
+ * invalid ORDER BY in the same query as a dropped option would be unwrapped
to a resolved
+ * attribute the Aggregate never provides, and reported as
`MISSING_ATTRIBUTES` instead of the
+ * `UNRESOLVED_COLUMN` the same query gets without a UDF. The batch must
therefore run before
+ * "Remove TempResolvedColumn", so that batch can still clean up behind this
re-run. A shape
+ * needing a resolution rule not listed here fails `CheckAnalysis` as it did
before the drop rule
+ * existed, rather than analyzing wrongly.
+ *
+ * @param resolveReferences the Analyzer's `ResolveReferences`, shared with
the Resolution batch.
+ * @param resolveAliases the Analyzer's `ResolveAliases`.
+ * @param resolveAggregateFunctions the Analyzer's `ResolveAggregateFunctions`.
+ */
+class DropUnresolvedTranspiledPythonUDFOptions(
+ resolveReferences: Rule[LogicalPlan],
+ resolveAliases: Rule[LogicalPlan],
+ resolveAggregateFunctions: Rule[LogicalPlan]) extends Rule[LogicalPlan] {
+ def apply(plan: LogicalPlan): LogicalPlan = {
+ val dropped =
+ if (!plan.containsPattern(TRANSPILED_PYTHON_UDF)) {
+ plan
+ } else {
+
plan.resolveOperatorsWithPruning(_.containsPattern(TRANSPILED_PYTHON_UDF)) {
+ case op if op.containsPattern(TRANSPILED_PYTHON_UDF) =>
+
op.transformExpressionsUpWithPruning(_.containsPattern(TRANSPILED_PYTHON_UDF)) {
+ case t: TranspiledPythonUDF if t.arguments.forall(_.resolved) &&
+ (t.optionInputCategories.nonEmpty ||
!t.transpiledOptions.forall(_.resolved)) =>
+ val typed =
ResolveTranspiledPythonUDFOptions.pruneByCategoryAndTypeParameters(t)
+ val (kept, dropped) =
typed.transpiledOptions.partition(_.resolved)
+ if (dropped.nonEmpty) {
+ val first = Utils.redact(
+ SQLConf.get.stringRedactionPattern,
dropped.head.simpleString(maxFields = 100))
+ // Only claim "falls back to interpreted Python" when every
option was
+ // dropped; with survivors, ConvertToCatalyst still picks
the first kept one.
+ if (kept.isEmpty) {
+ logWarning(log"Dropping ${MDC(LogKeys.COUNT,
dropped.length)} transpiled " +
+ log"option(s) for Python UDF
${MDC(LogKeys.FUNCTION_NAME, t.name)}; " +
+ log"the call falls back to interpreted Python. First
dropped: " +
+ log"${MDC(LogKeys.EXPR, first)}")
+ } else {
+ logWarning(log"Dropping ${MDC(LogKeys.COUNT,
dropped.length)} transpiled " +
+ log"option(s) for Python UDF
${MDC(LogKeys.FUNCTION_NAME, t.name)}; " +
+ log"${MDC(LogKeys.COUNT, kept.length)} option(s) remain.
First dropped: " +
Review Comment:
**Nit (P3):** Both counts in this warning use `LogKeys.COUNT`, and
`MessageWithContext.+` merges fragment contexts with `putAll` (common/utils
Logging.scala:80-83), so the structured record's `count` holds the kept count
and the dropped count is in no field, although the rendered text is right.
Logging the kept count under the existing `LogKeys.NUM_REMAINED` keeps both.
**Verification:**
- **Inspection:** The partial-drop warning uses a different log key for each
of its two counts, and its rendered message is unchanged.
--
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]