holdenk commented on code in PR #59216:
URL: https://github.com/apache/spark/pull/59216#discussion_r4580902813


##########
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:
   Fixed in 50ee61864c3: the example in the boolean-category arm's comment is 
now `(not x) + 1`.
   
   ---
   <sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of 
@holdenk.</sub>
   <!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk 
-->



##########
python/pyspark/sql/transpile.py:
##########
@@ -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:
   Fixed in 50ee61864c3, checked against the base branch's optimizer code. The 
Aggregate / Window entry is now marked CLOSED by SPARK-60633 (and names Union 
and watermark), the count reads "four optimizer rules ... (two now closed)", 
the BooleanSimplification bullet says it matches through `semanticEquals` 
(needs `deterministic`, ignores `throwable`; `RaiseError` is deterministic), 
and the atomicity paragraph now says subexpression elimination also takes what 
every CASE WHEN condition or value shares, which for a chain is already in the 
first condition.
   
   ---
   <sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of 
@holdenk.</sub>
   <!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk 
-->



##########
python/pyspark/sql/tests/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:
   Confirmed and fixed in 50ee61864c3. With the chain fold temporarily swapped 
to `&`, the Aggregate block still passes and the test first fails at the `(a < 
b < c) or (d < b < c)` case; the absorption case also returns True instead of 
raising. I kept the Aggregate block as a chain-over-aggregate pin, reworded its 
comment to say it no longer separates the folds, and fixed the lead comment and 
the `and` / `or` short-circuit test's note to name BooleanSimplification and 
subexpression elimination as the open divergences.
   
   ---
   <sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of 
@holdenk.</sub>
   <!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk 
-->



##########
python/pyspark/sql/tests/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:
   Added `nullable_ternary_body_and` (`(None if x > 0 else True) and (x < 0)`) 
in 50ee61864c3, with a check that the fallback returns None for x = 5. With the 
gate's IfExp arm temporarily checking only `orelse`, the case fails both the 
not-transpiled assertion and the result check (False where Python returns 
None); with both branches checked it passes.
   
   ---
   <sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of 
@holdenk.</sub>
   <!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk 
-->



##########
python/pyspark/sql/tests/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:
   Fixed in 50ee61864c3: the boundary orderings are now `(0, 1, 7)` and `(7, 1, 
0)`, so every triple value is in `_LONG_EDGES`.
   
   ---
   <sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of 
@holdenk.</sub>
   <!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk 
-->



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to