spark-test commented on code in PR #58185:
URL: https://github.com/apache/spark/pull/58185#discussion_r4508573429
##########
python/pyspark/sql/transpile.py:
##########
@@ -630,64 +689,55 @@ def _convert_chunk(self, params: List[str], body: ast.AST
| None) -> Column:
"is not supported by the transpiler"
)
case ast.BinOp(left=left, op=op, right=right):
- # Operator selection is driven by the operand *categories*
under
- # the current input-type variant (see ``_category``): Python's
- # `+` / `*` are overloaded for text. `+` -> add (num,num) or
- # concat (str,str); `*` -> multiply (num,num) or repeat
(str,int
- # / int,str); `-` / `%` are numeric-only. Combos that don't fit
- # (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.
+ # Numeric operations target ANSI semantics: fixed-width
overflow
+ # raises instead of promoting to an arbitrary-precision Python
+ # integer. NULL operands are guarded because Python raises a
+ # TypeError where Catalyst would otherwise propagate NULL.
String
+ # concatenation uses the same guard. String repetition falls
back
+ # because its count cannot be represented safely for every
Python
+ # integer.
+ # TODO(SPARK-55210): add exact integer promotion and remove the
+ # documented overflow divergence.
lc = self._category(params, left)
rc = self._category(params, right)
left_col = self._convert_chunk(params, left)
right_col = self._convert_chunk(params, right)
+ null_guard = left_col.isNull() | right_col.isNull()
Review Comment:
**Non-blocking (P2):** `left_col` and `right_col` each appear here in the
NULL check and again in the operation, and the unary arms do the same with
their operand. ColumnNodeToExpressionConverter and `resolveUDFParams`
materialize every reference separately. Subexpression elimination does not
merge them either: in a single-branch guard the condition copy is counted once,
and the `raise_error` value shares nothing with the else value. Each nesting
level therefore doubles plan size, analysis work, generated code, and per-row
evaluation. A 20-term `x + 1 + ... + 1` lowers to about 10 million nodes per
option, where the base branch produced 41. Under ANSI a guarded child is never
NULL, so re-checking it adds no semantics. The fix was agreed for after merge
under SPARK-58628; it stays listed because the growth also multiplies across
every option carried before pruning.
This extends an [existing
discussion](https://github.com/apache/spark/pull/58185#issuecomment-5417860086).
**Recommended change:** Track whether each lowered operand can be NULL, and
emit a NULL check only for operands that can. Guarded results, non-None
constants, and comparison results are then used without being re-checked, which
keeps the lowered tree linear in the UDF body. This resolves the TODO for
SPARK-58628.
**Why this works:** Under ANSI, a guarded arithmetic, unary, or
concatenation result either raises or returns a non-NULL value, and a non-None
constant is never NULL, so NULL checks on them are always false. Nullability is
derived bottom-up: a parameter or the None literal can be NULL, a ternary can
be NULL when either branch can, and an and/or when any operand can, while not
(coalesced), comparisons, guarded arithmetic, unary, and concatenation results,
and non-None constants never are. Each node then checks only the operands that
can be NULL, so every child is referenced once in its parent's operation.
Results and error messages stay the same, with one exception: when an inner
overflow coincides with a later NULL operand, the NULL error is reported, as in
Python.
**Scope:** Change how the transpiler builds NULL guards so that lowered
operands are neither re-checked nor duplicated, and add size-sensitive tests.
**Compatibility:** NULL operands raise exactly where Python raises
TypeError. Non-NULL results and the documented ANSI overflow divergence are
unchanged.
**Risks:** A wrong nullability classification would drop a needed NULL check
and return NULL where Python raises, so the classification must stay
conservative for any node kind not known to be non-NULL.
**Constraints:** NULL operands must still raise the same 'Python UDF
transpiler' errors wherever Python raises TypeError. Comparisons keep their
Python NULL semantics: == and != never raise, and ordering raises. A ternary
whose selected branch is a parameter, as in `(a if c > 0 else b) + 1`, keeps
its NULL check: only nodes that are never NULL by construction skip it.
**Exclusions:**
- The modulo formula's multiple references to its divisor, which the base
branch already had, are left as they are.
**Success:** For each option, the lowered expression for a chain of k nested
arithmetic or unary operators grows linearly in k, with one NULL check per
nullable operand. NULL inputs still raise wherever Python raises TypeError, and
non-NULL results are unchanged.
**Verification:**
- **Regression:** With transpilation enabled, lower a left-deep chain of
about 20 additions and a nested unary chain. Assert that the lowered expression
size grows linearly with depth and that results on non-NULL inputs match Python.
- **Behavior:** NULL inputs to nested arithmetic still fail with the
transpiler's NULL TypeError message, and comparison NULL semantics are
unchanged.
- **Behavior:** A ternary over parameters inside arithmetic, such as `(a if
c > 0 else b) + 1`, still raises the transpiler's NULL TypeError message when
the selected branch is NULL.
##########
python/pyspark/sql/transpile.py:
##########
@@ -839,32 +892,40 @@ def _annotation_category(annotation: Optional[ast.AST])
-> Optional[str]:
def _param_category_combos(function_ast: ast.FunctionDef, public_params:
List[str]) -> List[dict]:
"""Per-variant maps ``{public_param_index -> category}`` where category is
- one of ``"numeric"``/``"string"``/``"bool"``/``"binary"``.
-
- A typed param (``def f(a: str, b: int)``) is pinned to its category; an
- untyped param is tried as both numeric and string. To cap plan growth, when
- more than three params are untyped we collapse the untyped ones to the
- all-numeric and all-string variants (encourage typing inputs to keep the
- matrix small) while keeping every typed param pinned.
+ one of ``"numeric"``/``"integral"``/``"fractional"``/``"string"``/
+ ``"bool"``/``"binary"``.
+
+ A typed param (``def f(a: str, b: int)``) is pinned to its category. An
+ untyped param is normally tried as numeric and string; functions containing
+ value comparisons split numeric into integral and fractional so only the
+ latter emits NaN checks. To cap plan growth, when more than three params
are
+ untyped we emit only homogeneous variants while keeping typed params
pinned.
"""
+ value_comparison_ops = (ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt,
ast.GtE)
+ has_value_comparison = any(
+ isinstance(node, ast.Compare)
+ and any(isinstance(op, value_comparison_ops) for op in node.ops)
+ for node in ast.walk(function_ast)
+ )
+ numeric_candidates = ["integral", "fractional"] if has_value_comparison
else ["numeric"]
n = len(public_params)
public_args = function_ast.args.args[len(function_ast.args.args) - n :]
candidates: List[List[str]] = []
untyped = 0
for arg in public_args:
cat = _annotation_category(arg.annotation)
if cat is None:
- candidates.append(["numeric", "string"])
+ candidates.append(numeric_candidates + ["string"])
untyped += 1
else:
candidates.append([cat])
if untyped > 3:
- # Cap the 2**untyped blow-up, but keep each typed param pinned to its
+ # Cap the exponential blow-up, but keep each typed param pinned to its
# category (a single-element ``candidates`` entry); only the untyped
- # params collapse to the all-numeric / all-string pair.
+ # params collapse to homogeneous numeric/string variants.
return [
{i: c[0] if len(c) == 1 else fill for i, c in
enumerate(candidates)}
- for fill in ("numeric", "string")
+ for fill in numeric_candidates + ["string"]
Review Comment:
**Non-blocking (P2):** For comparison functions with more than three untyped
parameters, this fill list is now integral, fractional, and string. At the base
branch it was numeric and string, and the numeric variant matched any mix of
non-decimal numeric columns. `def f(a, b, c, d): return a + b > c + d` over
(long, double, long, long) columns now matches no option and runs as
interpreted Python. Nothing about the NaN fix requires that: `_is_fractional`
already treats a `numeric` operand as possibly NaN, so a homogeneous numeric
fill would stay correct. The new combos test pins only the integral,
fractional, and string fills.
This extends an [existing
discussion](https://github.com/apache/spark/pull/58185#issuecomment-5704479487).
See **Shared repair plan 1** in the review body.
##########
python/pyspark/sql/transpile.py:
##########
@@ -403,17 +457,15 @@ def _category(self, params: List[str], node: ast.AST) ->
str:
case ast.Name(id=name) if name in params:
# ``params`` is the caller-facing list, so its indexes are
already
# the ``_udf_param_N`` / category indexes -- see
``_transpile_func``.
- return self._param_categories.get(params.index(name),
"numeric")
+ category = self._param_categories.get(params.index(name),
"numeric")
+ return "numeric" if category in ("integral", "fractional")
else category
case ast.BinOp(left=left, op=op, right=right):
lc = self._category(params, left)
rc = self._category(params, right)
if isinstance(op, ast.Add) and lc == rc:
return lc # str + str -> str, num + num -> num
- if isinstance(op, ast.Mult):
- if {lc, rc} == {"numeric", "numeric"}:
- return "numeric"
- if {lc, rc} == {"numeric", "string"}:
- return "string" # str * int / int * str -> repeat
+ if isinstance(op, ast.Mult) and lc == rc == "numeric":
Review Comment:
**Nit (P3):** Typing `*` only for numeric*numeric makes every string
repetition fall back, including a literal count such as `a * 3` or `3 * a`. The
base branch lowered that to `repeat(a, 3)`, which matches Python for non-NULL
strings. The reason in the BinOp comment, that the count cannot be represented
safely for every Python integer, holds for column counts but not for an integer
literal within int range, whose value is known at transpile time. Behind the
same NULL guard concat uses, `repeat` matches Python there, including `''` for
zero or negative counts.
**Verification:**
- **Regression:** Run literal-count repetition on string columns with
positive, zero, and negative counts, and assert Python's results with no Python
UDF in the plan.
- **Behavior:** Assert that a NULL string operand raises, and that
column-count and fractional-count repetition still fall back.
##########
python/pyspark/sql/transpile.py:
##########
@@ -630,64 +689,55 @@ def _convert_chunk(self, params: List[str], body: ast.AST
| None) -> Column:
"is not supported by the transpiler"
)
case ast.BinOp(left=left, op=op, right=right):
- # Operator selection is driven by the operand *categories*
under
- # the current input-type variant (see ``_category``): Python's
- # `+` / `*` are overloaded for text. `+` -> add (num,num) or
- # concat (str,str); `*` -> multiply (num,num) or repeat
(str,int
- # / int,str); `-` / `%` are numeric-only. Combos that don't fit
- # (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.
+ # Numeric operations target ANSI semantics: fixed-width
overflow
+ # raises instead of promoting to an arbitrary-precision Python
+ # integer. NULL operands are guarded because Python raises a
+ # TypeError where Catalyst would otherwise propagate NULL.
String
+ # concatenation uses the same guard. String repetition falls
back
+ # because its count cannot be represented safely for every
Python
+ # integer.
+ # TODO(SPARK-55210): add exact integer promotion and remove the
+ # documented overflow divergence.
lc = self._category(params, left)
rc = self._category(params, right)
left_col = self._convert_chunk(params, left)
right_col = self._convert_chunk(params, right)
+ null_guard = left_col.isNull() | right_col.isNull()
+ null_error = lit(
+ "Python UDF transpiler: arithmetic with NULL would raise
TypeError in Python"
+ )
match op:
case ast.Add():
if lc == rc == "string":
- return concat(left_col, right_col)
+ return when(null_guard,
raise_error(null_error)).otherwise(
+ concat(left_col, right_col)
+ )
if lc == rc == "numeric":
- return left_col.__add__(right_col)
+ return when(null_guard,
raise_error(null_error)).otherwise(
Review Comment:
**Blocking (P1):** This guard makes the lowered `x + 1.0` a value that
raises for a NULL input, and the comparison's new NaN branch references that
value a second time. Because `and`/`or` are still lowered to Spark `&`/`|`,
subexpression elimination treats both operands as always evaluated
(`spark.sql.subexpressionElimination.skipForShortcutExpr` defaults to false).
Whole-stage codegen then computes the shared guarded value before the
short-circuit runs. So `lambda x: x is not None and x + 1.0 > 2.0` over a
nullable double column now fails the query on the NULL row with the
transpiler's TypeError message, where Python and the base branch return False.
The same happens for any `and`/`or`, including one in an if-test, whose
later operand does one of three things: applies an ordering or equality
comparison to a guarded arithmetic, unary, or concatenation result that may be
fractional; compares such a result with `==`/`!=` against a nullable operand;
or repeats a guarded subexpression. Ordinary createDataFrame input reaches this
path. The current tests just never put guarded arithmetic inside an `and`/`or`
over NULL rows. When the UDF is used as a filter, a top-level `x is not None`
conjunct is checked first, but `x is None or ...` still fails.
**Recommended change:** Lower Python and/or to CASE WHEN chains instead of
Spark & and |, so every operand after the first is a branch value that runs
only when Python would evaluate it. Add regression tests that run `is not None
and ...` and `is None or ...` guards over NULL rows, both in a select and as a
filter predicate.
**Why this works:** For the non-NULL boolean operands the transpiler admits,
`a and b` becomes CASE WHEN a THEN b ELSE false END and `a or b` becomes CASE
WHEN a THEN true ELSE b END, folded left for longer chains. Subexpression
elimination counts only a CaseWhen's first condition and the expressions common
to all of its branches, so a guarded operand inside a later branch is never
hoisted, and each operand is still referenced once. An operand that can
evaluate to NULL, such as a ternary with a None branch, falls back to
interpreted Python, as None literal operands already do.
**Scope:** Change how the transpiler lowers Python and/or, and add tests
that run the lowered expression through whole-stage codegen.
**Compatibility:** Python's operand-returning semantics for boolean and/or,
and the existing fallbacks for non-boolean and None operands.
**Risks:** Plans for transpiled and/or UDFs change from And/Or to CASE WHEN.
A filter on such a UDF no longer exposes a separate IS NOT NULL conjunct, so
constraint inference and data-source pushdown no longer see that check; results
are unchanged. The change stays inside the experimental transpiler behind
spark.sql.experimental.optimizer.transpilePyUDFs, which turns it off. Boolean
operands that can be NULL now fall back to interpreted Python instead of
lowering with Spark's three-valued And/Or, which already differed from Python's
operand-returning semantics.
**Constraints:** Each operand must still be lowered and referenced once, so
the change does not reintroduce the duplication that makes nested guards grow
exponentially. The existing refusals for non-boolean operands and literal None
operands stay.
**Success:** `x is not None and x + 1.0 > 2.0`, over a nullable double
column with default subexpression-elimination settings, returns False for NULL
rows and Python's result for the others, with no Python UDF in the plan, for
createDataFrame and range input alike. Under the same conditions, `x is None or
x + 1.0 > 2.0` returns True for NULL rows, both as a selected value and as a
filter predicate. and/or bodies over non-NULL inputs return the same results as
before.
**Verification:**
- **Regression:** With transpilation enabled, run `x is not None and x + 1.0
> 2.0` and `x is None or x + 1.0 > 2.0` over a nullable double column with NULL
rows, both in a select and as a filter predicate; the existing createDataFrame
helpers already reach whole-stage codegen. Assert Python's results, no failure
on NULL rows, and no Python UDF evaluation in the executed plan.
- **Regression:** Cover the same guard inside an if-test, and over a guarded
subexpression written twice, with subexpression elimination at its defaults.
- **Behavior:** Existing and/or transpilation cases keep their results and
stay lowered.
##########
python/pyspark/sql/transpile.py:
##########
@@ -839,32 +892,40 @@ def _annotation_category(annotation: Optional[ast.AST])
-> Optional[str]:
def _param_category_combos(function_ast: ast.FunctionDef, public_params:
List[str]) -> List[dict]:
"""Per-variant maps ``{public_param_index -> category}`` where category is
- one of ``"numeric"``/``"string"``/``"bool"``/``"binary"``.
-
- A typed param (``def f(a: str, b: int)``) is pinned to its category; an
- untyped param is tried as both numeric and string. To cap plan growth, when
- more than three params are untyped we collapse the untyped ones to the
- all-numeric and all-string variants (encourage typing inputs to keep the
- matrix small) while keeping every typed param pinned.
+ one of ``"numeric"``/``"integral"``/``"fractional"``/``"string"``/
+ ``"bool"``/``"binary"``.
+
+ A typed param (``def f(a: str, b: int)``) is pinned to its category. An
+ untyped param is normally tried as numeric and string; functions containing
+ value comparisons split numeric into integral and fractional so only the
+ latter emits NaN checks. To cap plan growth, when more than three params
are
+ untyped we emit only homogeneous variants while keeping typed params
pinned.
"""
+ value_comparison_ops = (ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt,
ast.GtE)
+ has_value_comparison = any(
+ isinstance(node, ast.Compare)
+ and any(isinstance(op, value_comparison_ops) for op in node.ops)
+ for node in ast.walk(function_ast)
+ )
+ numeric_candidates = ["integral", "fractional"] if has_value_comparison
else ["numeric"]
Review Comment:
**Nit (P3):** `has_value_comparison` is decided once for the whole function,
so every untyped parameter gets integral, fractional, and string candidates as
soon as any comparison appears. For a parameter that never reaches a comparison
operand, `_category` folds integral and fractional back to `numeric` and
`_is_fractional` is never consulted, so the two variants lower to the same
tree. `def f(a, b, c): return a + b if c > 0 else a - b` now yields 27 combos,
of which 8 lower but form only 2 distinct trees; the base branch lowered 1
option. Each extra option is built at UDF construction and converted and
analyzed at every call until pruning.
This extends an [existing
discussion](https://github.com/apache/spark/pull/58185#issuecomment-5704479487).
See **Shared repair plan 1** in the review body.
--
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]