spark-test commented on code in PR #59216:
URL: https://github.com/apache/spark/pull/59216#discussion_r4584336073
##########
python/pyspark/sql/transpile.py:
##########
@@ -752,49 +1043,35 @@ def _convert_chunk(self, params: List[str], body:
ast.AST | None) -> Column:
case ast.BoolOp(op=op, values=values):
# Python `and` / `or` short-circuit and return one of the
# operands rather than a strict boolean. For the booleans
- # produced by Compare / UnaryOp(Not) / nested BoolOps this
- # maps cleanly onto Spark Column `&` / `|`. For
- # non-boolean operands (including bare parameter names whose
- # runtime type is unknown) the right semantics would require
- # Python's truthiness rules (0 / "" / None / [] all
- # falsy), which we can't faithfully reproduce without the
- # input column types -- Spark's `&` / `|` would silently
- # do bitwise instead. Require all operands to be statically
- # known boolean so the caller falls back to interpreted
- # Python rather than producing a plan whose results diverge.
- if not all(_is_definitely_boolean(v) for v in values):
- raise UnsupportedOperationException(
- "`and` / `or` operand type is not statically known "
- "to be boolean; Spark's `&` / `|` are bitwise, not "
- "Python truthiness, so the transpiler refuses to "
- "lower this and the UDF falls back to interpreted "
- "Python"
- )
- # A literal None operand short-circuits differently: Python's
- # `None and (x > 0)` returns None regardless of x, but Spark's
- # three-valued `null AND false` is false (and `null OR true` is
- # true), so the lowered form diverges. `_is_definitely_boolean`
- # accepts None for `not`/if-test contexts where coalesce
handles
- # it; here it must force a fallback instead.
- if any(isinstance(v, ast.Constant) and v.value is None for v
in values):
+ # produced by Compare / UnaryOp(Not) / nested BoolOps, this
maps
+ # cleanly onto `&` / `|`. For non-boolean operands (including
+ # bare parameter names whose runtime type is unknown) the right
+ # semantics would need Python's truthiness rules (0 / "" /
None /
+ # [] all falsy), which we can't reproduce without the input
+ # column types -- Spark's `&` / `|` require boolean operands.
+ #
+ # The gate is `_is_never_null_boolean` rather than
+ # `_is_definitely_boolean` because Spark's `NULL AND false` is
+ # `false` where Python's `None and False` is `None`.
+ if not all(_is_never_null_boolean(v) for v in values):
Review Comment:
**Non-blocking (P2):** The divergence this gate fixes needs a possibly-NULL
operand followed by another operand: `NULL AND false` is false where `None and
False` is None. A possibly-NULL operand in last position already gets Python's
answer from the `&` / `|` fold when every operand before it is a never-NULL
boolean: `false AND v` is false without evaluating `v` and `true AND v` is `v`,
matching `False and v` and `True and v`, a NULL `v` included, and `Or` is
symmetric. The base branch's gate (`_is_definitely_boolean` plus a literal-None
refusal) lowered `(x > 0) and (True if y > 0 else None)`, and the guarded style
the NULL-guard warning recommends, `(a > 0) and ((b < 10) if b is not None else
None)`, with Python's answer; at head both run as interpreted Python, every row
through a Python worker. Requiring `_is_never_null_boolean` only of the
operands before the last, and the base branch's `_is_definitely_boolean` of the
last while still refusing a literal None, keeps the fallbac
k for every input that diverged.
`test_udf_transpile_falls_back_for_none_in_boolop` puts every nullable operand
first, so no test covers this case.
This extends an [existing
discussion](https://github.com/apache/spark/pull/59216#discussion_r4576908251).
**Verification:**
- **Regression:** `and`/`or` bodies whose only possibly-NULL operand is
last, returned, used as an if/ternary test and under `not`, lower with no
Python evaluation node and match Python over every NULL combination under both
generated and interpreted expression evaluation.
- **Compatibility:** Bodies with a possibly-NULL operand in a non-last
position, including a None in either ternary branch, still fall back and return
Python's answer.
##########
python/pyspark/sql/transpile.py:
##########
@@ -828,60 +1105,45 @@ def _convert_chunk(self, params: List[str], body:
ast.AST | None) -> Column:
orelse[0] if orelse else None,
)
case ast.Compare(left, ops, comps):
- if len(ops) != 1 or len(comps) != 1:
+ # `in` / `not in` are container membership, not a chainable
value
+ # comparison, and need their own NULL analysis: Python's `in`
Review Comment:
**Nit (P3):** Python chains `in` and `not in` like the other comparison
operators: `a < b in (1, 2)` parses as one `Compare` with ops `[Lt, In]` and
means `(a < b) and (b in (1, 2))`. The refusal below scans every operator for
that reason, and `test_udf_transpile_comparison_fallbacks` lists `a < b in (1,
2)` as a chain that must still refuse, so a membership lowering written from
this comment would miss the chain-link case. Suggested wording:
```suggestion
# `in` / `not in` are container membership rather than value
comparisons,
# though one can be a link of a chain; they need their own
NULL analysis: `in`
```
**Verification:**
- **Inspection:** The comment on the membership refusal agrees with Python's
chaining of `in` / `not in` and with the refusal's scan of every operator.
##########
python/pyspark/sql/transpile.py:
##########
@@ -752,49 +1043,35 @@ def _convert_chunk(self, params: List[str], body:
ast.AST | None) -> Column:
case ast.BoolOp(op=op, values=values):
# Python `and` / `or` short-circuit and return one of the
# operands rather than a strict boolean. For the booleans
- # produced by Compare / UnaryOp(Not) / nested BoolOps this
- # maps cleanly onto Spark Column `&` / `|`. For
- # non-boolean operands (including bare parameter names whose
- # runtime type is unknown) the right semantics would require
- # Python's truthiness rules (0 / "" / None / [] all
- # falsy), which we can't faithfully reproduce without the
- # input column types -- Spark's `&` / `|` would silently
- # do bitwise instead. Require all operands to be statically
- # known boolean so the caller falls back to interpreted
- # Python rather than producing a plan whose results diverge.
- if not all(_is_definitely_boolean(v) for v in values):
- raise UnsupportedOperationException(
- "`and` / `or` operand type is not statically known "
- "to be boolean; Spark's `&` / `|` are bitwise, not "
- "Python truthiness, so the transpiler refuses to "
- "lower this and the UDF falls back to interpreted "
- "Python"
- )
- # A literal None operand short-circuits differently: Python's
- # `None and (x > 0)` returns None regardless of x, but Spark's
- # three-valued `null AND false` is false (and `null OR true` is
- # true), so the lowered form diverges. `_is_definitely_boolean`
- # accepts None for `not`/if-test contexts where coalesce
handles
- # it; here it must force a fallback instead.
- if any(isinstance(v, ast.Constant) and v.value is None for v
in values):
+ # produced by Compare / UnaryOp(Not) / nested BoolOps, this
maps
+ # cleanly onto `&` / `|`. For non-boolean operands (including
+ # bare parameter names whose runtime type is unknown) the right
+ # semantics would need Python's truthiness rules (0 / "" /
None /
+ # [] all falsy), which we can't reproduce without the input
+ # column types -- Spark's `&` / `|` require boolean operands.
+ #
+ # The gate is `_is_never_null_boolean` rather than
+ # `_is_definitely_boolean` because Spark's `NULL AND false` is
+ # `false` where Python's `None and False` is `None`.
+ if not all(_is_never_null_boolean(v) for v in values):
raise UnsupportedOperationException(
- "literal None operand in `and` / `or` cannot be
lowered: "
- "Spark's three-valued logic diverges from Python's "
- "short-circuit-return-operand semantics, so the UDF "
- "falls back to interpreted Python"
+ "`and` / `or` operand is not statically known to be a "
+ "non-NULL boolean; Python's short-circuit returns the "
+ "operand itself (so `None and x` is None) while
Spark's "
+ "`&` / `|` build logical And / Or over three-valued
logic, so the "
+ "transpiler refuses to lower this and the UDF falls
back "
+ "to interpreted Python"
)
cols = [self._convert_chunk(params, v) for v in values]
- if isinstance(op, ast.And):
- result = cols[0]
- for c in cols[1:]:
- result = result & c
- return result
- if isinstance(op, ast.Or):
- result = cols[0]
- for c in cols[1:]:
- result = result | c
- return result
- raise UnsupportedOperationException(f"BoolOp operator {op} is
not supported")
+ match op:
Review Comment:
**Blocking (P1):** This extends the earlier comment on this line beyond
bodies with a chained comparison. The `&` / `|` fold also reaches bodies with
no chain that only the new `case ast.Compare(): return "bool"` arm lets lower,
those with a comparison over a comparison, `and` / `or` or ternary operand.
Reading the lowering, `((y > 0 and x > 0) or (z > 0 and x > 0)) == True`
declared `BooleanType` is refused by the base branch, which labels that
comparison numeric, and lowers at head with the same guarded `x > 0` in both
`And`s of the `Or`. BooleanSimplification's common-factor elimination
(optimizer/expressions.scala:601-625) matches the two copies through
`semanticEquals` and moves the guard to the front, so for x = NULL and y = z =
-1 the query fails with 'cannot compare NULL' where Python returns False. The
chain shapes behave the same way: `(0 <= x <= 10 and y > 0) or (20 <= x <= 30
and y > 0)` fails for x = 15 and y = NULL, and the absorption shape `(0 <= x <=
10 and y > 0)
or (y > 0)` returns True for x = NULL and y = 5, where Python raises
TypeError. Bodies without either construct already diverge this way on the base
branch, as the module docstring records; this change extends the divergence to
bodies the base branch ran as interpreted Python with Python's answer.
This extends an [existing
discussion](https://github.com/apache/spark/pull/59216#discussion_r4576908248).
**Recommended change:** In a body only this change lowers, one with a
multi-link chained comparison or with a comparison over an operand that
`_is_definitely_basic_type` rejects (a comparison, `and`/`or`, ternary or other
non-basic operand), fold every user-written `and`/`or` into a sequential CASE
WHEN, as chains already are: `CASE WHEN NOT v1 THEN false ... WHEN NOT v(n-1)
THEN false ELSE vn END` for `and` and `CASE WHEN v1 THEN true ... WHEN v(n-1)
THEN true ELSE vn END` for `or`, keeping `&`/`|` for every other body. Decide
once per body whether it holds either construct; the base branch refused chains
outright and labeled such comparisons numeric, so it did not lower these bodies
under a Boolean return. This change's first commit, 818d783924b, folded every
`and`/`or` through nested-CASE WHEN helpers `_lazy_and` / `_lazy_or`;
d8aebad1096 removed them so that already-shipped UDFs keep the splittable `And`
that predicate pushdown, partition pruning and InferFiltersFromConstraint
s need. That reason holds for the bodies that keep `&`/`|`, not for the bodies
the base branch never lowered, so start from 818d783924b's helpers. Update the
module docstring and the arm's comment, and add UDF transpiler unit tests for
such bodies whose `and`/`or` repeats a guarded comparison.
**Why this works:** Each later operand sits in a branch that runs only once
every earlier operand has not decided the result, which is how Python evaluates
`and`/`or`; the operands before the last are never-NULL booleans, so no
condition is NULL, and the last operand is returned as Python returns it. A
CASE WHEN is no `And`/`Or`, so splitConjunctivePredicates and
BooleanSimplification treat it as one predicate, and subexpression elimination
extracts only what its first condition holds or what all its conditions or all
its values share, so no rule can move a guard ahead of the operands that gate
it.
**Scope:** Change how the Python UDF transpiler folds `and`/`or` in the
bodies only this change lowers, and cover those bodies in the transpiler's unit
tests.
**Compatibility:** `and`/`or` bodies with neither a chained comparison nor a
comparison over a non-basic operand keep the base branch's `&`/`|` fold and the
plans that follow from it.
**Risks:** `and`/`or` in a body with a chained comparison or a comparison
over a non-basic operand become one predicate for the optimizer: a
non-throwable conjunct such as `b == c` in `(0 < a < 10) and (b == c)` is no
longer pushed below a join or into a scan on its own, and over nullable
operands the whole predicate stays above a join, as a chain already does; the
base branch ran these bodies as interpreted Python. Rolling back means
restoring `&`/`|` for these bodies.
**Constraints:** Bodies with neither a chained comparison nor a comparison
over a non-basic operand keep the `&`/`|` fold and its per-conjunct pushdown,
so already-lowered `and`/`or` UDFs keep their plans. Every operand before the
last stays gated as a never-NULL boolean, so no CASE WHEN condition is NULL,
and the last operand stays the ELSE branch, so its value, NULL included, is
returned unchanged.
**Exclusions:**
- BooleanSimplification and subexpression elimination on `and`/`or` bodies
the base branch already lowers stay with the separately tracked optimizer
fixes, as the change declares.
**Success:** `(0 <= x <= 10 and y > 0) or (20 <= x <= 30 and y > 0)` returns
False for x = 15 and y = NULL with the body lowered. `(0 <= x <= 10 and y > 0)
or (y > 0)` raises like Python for x = NULL and y = 5 with the body lowered.
`((y > 0 and x > 0) or (z > 0 and x > 0)) == True` declared Boolean returns
False for x = NULL and y = z = -1 with the body lowered. `and`/`or` bodies with
neither construct lower to the same `&`/`|` expressions as before, and bodies
with one, such as `(0 < a < 10) and (b == c)`, still lower and return the same
values.
**Verification:**
- **Regression:** Bodies with a chained comparison, and bodies with a
comparison over an `and`/`or`, comparison or ternary operand, whose `and`/`or`
repeats a guarded comparison across `or` branches, in the common-factor and
absorption shapes, return Python's answer or raise like it, with no Python
evaluation node, under both generated and interpreted expression evaluation.
- **Compatibility:** `and`/`or` bodies with neither construct keep their
`&`/`|` lowering and their short-circuit, join and optimizer-survival results,
and bodies with one that already lowered keep returning the same values.
##########
python/pyspark/sql/transpile.py:
##########
@@ -692,11 +975,19 @@ def branch_category(b: ast.AST) -> Optional[str]:
"ternary with all-None branches has no usable column
category"
)
return result_cat
+ case ast.Compare():
+ # Checked by node kind, not through `_is_definitely_boolean`:
that
+ # also demands basic-type operands, so it misses `(a < b) ==
True`,
+ # which then reached the numeric catch-all below and let a
boolean
+ # body satisfy a numeric declared return type -- emitting
+ # `cast(<boolean> as bigint)` where the interpreted path
returns
+ # NULL. EVERY Python comparison evaluates to a bool.
+ return "bool"
case _ if _is_definitely_boolean(node):
- # Comparisons, `not`, and boolean ops produce a boolean column.
- # Labeling them "numeric" (the old catch-all) let booleans into
+ # `not` and boolean ops produce a boolean column. Labeling them
+ # "numeric" (the old catch-all) let booleans into
# arithmetic/equality lowerings where ANSI analysis fails (e.g.
- # `(x > 0) + 1`, valid Python) instead of falling back.
+ # `(not x) + 1`, valid Python) instead of falling back.
Review Comment:
**Nit (P3):** The example the previous review suggested here does not work:
`(not x) + 1` stops at the `not` arm, which refuses the bare name `x` as not
provably boolean, before the `+` arm lowers anything, and it does so under the
old 'numeric' label as well, so it never reaches the arithmetic lowering this
comment describes. An example whose `not` operand is boolean does: `(not (x >
0)) + 1` lowers its `not`, and with a 'numeric' label it would build a boolean
addition that fails ANSI analysis.
```suggestion
# `(not (x > 0)) + 1`, valid Python) instead of falling back.
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/59216#discussion_r4576908254).
**Verification:**
- **Inspection:** The example in the boolean-category arm's comment has a
provably boolean `not` operand, so it reaches the `+` lowering rather than the
`not` refusal.
--
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]