spark-test commented on code in PR #59216:
URL: https://github.com/apache/spark/pull/59216#discussion_r4576908248


##########
python/pyspark/sql/transpile.py:
##########
@@ -752,49 +1046,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):** In a body that contains a chained comparison, this fold 
still leaves a user-written `and` / `or` as a splittable `And` / `Or`. Reading 
the lowering, `(0 <= x <= 10 and y > 0) or (20 <= x <= 30 and y > 0)` becomes 
`Or(And(chain1, g), And(chain2, g))`, where both `g` are the same guarded `y > 
0`: the raise message depends only on the operator, and `RaiseError` overrides 
`throwable` but stays deterministic, so `semanticEquals` matches the two. 
ConvertToCatalyst substitutes the option before the operator-optimization rules 
run, and BooleanSimplification's common-factor elimination for disjunction 
(optimizer/expressions.scala:601-625) rewrites it to `g && (chain1 || chain2)` 
without checking `throwable`. `And` evaluates `g` first, so a row with x = 15 
and y NULL fails with 'cannot compare NULL' where Python returns False. The 
absorption shape `(0 <= x <= 10 and y > 0) or (y > 0)` reduces to `g`, which 
returns True for x NULL and y = 5 where Python raises TypeError. T
 he module docstring records the same rewrites for the `and` spelling, and 
notes that subexpression elimination hoists a repeated guard on its own. On the 
base branch both bodies contain a chain and run as interpreted Python with 
Python's answer; a chain inside `and` / `or` without a repeated guard is 
unaffected.
   
   See **Shared repair plan 1** in the review body.



##########
python/pyspark/sql/transpile.py:
##########
@@ -752,49 +1046,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):** This extends the earlier comment on this line to the 
returned and compared uses. The gate refuses an operand that can be NULL 
wherever the `and` / `or` sits. As an if/ternary test the lowered BoolOp is 
wrapped in `coalesce(test, false)`, and under `not` in `coalesce(~x, true)`, so 
there the base branch's lowering already matched Python: tracing both versions 
over every NULL combination, `1 if ((True if c > 0 else None) or (x > 0)) else 
0`, `not ((True if c > 0 else None) or (x > 0))` and the guard style `1 if (((a 
< b) if a is not None and b is not None else None) and c == 1) else 0` lower on 
the base branch with Python's answer, and the released transpiler lowers the 
first two as well, while head runs all three in a Python worker for every row. 
The returned and compared uses, and an `and` whose later comparison raises 
after a NULL left operand, did diverge, and falling back fixes them, but it 
costs more than the fix needs: folding a possibly-NULL left opera
 nd as `CASE WHEN coalesce(a, false) THEN b ELSE a END` for `and` and `CASE 
WHEN coalesce(a, false) THEN true ELSE b END` for `or` returns Python's value, 
None included, and evaluates the same operands Python does, in every position. 
Results are correct either way; what this costs is per-row interpreted 
evaluation for these bodies.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59216#discussion_r4507366768).
   
   See **Shared repair plan 1** in the review body.



##########
python/pyspark/sql/transpile.py:
##########
@@ -692,9 +978,17 @@ 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

Review Comment:
   **Nit (P3):** Comparisons now take the `case ast.Compare(): return "bool"` 
arm just above, so this arm only sees `not` and boolean ops, yet the example 
two lines down is still the comparison `(x > 0) + 1`. A maintainer reading the 
arm is told comparisons still reach it; an example such as `(not x) + 1` would 
match.
   
   **Verification:**
   - **Inspection:** The example in the boolean-category arm's comment is a 
`not` or boolean-op expression rather than a comparison.



##########
python/pyspark/sql/transpile.py:
##########
@@ -35,6 +35,81 @@
 functions with more than three untyped parameters only emit the
 all-numeric and all-string variants.
 
+Constructs that short-circuit in Python -- ``and`` / ``or`` and chained
+comparisons such as ``0 <= x <= 100`` -- keep the ``raise_error`` NULL guard in
+a later operand from firing on rows Python never reaches. ``and`` / ``or`` fold
+with ``&`` / ``|``: ``And`` skips its right operand when the left is exactly
+``false`` (and ``Or`` when the left is exactly ``true``) in both ``eval`` and
+``doGenCode``. Note the "exactly": a NULL left operand still evaluates the 
right,
+so ``and`` / ``or`` operands must be provably boolean and non-NULL (see
+``_is_never_null_boolean``). A chain folds instead into a sequential CASE WHEN
+(``CASE WHEN NOT link1 THEN false ... WHEN NOT link(n-1) THEN false ELSE linkN
+END``): each later link sits in a branch that runs only after every earlier 
link
+is true, so it short-circuits the same way. Chain links need no non-NULL gate,
+because every comparison lowering is total, so ``NOT link`` is never NULL.
+
+That short-circuit is an EVALUATION-time property only, and it does not by
+itself survive the optimizer. The ``&`` / ``|`` fold that ``and`` / ``or`` use
+is splittable, and four optimizer rules diverge on it, all measured rather than
+reasoned about (the last bullet adds the NaN value-level difference). A chain's
+CASE WHEN is atomic -- ``splitConjunctivePredicates`` matches only ``And``,
+``BooleanSimplification``'s patterns match ``And`` / ``Or``, and subexpression
+elimination recurses only into a CASE WHEN's first condition -- so no rule can
+move a later guard ahead of the links that gate it, and a chain predicate moves
+only as a whole when pushdown applies. The divergences below are therefore the
+``and`` / ``or`` fold's; the ``and`` form of each repro (``a < b and b < c`` 
for
+``a < b < c``) predates this lowering and diverges identically.
+
+* Predicate pushdown through a JOIN -- CLOSED by SPARK-58627. ``Optimizer``
+  partitions on ``cond.deterministic && !cond.throwable``, and the ``&`` fold 
is
+  splittable by ``splitConjunctivePredicates``, so while ``RaiseError`` still
+  reported non-throwable a guard could be pushed below a join and run on rows 
the
+  join drops. ``RaiseError`` now overrides ``throwable``, and the same repro
+  returns Python's answer. ``test_udf_transpile_boolop_short_circuits`` is the
+  regression test. (A pure chain ``lambda a, b, c: a < b < c`` over a join was
+  the original repro; it no longer reaches this path, since the chain now folds
+  to an atomic CASE WHEN that cannot be split.)
+* Predicate pushdown through an AGGREGATE or WINDOW -- OPEN, and the reason the

Review Comment:
   **Nit (P3):** Since the rebase onto a base branch with SPARK-60633, this 
divergence no longer reproduces: the Aggregate arm goes through 
`pushBelowAggregate`, whose `splitPushable` keeps a throwable conjunct written 
after one that stays up above the operator (Optimizer.scala:2907-2937, 
3010-3016), and the Window, Union and EventTimeWatermark arms use 
`splitPushableConjuncts`, which checks `throwable` the same way. In the cited 
repro `sa < b` reads an aggregate alias and stays up, so the guarded `b < c` 
written after it stays up too. With the JOIN bullet already closed, only 
BooleanSimplification and subexpression elimination of the 'four optimizer 
rules' still diverge. Two nearby reasons are imprecise as well: 
BooleanSimplification matches conjuncts through `semanticEquals`, which 
requires both sides to be deterministic, and subexpression elimination also 
extracts what every CASE WHEN condition or every value shares (`branchGroups`); 
for the chain fold that is already in the first
  condition, so the atomicity conclusion still holds.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59216#discussion_r4507366783).
   
   **Verification:**
   - **Inspection:** The docstring's status, count and stated reasons for each 
optimizer divergence agree with the base branch's pushdown, 
BooleanSimplification and subexpression-elimination code.



##########
python/pyspark/sql/tests/test_udf_transpile_hypothesis.py:
##########
@@ -206,6 +206,25 @@ def _env_opts_in(value: Optional[str]) -> bool:
         (1, -_LONG_BOUND),
     )
 
+    # Triple edges for the chained-comparison tests, pulled from the

Review Comment:
   **Nit (P3):** The boundary orderings `(0, 1, 2)` and `(2, 1, 0)` use 2, 
which `_LONG_EDGES` (line 159) does not contain, so the triples are not all 
pulled from the single-value edges. Using an edge such as 7, or dropping the 
provenance claim, would make the comment match.
   
   **Verification:**
   - **Inspection:** Every value the triple-edge comment attributes to 
`_LONG_EDGES` is in `_LONG_EDGES`.



##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -549,39 +564,520 @@ def gte_zero(x):
                     self.assertEqual(row_lte[0], lte_expected)
                     self.assertEqual(row_gte[0], gte_expected)
 
-    def test_udf_transpile_chained_comparison_falls_back(self):
-        # ``a < b < c`` is a chained comparison: Python evaluates it as
-        # ``(a < b) and (b < c)``. The transpiler refuses chained Compare
-        # nodes (``len(ops) != 1``) and must fall back to interpreted Python.
+    def test_udf_transpile_chain_short_circuits(self):
+        # THE test for the chained lowering. Python's chain short-circuits: 
when
+        # ``a < b`` is false, ``b < c`` is never evaluated, so a NULL ``c`` 
cannot
+        # raise. The chain's CASE WHEN only reaches a later link once every 
earlier
+        # one is true, so the fold matches. Nullable *columns* are required: a
+        # literal `None` has no column category, so `1 < 0 < None` just falls 
back.
+        #
+        # Both of `CaseWhen`'s laziness implementations are exercised: 
`doGenCode`
+        # under the default FALLBACK factory mode, and `eval` under NO_CODEGEN.
+        # `spark.sql.codegen.wholeStage=false` is NOT enough for the latter -- 
it
+        # disables whole-stage fusion, but expressions are still compiled 
through
+        # the codegen factory, so `doGenCode` runs either way. Survival 
through the
+        # OPTIMIZER is separate; see 
test_udf_transpile_chain_survives_optimizer.
+        def chained(a, b, c):
+            return a < b < c
+
+        schema = "a long, b long, c long"
+        for factory_mode in ("FALLBACK", "NO_CODEGEN"):
+            conf = dict(_TRANSPILE_ON)
+            conf["spark.sql.codegen.factoryMode"] = factory_mode
+            with self.subTest(factory_mode=factory_mode), self.sql_conf(conf):
+                pudf = UserDefinedFunction(chained, BooleanType())
+                self.assertTrue(pudf.transpiled, "3-column chain should 
transpile")
+                df = self.spark.createDataFrame([(1, 0, None)], schema)
+                [row] = df.select(pudf("a", "b", "c")).collect()
+                self.assertEqual(
+                    False,
+                    row[0],
+                    "first link is false, so the NULL second link must not be 
evaluated",
+                )
+                # ... but when the first link IS true the second link is 
reached
+                # and its NULL guard fires, exactly as Python raises TypeError.
+                df = self.spark.createDataFrame([(0, 1, None)], schema)
+                with self.assertRaises(Exception) as ctx:
+                    df.select(pudf("a", "b", "c")).collect()
+                self.assertIn("cannot compare NULL", str(ctx.exception))
+
+    def test_udf_transpile_chain_survives_optimizer(self):
+        # A chain folds to a sequential CASE WHEN, which is atomic to
+        # `splitConjunctivePredicates` and `BooleanSimplification`. An `&` fold
+        # would let those rules split or reorder it, moving a later link's NULL
+        # guard ahead of the links that gate it -- as they still do for the
+        # equivalent user-written `and` (see the module docstring). Each repro
+        # below is such a shape; all must return Python's answer (or raise like
+        # Python) with the chain fully lowered (no EvalPython in the plan).
+
+        # PushDownPredicates / Aggregate: an `&` fold's later link over only

Review Comment:
   **Nit (P3):** This case can no longer fail if the chain fold regresses to 
`&`: the first conjunct `sa < b` reads an aggregate alias and cannot be pushed, 
and since SPARK-60633 `splitPushable` keeps every throwable conjunct written 
after it above the Aggregate (Optimizer.scala:2907-2937, 3010-3016), so the 
guarded `b < c` stays up under either fold and the query returns `[]` with no 
EvalPython node. Only the two BooleanSimplification cases below tell the folds 
apart. The lead comment ('as they still do for the equivalent user-written 
`and`') and the `and` / `or` short-circuit test's note that the other docstring 
divergences remain open rest on the same premise, so the case reads as coverage 
it does not provide.
   
   **Verification:**
   - **Inspection:** The optimizer-survival test attributes fold discrimination 
only to its BooleanSimplification cases, and the surrounding test comments list 
the same open divergences as the module docstring.



##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -1084,22 +1580,33 @@ def wrapper(x):
             self.assertEqual(result[0], 60, "must run the wrapper, not the 
wrapped source")
 
     def test_udf_transpile_falls_back_for_none_in_boolop(self):
-        # Python's `None and x` short-circuits to None; Spark's three-valued
-        # `null AND false` is false. A literal None operand must force a
-        # fallback rather than silently diverge.
+        # Python's `None and x` short-circuits to None, which Spark's 
three-valued
+        # `null AND false` (false) does not reproduce. Any operand
+        # `_is_never_null_boolean` cannot prove non-NULL -- a literal None, or 
a
+        # ternary with a None branch -- must fall back rather than diverge.
         import warnings as _warnings
 
         from pyspark.sql.types import StructField, StructType
 
         def none_and(x):
             return None and (x > 0)
 
+        def nullable_ternary_and(x):

Review Comment:
   **Nit (P3):** This is the only ternary `and` / `or` operand in either suite, 
and its None is in the else branch. `_is_never_null_boolean` checks both 
branches (transpile.py:441-442), but if its IfExp arm checked only `orelse`, 
`(None if x > 0 else True) and (x < 0)` would take the `&` fold and return 
False for x = 5 where Python returns None, and every existing assertion would 
still pass. A case with the None in the body branch that asserts Python's 
answer gives that check a failure signal.
   
   **Verification:**
   - **Regression:** With the gate's ternary arm checking only the else branch, 
the body-branch case fails because the `&` lowering returns False where Python 
returns None; with both branches checked it passes.



-- 
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]

Reply via email to