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


##########
python/pyspark/sql/transpile.py:
##########
@@ -844,60 +1096,44 @@ 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 rather than value 
comparisons,
+                # though one can be a link of a chain; they need their own 
NULL analysis: `in`
+                # semantics depend on the container -- equality for tuple/list,
+                # substring containment for str -- and a `None` probe can raise
+                # (`None in "abc"` -> TypeError). Not lowered yet, so refuse 
and
+                # fall back.
+                if any(isinstance(o, (ast.In, ast.NotIn)) for o in ops):
                     raise UnsupportedOperationException(
-                        "chained comparisons (e.g. `a < b < c`) are not 
supported by the transpiler"
+                        "`in` / `not in` is not supported by the transpiler; 
the "
+                        "UDF falls back to interpreted Python"
                     )
-                comp = comps[0]
-                match ops[0]:
-                    case ast.Is() | ast.IsNot():
-                        # Only lower `x is None` / `None is x` (and their
-                        # `is not` variants) to isNull/isNotNull. For any
-                        # other comparator (e.g. `x is 0`, `x is y`) Python
-                        # performs an object-identity check that has no SQL
-                        # equivalent, so we must fall back to interpreted
-                        # Python rather than silently emitting a null check.
-                        is_none_left = isinstance(left, ast.Constant) and 
left.value is None
-                        is_none_right = isinstance(comp, ast.Constant) and 
comp.value is None
-                        if not (is_none_left or is_none_right):
-                            raise UnsupportedOperationException(
-                                "`is`/`is not` is only supported when one "
-                                "operand is the literal None; other identity "
-                                "checks (e.g. `x is 0`, `x is y`) cannot be "
-                                "lowered to SQL and the UDF falls back to "
-                                "interpreted Python"
-                            )
-                        subject_node = comp if is_none_left else left
-                        subject_col = self._convert_chunk(params, subject_node)
-                        if isinstance(ops[0], ast.Is):
-                            return subject_col.isNull()
-                        else:
-                            return subject_col.isNotNull()
-                    case ast.Eq():
-                        return self._lower_eq(params, left, comp, equal=True)
-                    case ast.NotEq():
-                        return self._lower_eq(params, left, comp, equal=False)
-                    case ast.Lt():
-                        return self._lower_value_compare(
-                            params, left, comp, lambda l, r: l < r, "<"
-                        )
-                    case ast.LtE():
-                        return self._lower_value_compare(
-                            params, left, comp, lambda l, r: l <= r, "<="
-                        )
-                    case ast.Gt():
-                        return self._lower_value_compare(
-                            params, left, comp, lambda l, r: l > r, ">"
-                        )
-                    case ast.GtE():
-                        return self._lower_value_compare(
-                            params, left, comp, lambda l, r: l >= r, ">="
-                        )
-                    case _:
-                        raise UnsupportedOperationException(
-                            f"comparison operator {type(ops[0]).__name__} "
-                            "is not supported by the transpiler"
+                if len(ops) > _MAX_COMPARISON_OPS:
+                    raise UnsupportedOperationException(
+                        f"chained comparison has {len(ops)} operators; the "
+                        f"transpiler lowers at most {_MAX_COMPARISON_OPS}, so 
the "
+                        "UDF falls back to interpreted Python"
+                    )
+                # `a OP1 b OP2 c` is `(a OP1 b) and (b OP2 c)` with `b` 
evaluated
+                # once. Each operand is lowered once and its Column handed to 
both
+                # adjacent links; reading it twice is safe because SPARK-58626
+                # gives a repeated argument one column per row (before it,
+                # `50 < x < 60` over `rand(7) * 100` was ~30% true where 
Python is
+                # ~10%).
+                #
+                # The links fold to a sequential CASE WHEN rather than `&` (see
+                # the module docstring); every link is total, so no condition 
is
+                # NULL.
+                nodes = [left, *comps]
+                cols = [self._convert_chunk(params, n) for n in nodes]
+                return _short_circuit(

Review Comment:
   **Blocking (P1):** Under 
`spark.sql.experimental.optimizer.transpileNullStrictness=loose`, 
`_lower_value_compare` returns the bare comparison for an operand it cannot 
prove non-null, so an ordering link is NULL when an operand is NULL. This fold 
makes each earlier link the condition `NOT link`, and `CaseWhen` takes a branch 
only when its condition is true, in `eval` and in generated code alike, so a 
NULL earlier link falls through to the later links instead of propagating.
   
   Reading the lowering, `x < y < z` on (NULL, 1, 2) becomes `CASE WHEN NOT 
(NULL < 1) THEN false ELSE (1 < 2) END`, which is true, while `x < y and y < z` 
gives NULL and interpreted Python raises TypeError. `lo <= x <= hi` with a NULL 
`lo` is true, and `not (x < y < z)` and `1 if (x < y < z) else 0` give false 
and 1 where their `and` spellings give true and 0. The `and` / `or` arm takes 
the same fold in bodies that hold a chain or a comparison over a non-basic 
operand: `(0 < x < 10) and (y > 0)` on (NULL, 5) is true, and `((x > 0) and (y 
> 0)) == True` on (NULL, 5) is true where an `&` fold gives false. A UDF used 
as a filter keeps those rows.
   
   The fold relies on every link being total, as `_lower_compare_pair`'s 
docstring, `_is_never_null_boolean`'s Compare arm, the module docstring and 
this arm's comment say, but that holds only under the default strict setting, 
and no test runs a chain or a CASE WHEN `and` / `or` under loose. It takes the 
experimental transpiler with ANSI on and the non-default loose setting; under 
strict these rows raise as Python does.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/59216#discussion_r4260389154), 
[2](https://github.com/apache/spark/pull/59216#discussion_r4584336045).
   
   **Recommended change:** Under transpileNullStrictness=loose, fold chain 
links with `&` and every `and` / `or` with `&` / `|`, keeping the sequential 
CASE WHEN fold for strict; qualify the module docstring, the 
`_lower_compare_pair` and `_short_circuit` docstrings, 
`_is_never_null_boolean`'s Compare arm and the chain-arm comment so that link 
totality and the CASE WHEN fold are stated for strict null strictness; and add 
loose-mode chain and `and` / `or` cases to the UDF transpiler unit tests. 
Commit e8948f6e049 folded chain links with `&`, and 15ddee864b6 replaced that 
with the CASE WHEN fold so that optimizer rules cannot move a later link's NULL 
guard ahead of the links that gate it, a reason that holds only where links 
carry guards; start the loose path from e8948f6e049's `&` fold.
   
   **Why this works:** Under loose an ordering link carries no raise_error 
guard and is NULL for a NULL operand. `&` / `|` combine a NULL operand with 
three-valued logic, which is the result the setting documents and the result 
the `and` spelling of the same chain already gives, so a NULL earlier link no 
longer falls through to the later links. Under strict every link stays total, 
so the CASE WHEN fold keeps the guard ordering it was chosen for. `not` and 
if/ternary tests coalesce the value they receive, so they match the `and` 
spelling once the chain does.
   
   **Scope:** Choose the chain and `and` / `or` fold by null strictness in the 
Python UDF transpiler, state link totality as a strict-mode property, and 
cover, under loose null strictness in the transpiler unit tests, chains and the 
`and` / `or` of every body that takes the CASE WHEN fold.
   
   **Compatibility:** Strict-mode chain and `and` / `or` lowering, including 
the sequential CASE WHEN fold and its NULL guards, stays exactly as the change 
implements it.
   
   **Risks:** Under loose, chains and the `and` / `or` of bodies holding a 
chain or a comparison over a non-basic operand become splittable `And` / `Or` 
again: per-conjunct pushdown returns for them, and a `len()` NULL guard or an 
ANSI arithmetic error inside them is exposed to the BooleanSimplification and 
subexpression-elimination divergences the module docstring lists for the `&` / 
`|` fold, exactly as their `and` spelling already is. Strict mode is 
unaffected, and reverting restores the CASE WHEN fold, which returns wrong 
results under loose.
   
   **Constraints:** Strict null strictness keeps the sequential CASE WHEN fold, 
its NULL guards and its plans unchanged. The fold chosen for a body must follow 
the same `_null_strictness` value that `_lower_value_compare` uses for its 
links.
   
   **Exclusions:**
   - The BooleanSimplification and subexpression-elimination divergences of the 
`&` / `|` fold stay with the separately tracked optimizer fixes.
   
   **Success:** Under transpileNullStrictness=loose, `x < y < z` on (NULL, 1, 
2) returns NULL, as `x < y and y < z` does, and `(0 < x < 10) and (y > 0)` on 
(NULL, 5) returns NULL. Under loose, `not (x < y < z)` and `1 if (x < y < z) 
else 0` return the same values as their `and` spellings when an earlier operand 
is NULL. Under loose, an `and` / `or` in a body that holds a comparison over a 
non-basic operand but no chain returns the value of its `&` / `|` fold: `((x > 
0) and (y > 0)) == True` on (NULL, 5) returns False, not True. Under strict, 
every chained comparison and every `and` / `or` in a body holding a chain or a 
comparison over a non-basic operand lowers to the same sequential CASE WHEN as 
before and returns the same results. Every docstring or comment that states 
that comparison links are total says that it holds under strict null strictness.
   
   **Verification:**
   - **Regression:** Under loose null strictness, chains and the `and` / `or` 
of bodies holding a chain or a comparison over a non-basic operand, with a NULL 
operand in an earlier ordering comparison, return the same values as their `&` 
/ `|` spellings, directly, under `not`, as an if/ternary test and as an operand 
of `==`, under both generated and interpreted expression evaluation.
   - **Compatibility:** Under strict null strictness, chain and `and` / `or` 
lowering keeps its NULL-guard raises, its short-circuit results, its 
optimizer-shape results and its CASE WHEN plan shape.
   - **Inspection:** Every statement in the transpiler that comparison links 
are total, or that the CASE WHEN fold needs no NULL handling, is qualified as 
holding under strict null strictness.



##########
python/pyspark/sql/transpile.py:
##########
@@ -1596,6 +1849,10 @@ def _transpile_func(
                         )
                 except Exception as e:
                     errors.append(str(e))
+        # Every option is built each time the UDF is applied, before the JVM
+        # prunes them to the one matching the bound types, so bound their sum.
+        if refusal := too_heavy(len(transpiled)):

Review Comment:
   **Blocking (P1):** This check, like the one before lowering, applies to 
every body, including flat ones whose materialized size grows only linearly 
with their source. Each untyped parameter is tried as integer, float and 
string, so a body over three untyped parameters keeps up to 27 options, and 
their count multiplies a size that does not compound.
   
   Reading the code, `def f(a, b, c): return (a == 0 or ... or a == 229) and b 
is not None and c is not None` declared BooleanType weighs 3,704 and keeps 18 
options, so `too_heavy(18)` sees 66,672 and the UDF runs as an interpreted 
Python UDF, sending every row through a Python worker. The base branch has no 
bound and lowers the same 18 options natively, about 85,000 expanded nodes per 
application by the review's count. The check before lowering likewise refuses 
an `or` of about 4,100 `==` terms over annotated parameters, which the base 
branch lowered, while it accepts a 4,000-term one that expands to about 68,000 
nodes, so refusing these bodies guards against nothing the bound otherwise 
allows.
   
   `test_udf_transpile_many_flat_comparisons` says a body with no chained or 
nested comparison grows linearly, 'so no bound refuses it', but it uses one 
untyped parameter (two options), so no test covers this.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/59216#discussion_r4507366754), 
[2](https://github.com/apache/spark/pull/59216#discussion_r4507366797).
   
   **Recommended change:** Alongside the weight, determine whether a body's 
expansion compounds, that is, whether an operand that a lowering reads more 
than once (an `==` / `!=` or ordering comparison, the divisor of `%`, the 
argument of `len`) itself contains such a lowering, and apply both size checks 
only to bodies whose expansion compounds; keep the 64-operator chain cap for 
every body, and update the `_MAX_MATERIALIZED_WEIGHT` comment and the UDF 
transpiler plan-growth tests to cover flat bodies with several untyped 
parameters. Commit f9072281319 added the check over the kept options, stating 
that every option is built on each application; that holds for every body, but 
only a compounding body's size multiplies per nesting level.
   
   **Why this works:** A lowering that reads a leaf or linear operand several 
times adds a constant per term, so a flat body's materialized size stays 
proportional to its source for any number of options, as on the base branch; 
only an operand that itself reads its operands several times multiplies the 
size per level. Applying the checks to compounding bodies refuses exactly the 
shapes whose expansion explodes (nested comparisons, ternary-routed nests, `%` 
and `len` nests), while flat bodies keep every option they lowered on the base 
branch.
   
   **Scope:** Restrict the materialized-size checks in the Python UDF 
transpiler to bodies whose expansion compounds, and cover flat many-option 
bodies alongside the existing nested refusals in the transpiler unit tests.
   
   **Compatibility:** Nested comparison bodies, ternary-routed nests and `%` or 
`len` nests stay refused, before lowering or after counting options, exactly as 
the change implements.
   
   **Risks:** Flat bodies are again unbounded, as on the base branch: one 
application converts every kept option, so a flat body of N comparisons with 27 
options converts roughly 27 x 16N nodes; restoring the unconditional check 
rolls this back.
   
   **Constraints:** Every shape the caps test expects to refuse (right-nested 
and chain-nested comparisons, ternary-routed nests, the `%` and `len` nests, 
the NaN-guarded nest and the many-options body) must still be refused with the 
weight message, and every shape it expects to lower must still lower. The 
compounding test must recognize every lowering `_materialized_weight` charges 
more than once per operand and look through every operand route that can hide 
one, such as ternary branches and tests, `not`, `and` / `or` and arithmetic.
   
   **Success:** `(a == 0 or ... or a == 229) and b is not None and c is not 
None` over three untyped parameters keeps its 18 options and lowers natively, 
as on the base branch, and a typed flat body of several thousand comparisons 
lowers too. Every body whose expansion compounds is still refused when one 
option's weight, or that weight times the options kept, passes 65,536. The 
`_MAX_MATERIALIZED_WEIGHT` comment, and the flat-body test's statement that no 
bound refuses a body with no chained or nested comparison, describe what the 
code does.
   
   **Verification:**
   - **Regression:** Flat bodies with no nested multi-read lowering that the 
base branch lowered, including an `or` of a few hundred `==` terms over three 
untyped parameters and a typed body of several thousand comparisons, keep their 
options and run with no Python evaluation node, returning Python's answers.
   - **Compatibility:** Every nested shape past the bound (right-nested and 
chain-nested comparisons, ternary-routed nests, `%` and `len` nests, the 
NaN-guarded nest and the many-options body) is still refused with the weight 
message, and the shapes expected to lower still lower.



##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -1084,25 +1489,70 @@ 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.
-        import warnings as _warnings
-
-        from pyspark.sql.types import StructField, StructType
+        # Python's `None and x` short-circuits to None, which Spark's 
three-valued
+        # `null AND false` (false) does not reproduce. An operand before the 
last
+        # that `_is_never_null_boolean` cannot prove non-NULL -- a literal 
None, or
+        # a ternary with a None branch -- must fall back rather than diverge, 
and
+        # so must a literal None in last position.
+        long_schema = "a long"
 
         def none_and(x):
             return None and (x > 0)
 
-        long_schema = StructType([StructField("a", LongType(), nullable=True)])
+        def and_none(x):
+            return (x > 0) and None
+
+        def nullable_ternary_and(x):
+            return (True if x > 0 else None) and (x > 0)
+
+        def nullable_ternary_body_and(x):
+            return (None if x > 0 else True) and (x < 0)
+
         with self.sql_conf(_TRANSPILE_ON):
-            with _warnings.catch_warnings(record=True):
-                _warnings.simplefilter("always")
-                pudf = UserDefinedFunction(none_and, BooleanType())
-            self.assertEqual([], pudf.transpiled, "literal None in and/or must 
not transpile")
-            df = self.spark.createDataFrame([Row(a=-5)], schema=long_schema)
-            [result] = df.select(pudf("a")).collect()
-            self.assertIsNone(result[0])
+            # Python returns None for x = 5 where an `&` fold would say False.
+            for func, value in [

Review Comment:
   **Nit (P3):** Now that the gate lets the last `and` / `or` operand be NULL, 
`_is_never_null_boolean`'s BoolOp arm is the only thing that refuses a nested 
`and` / `or` ending in a possibly-NULL operand when it is used before the last 
operand; such an operand is NULL whenever its own last operand is. None of 
these cases has that shape, and 
`test_udf_transpile_nullable_last_boolop_operand` covers only bodies that 
should lower. If the arm were relaxed to mirror the gate, `((x > 0) and (True 
if y > 0 else None)) and (z > 0)` would lower to an `&` fold that returns False 
for (1, -1, -1), where Python returns None, and both tests would still pass. A 
case such as `((x > 0) and (True if x > 5 else None)) and (x > 10)`, probed at 
x = 1 where Python returns None and an `&` fold returns False, would give the 
arm a failure signal.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59216#discussion_r4584336073).
   
   **Verification:**
   - **Regression:** With `_is_never_null_boolean`'s BoolOp arm relaxed to 
mirror the `and` / `or` gate, the nested case transpiles and returns False 
where Python returns None, so the test fails; as written it falls back and 
returns None.



##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -549,39 +550,443 @@ 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.
-        import warnings as _warnings
+    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.
+        B = BooleanType()
+        chain3 = lambda a, b, c: a < b < c  # noqa: E731
+        chain4 = lambda a, b, c, d: a < b < c < d  # noqa: E731
+        abc, abcd = "a long, b long, c long", "a long, b long, c long, d long"
+        for factory_mode in ("FALLBACK", "NO_CODEGEN"):
+            conf = {"spark.sql.codegen.factoryMode": factory_mode}
+            with self.subTest(factory_mode=factory_mode), self.sql_conf(conf):
+                # An earlier link is false, so the NULL in a later one is never
+                # evaluated -- from the first link, and from an interior one.
+                self.assertEqual(self._vals(chain3, B, abc, [(1, 0, None)]), 
[False])
+                self.assertEqual(self._vals(chain4, B, abcd, [(1, 2, 1, 
None)]), [False])
+                # ... but when every earlier link IS true the last one is 
reached
+                # and its NULL guard fires, exactly as Python raises TypeError.
+                with self.assertRaisesRegex(Exception, "cannot compare NULL"):
+                    self._vals(chain3, B, abc, [(0, 1, None)])
+                with self.assertRaisesRegex(Exception, "cannot compare NULL"):
+                    self._vals(chain4, B, abcd, [(1, 2, 3, None)])
+
+    def test_udf_transpile_chain_survives_optimizer(self):
+        # A chain folds to a sequential CASE WHEN, and so do the `and` / `or` 
of a
+        # body holding a chain or a comparison over a non-basic operand. That 
fold
+        # is atomic to `splitConjunctivePredicates` and 
`BooleanSimplification`;
+        # an `&` / `|` fold lets BooleanSimplification move a later operand's 
NULL
+        # guard ahead of the operands that gate it, or drop one, as it still 
does
+        # for the `and` / `or` bodies that keep `&` / `|` (see the module
+        # docstring). Each body must return Python's answer, or raise like
+        # Python, fully lowered, under generated and interpreted evaluation.
+        abc = "a long, b long, c long"
+        # Common factor: `(p && g) || (q && g) => g && (p || q)` hoists the 
shared
+        # guarded operand to the front, where its NULL raises.
+        factor_chains = lambda a, b, c, d: (a < b < c) or (d < b < c)  # noqa: 
E731
+
+        def factor_and(a, b):
+            return (0 <= a <= 10 and b > 0) or (20 <= a <= 30 and b > 0)
+
+        def factor_nested(a, b, c):
+            return ((b > 0 and a > 0) or (c > 0 and a > 0)) == True  # noqa: 
E712
+
+        # Absorption: `(p && g) || g => g` drops the guard in `p`, returning 
True
+        # where Python raises.
+        absorb_chain = lambda a, b, c: (a < b < c) or (b < c)  # noqa: E731
+        absorb_and = lambda a, b: (0 <= a <= 10 and b > 0) or (b > 0)  # noqa: 
E731
+        # (body, schema, row, Python's answer or None where Python raises 
TypeError)
+        cases = [
+            (factor_chains, abc + ", d long", (5, 1, None, 7), False),
+            (factor_and, "a long, b long", (15, None), False),
+            (factor_nested, abc, (None, -1, -1), False),
+            (absorb_chain, abc, (None, 0, 1), None),
+            (absorb_and, "a long, b long", (None, 5), None),
+        ]
+        for factory_mode in ("FALLBACK", "NO_CODEGEN"):
+            conf = {**_TRANSPILE_ON, "spark.sql.codegen.factoryMode": 
factory_mode}
+            for i, (func, schema, row, expected) in enumerate(cases):
+                with self.subTest(factory_mode=factory_mode, case=i), 
self.sql_conf(conf):
+                    df = self.spark.createDataFrame([row], schema)
+                    projected = df.select(self._transpiled_udf(func, 
BooleanType())(*df.columns))
+                    self.assertEqual(0, self._eval_python_count(projected), 
"must stay lowered")
+                    if expected is None:
+                        with self.assertRaisesRegex(Exception, "cannot compare 
NULL"):
+                            projected.collect()
+                    else:
+                        self.assertEqual([expected], [r[0] for r in 
projected.collect()])
 
-        from pyspark.sql.types import StructField, StructType
+        # A chain as a filter over an Aggregate: the group (b=1, c=NULL, sa=6) 
has
+        # `sa < b` false, so Python never touches `b < c`. Since SPARK-60633 
an `&`
+        # fold passes this too; it pins the chain over an aggregate.
+        from pyspark.sql.functions import sum as sum_
 
-        def chained(x):
-            return 0 < x < 10
+        with self.sql_conf(_TRANSPILE_ON):
+            chain_over_agg = lambda sa, b, c: sa < b < c  # noqa: E731
+            udf = self._transpiled_udf(chain_over_agg, BooleanType())
+            agg = (
+                self.spark.createDataFrame([(1, 1, None), (5, 1, None), (2, 2, 
3)], abc)
+                .groupBy("b", "c")
+                .agg(sum_("a").alias("sa"))
+            )
+            filtered = agg.filter(udf("sa", "b", "c"))
+            self.assertEqual([], filtered.select("b", "c").collect())
+            self.assertEqual(0, self._eval_python_count(filtered), "chain must 
stay lowered")
+
+    def test_udf_transpile_and_or_fold_choice(self):
+        # Only a body that holds a chain or a comparison over a non-basic 
operand
+        # takes the CASE WHEN fold for its `and` / `or`; every other body keeps
+        # `&` / `|`, and with it per-conjunct pushdown.
+        import ast as _ast
 
-        schema = StructType([StructField("a", LongType(), nullable=False)])
-        with self.sql_conf(
-            {
-                "spark.sql.experimental.optimizer.transpilePyUDFs": True,
-                "spark.sql.ansi.enabled": True,
-            }
+        from pyspark.sql.transpile import _needs_atomic_boolops
+
+        for src, atomic in [
+            ("a > 0 and c > 0", False),
+            ("(a == 1 or a == 2) and not (c < 0)", False),
+            ("(0 < a < 10) and c > 0", True),
+            ("((a > 0 and c > 0) or c > 1) == True", True),
+            ("(a if c > 0 else 1) == 1 and c > 0", True),
+        ]:
+            with self.subTest(src=src):
+                self.assertEqual(atomic, _needs_atomic_boolops(_ast.parse(src, 
mode="eval")))
+
+        df = self.spark.createDataFrame([(1, 2)], "a long, c long")
+        with self.sql_conf(_TRANSPILE_ON):
+            plain = lambda a, c: a > 0 and c > 0  # noqa: E731
+            chained = lambda a, c: (0 < a < 10) and c > 0  # noqa: E731
+            for func, splittable in [(plain, True), (chained, False)]:
+                udf = self._transpiled_udf(func, BooleanType())
+                plan = self._optimized_plan(df.select(udf("a", "c")))
+                self.assertEqual(splittable, " AND " in plan, plan)
+
+    def test_udf_transpile_boolop_short_circuits(self):
+        # The `and` / `or` counterpart of the chain short-circuit: a NULL 
guard in
+        # the second operand must not fire when the first already decided the
+        # result.
+        def both_positive(a, c):
+            return a > 0 and c > 0
+
+        def either_positive(a, c):
+            return a > 0 or c > 0
+
+        # Under both factory modes, so `And` / `Or`'s `doGenCode` and `eval`
+        # laziness are both covered (see 
test_udf_transpile_chain_short_circuits).
+        B, schema = BooleanType(), "a long, c long"
+        for factory_mode in ("FALLBACK", "NO_CODEGEN"):
+            conf = {"spark.sql.codegen.factoryMode": factory_mode}
+            with self.subTest(factory_mode=factory_mode), self.sql_conf(conf):
+                self.assertEqual(self._vals(both_positive, B, schema, [(-5, 
None)]), [False])
+                self.assertEqual(self._vals(either_positive, B, schema, [(5, 
None)]), [True])
+
+        # The same across a join, with the NULL operand entirely on the right
+        # side: the regression test for SPARK-58627. Before `RaiseError` 
overrode
+        # `Expression.throwable`, `splitConjunctivePredicates` decomposed the
+        # `And` and `PushPredicateThroughJoin` pushed the guard to one side of 
the
+        # join, where it fired on rows Python short-circuits past.
+        # BooleanSimplification and subexpression elimination, listed in the
+        # module docstring, remain open. No AQE and no broadcast, so the
+        # pushed-down guard either exists or does not, rather than racing AQE
+        # eliminating the empty join.
+        deterministic = {
+            **_TRANSPILE_ON,
+            "spark.sql.adaptive.enabled": False,
+            "spark.sql.autoBroadcastJoinThreshold": -1,
+        }
+        with self.sql_conf(deterministic):
+            and_udf = self._transpiled_udf(both_positive, B)
+            left = self.spark.createDataFrame([(1, -5)], "k long, a long")
+            right = self.spark.createDataFrame([(1, None)], "k long, c long")
+            joined = left.join(right, "k")
+            # Results alone do not prove the lowering ran -- interpreted Python
+            # returns the same -- so also assert zero EvalPython nodes.
+            joined_select = joined.select(and_udf("a", "c"))
+            self.assertEqual([False], [r[0] for r in joined_select.collect()])
+            self.assertEqual(0, self._eval_python_count(joined_select), 
"joined select lowered")
+            filtered = joined.filter(and_udf("a", "c"))
+            self.assertEqual([], filtered.select("k").collect())
+            self.assertEqual(0, self._eval_python_count(filtered), "joined 
filter lowered")
+
+    def test_udf_transpile_chain_operator_mix_and_eq_nulls(self):
+        # Mixed operators in one chain, and `x == y == z` over every NULL 
pattern.
+        # Equality never raises in Python (`None == None` is True, `None == 0` 
is
+        # False), so every pattern has a defined answer to match exactly.
+        B = BooleanType()
+        chained_eq = lambda a, b, c: a == b == c  # noqa: E731
+
+        # (a, b, c, expected) -- every NULL pattern plus value cases.
+        eq_cases = [
+            (None, None, None, True),
+            (None, None, 1, False),
+            (None, 1, None, False),
+            (None, 1, 2, False),
+            (1, None, None, False),
+            (1, None, 2, False),
+            (1, 2, None, False),
+            (1, 1, None, False),
+            (1, 1, 1, True),
+            (1, 1, 2, False),
+            (1, 2, 3, False),
+        ]
+        self.assertEqual(
+            self._vals(chained_eq, B, "a long, b long, c long", [c[:3] for c 
in eq_cases]),
+            [c[3] for c in eq_cases],
+            "a == b == c over the NULL patterns",
+        )
+
+        # Operator mixes, on non-NULL rows so the ordering guards stay quiet.
+        lt_eq = lambda a, b, c: a < b == c  # noqa: E731
+        eq_lt = lambda a, b, c: a == b < c  # noqa: E731
+        gt_gte = lambda a, b, c: a > b >= c  # noqa: E731
+        lte_lte = lambda a, b, c: a <= b <= c  # noqa: E731
+        four_ops = lambda a, b, c, d, e: a < b < c < d < e  # noqa: E731
+        for label, func, rows, expected in [
+            ("a < b == c", lt_eq, [(1, 2, 2), (1, 2, 3), (2, 1, 1)], [True, 
False, False]),
+            ("a == b < c", eq_lt, [(1, 1, 2), (1, 1, 0), (1, 2, 3)], [True, 
False, False]),
+            ("a > b >= c", gt_gte, [(3, 2, 2), (3, 2, 5), (1, 2, 2)], [True, 
False, False]),
+            ("a <= b <= c", lte_lte, [(1, 1, 2), (1, 2, 2), (2, 1, 3)], [True, 
True, False]),
+        ]:
+            with self.subTest(func=label):
+                self.assertEqual(
+                    self._vals(func, B, "a long, b long, c long", rows), 
expected, label
+                )
+        self.assertEqual(
+            self._vals(
+                four_ops,
+                B,
+                "a long, b long, c long, d long, e long",
+                [(1, 2, 3, 4, 5), (1, 2, 3, 5, 4)],
+            ),
+            [True, False],
+            "a chain of four operators is well under the cap and must 
transpile",
+        )
+
+    def test_udf_transpile_comparison_fallbacks(self):
+        # Comparison forms the transpiler must REFUSE. Each case asserts both 
that
+        # nothing transpiled and that a query using the UDF still returns 
Python's
+        # answer. The second half matters because an option that survives is
+        # type-checked by CheckAnalysis as a child of TranspiledPythonUDF: a
+        # half-refused form would fail the whole query rather than fall back, 
so
+        # "did not transpile" alone is not enough to prove the fallback works.
+        #
+        # `in` / `not in` are refused wholesale, so those cases all take the 
same
+        # branch; they are kept because the reasons differ. `in` on a str is
+        # substring containment rather than equality, a container of runtime
+        # values would need runtime NULL analysis, and `in` can appear as a 
link
+        # in a chain (`a < b in (1, 2)` is one Compare), which the refusal also
+        # covers. Membership needs its own NULL analysis and is deferred to its
+        # own ticket (SPARK-56925 is the unrelated bare-`if` truthiness work).
+        str_in = lambda x: x in "abc"  # noqa: E731
+        runtime_in = lambda x, y: x in (y, 2)  # noqa: E731
+        chained_in = lambda a, b: a < b in (1, 2)  # noqa: E731
+        # Short-circuits for non-positive inputs.
+        cross_chain = lambda x: 0 < x < "z"  # noqa: E731
+        # Boolean bodies declared LongType return NULL through interpreted 
Python.
+        chain_long_rt = lambda x: 0 < x < 10  # noqa: E731
+        in_long_rt = lambda x: x in (1, 2)  # noqa: E731
+
+        B, L = BooleanType(), LongType()
+        # (func, return type, schema, rows, what interpreted Python produces)
+        cases = [
+            (str_in, B, "a string", [("b",), ("z",)], [True, False]),
+            (runtime_in, B, "a long, b long", [(1, 1), (3, 5)], [True, False]),
+            (chained_in, B, "a long, b long", [(0, 1), (1, 0)], [True, False]),
+            (cross_chain, B, "a long", [(0,)], [False]),
+            (chain_long_rt, L, "a long", [(0,)], [None]),
+            (in_long_rt, L, "a long", [(0,)], [None]),
+        ]
+        with self.sql_conf(_TRANSPILE_ON):
+            for i, (func, return_type, schema, rows, expected) in 
enumerate(cases):
+                with self.subTest(case=i):
+                    pudf, _ = self._fallback_reason(func, return_type)
+                    df = self.spark.createDataFrame(rows, schema)
+                    self.assertEqual(
+                        [r[0] for r in 
df.select(pudf(*df.columns)).collect()], expected
+                    )
+
+    def test_udf_transpile_boolean_body_requires_boolean_return_type(self):
+        # A comparison body is boolean whatever its operands look like, so it 
must
+        # not satisfy a numeric declared return type. `_is_definitely_boolean` 
says
+        # False for a comparison over a ternary / comparison / boolean op (it 
also
+        # demands basic-type operands), and those used to fall through 
`_category`'s
+        # numeric catch-all: `_transpile_from_ast` then accepted `LongType` 
and the
+        # option returned `cast(<boolean> as bigint)` -- 1 or 0 -- where the
+        # interpreted path returns NULL. `_category` now classifies every
+        # `ast.Compare` as "bool" directly.
+        def ternary_compare(c, x, y):
+            return (x if c > 0 else y) == 1
+
+        def eq_true(a, b):
+            return (a < b) == True  # noqa: E712
+
+        def compare_of_compares(a, b, c):
+            return (a < b) <= (b < c)
+
+        cases = [
+            (ternary_compare, "c long, x long, y long", (1, 1, 9)),
+            (eq_true, "a long, b long", (1, 2)),
+            (compare_of_compares, "a long, b long, c long", (1, 2, 3)),
+        ]
+        for func, schema, row in cases:
+            with self.subTest(func=func.__name__), 
self.sql_conf(_TRANSPILE_ON):
+                # Declared LongType it falls back, and the interpreted path
+                # returns NULL for a bool.
+                pudf, _ = self._fallback_reason(func, LongType())
+                df = self.spark.createDataFrame([row], schema)
+                self.assertEqual([None], [r[0] for r in 
df.select(pudf(*df.columns)).collect()])
+                # Declared BooleanType it runs natively and keeps its NULL 
guard.
+                self.assertEqual(self._vals(func, BooleanType(), schema, 
[row]), [func(*row)])
+                with self.assertRaisesRegex(Exception, "cannot compare NULL"):
+                    self._vals(func, BooleanType(), schema, [(None, *row[1:])])
+
+    def test_udf_transpile_lowering_caps(self):
+        # The bounds on comparison lowering: the per-chain operator cap, and 
the
+        # materialized size of everything one application of the UDF builds.
+        import ast as _ast
+
+        from pyspark.sql.transpile import (
+            _MAX_COMPARISON_OPS,
+            _MAX_MATERIALIZED_WEIGHT,
+            CatalystTranspiler,
+            _materialized_weight,
+        )
+
+        weight_msg = f"more than {_MAX_MATERIALIZED_WEIGHT}"
+
+        def weight(src):
+            return _materialized_weight(_ast.parse(src, mode="eval").body)
+
+        def build(src, params="x"):
+            func = self._function_from_source(f"def f({params}):\n    return 
{src}\n")
+            return self._udf_and_warnings(func, BooleanType())
+
+        def chain(n):
+            # n operators over n + 1 operands: x < 0 < 1 < ... < n - 1
+            return " < ".join(["x"] + [str(i) for i in range(n)])
+
+        def right_nested(depth, leaf="(x < 0)", op="<"):
+            # ONE operand of a single comparison per level: 2d + 1 links but 
~2^d
+            # materialized nodes, since a link reads each operand Column twice
+            # (four times for `==`) and the JVM converter does not memoize.
+            src = leaf
+            for _ in range(depth):
+                src = f"{leaf} {op} ({src})"
+            return src
+
+        def chain_nested(depth):
+            src = "(x < 0)"
+            for _ in range(depth):
+                src = f"((x < 0) < {src} < (x < 0))"
+            return src
+
+        lowers = [
+            chain(_MAX_COMPARISON_OPS),
+            right_nested(2),
+            chain_nested(2),
+            # One level over a ternary.
+            "(x < 0) < ((x < 1) if x > 0 else (x < 2))",
+            # `is None` reads only its subject, so an identity nest stays 
linear.
+            "(" * 20 + "x < 0" + ") is None" * 20,
+        ]
+        # The nest routed through a ternary: its Column is read as often as any
+        # other operand, in each of its three positions.
+        ternary_nests = []
+        for shape in (
+            "(x < 0) {op} (True if ({inner}) else False)",
+            "(x < 0) {op} (({inner}) if x > 0 else (x < 0))",
+            "(x < 0) {op} ((x < 0) if x > 0 else ({inner}))",
         ):
-            with _warnings.catch_warnings(record=True) as caught:
-                _warnings.simplefilter("always")
-                pudf = UserDefinedFunction(chained, BooleanType())
-            self.assertEqual([], pudf.transpiled, "chained comparison must NOT 
transpile")
-            fallback = [
-                w
-                for w in caught
-                if "Unable to transpile" in str(w.message) or "Errors 
encountered" in str(w.message)
-            ]
-            self.assertTrue(fallback, "expected a fallback warning")
-            for value, expected in [(5, True), (0, False), (10, False), (-3, 
False)]:
-                with self.subTest(value=value):
-                    df = self.spark.createDataFrame([Row(a=value)], 
schema=schema)
-                    [row] = df.select(pudf("a")).collect()
-                    self.assertEqual(row[0], expected)
+            for op in ("<", "=="):
+                src = "(x < 0)"
+                for _ in range(20):
+                    src = shape.format(op=op, inner=src)
+                ternary_nests.append(src)
+        # Modulo reads its divisor five times and `len` its argument twice.
+        modulo = "x"
+        for _ in range(10):
+            modulo = f"x % ({modulo})"
+        too_heavy = [
+            right_nested(20),
+            right_nested(20, "(x == 1)", "=="),
+            chain_nested(10),
+            *ternary_nests,
+            f"({modulo}) > 0",
+            f"len('a' if ({right_nested(9)}) else 'b') > 0",
+        ]
+        with self.sql_conf(_TRANSPILE_ON):
+            for src in lowers:
+                with self.subTest(src=src[:40]):
+                    u, reasons = build(src)
+                    self.assertTrue(u.transpiled, reasons)
+            u, reasons = build(chain(_MAX_COMPARISON_OPS + 1))
+            self.assertEqual([], u.transpiled)
+            self.assertIn("operators", reasons)
+            for src in too_heavy:
+                with self.subTest(src=src[:40]):
+                    u, reasons = build(src)
+                    self.assertEqual([], u.transpiled)
+                    self.assertIn(weight_msg, reasons)
+
+            # A NaN-guarded `==` reads each operand four times. Charged three, 
this
+            # nest weighs under the bound while every float option expands 
past it.
+            nan_nest = "x == z"
+            for _ in range(7):
+                nan_nest = f"(x if ({nan_nest}) else y) == z"
+            u, reasons = build(nan_nest, "x, y, z")

Review Comment:
   **Nit (P3):** This nest and the `len('a' if (...) else 'b') > 0` body above 
are both built over untyped parameters. At the current charges the check before 
lowering refuses them (weights 502,438 and 69,566). By the review's reading of 
the weight model, with `==` charged three reads the nest passes that check and 
nine options lower, and with `len` charged one read the `len` body passes and 
two lower; the check over kept options then refuses each with the same 'more 
than 65536' message. `assertEqual([], u.transpiled)` and `assertIn(weight_msg, 
reasons)` pass either way, so neither case pins the charge its comment 
describes.
   
   Building them over annotated parameters, `x: float, y: float, z: float` for 
the nest and `x: int` for the `len` body, leaves one option, which is refused 
at the current charges and lowers once its own charge is lowered, so each case 
would fail as intended.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59216#discussion_r4507366799).
   
   **Verification:**
   - **Regression:** With `==` / `!=` charged three reads, the NaN-guarded `==` 
nest built over float parameters lowers and the case fails; with `len` charged 
one read, the `len` body over an integer parameter lowers and the case fails.
   - **Behavior:** At the current charges both single-option cases are refused 
with the materialized-weight message.



##########
python/pyspark/sql/transpile.py:
##########
@@ -1596,6 +1849,10 @@ def _transpile_func(
                         )
                 except Exception as e:
                     errors.append(str(e))
+        # Every option is built each time the UDF is applied, before the JVM
+        # prunes them to the one matching the bound types, so bound their sum.
+        if refusal := too_heavy(len(transpiled)):

Review Comment:
   **Nit (P3):** The NULL-guard UserWarning is published inside 
`_transpile_from_ast` as each variant finishes lowering, while this check runs 
only after every variant has lowered and then discards them all. A refused body 
therefore still says that 'the transpiled UDF includes a NULL guard that raises 
at runtime' and suggests `is not None` guards, beside 'Unable to transpile 
UDF'. For example, `((((((x > 0) == (y > 1)) == (x > 2)) == (y > 3)) == (x > 
4)) == (y > 5))` over two untyped parameters weighs 25,249, lowers four options 
that each emit the warning, and is then refused at 100,996; the caps test's 
`many_options` body emits 18 such warnings before its refusal. On the base 
branch every variant that warned was kept, so the warning always described a 
transpiled option.
   
   Recording whether each lowered variant emitted a guard, as 
`_null_guard_emitted` already tracks, and publishing the warning from 
`_transpile_func` after this check, only when a kept option carries a guard, 
keeps the warning accurate.
   
   **Verification:**
   - **Regression:** Building a UDF that the post-lowering size check refuses 
after its variants lowered NULL guards emits no NULL-guard warning, only the 
fallback warning naming the refusal.
   - **Compatibility:** A transpiled UDF whose kept option guards a nullable 
ordering operand or `len` argument still warns about the NULL guard, and one 
with no guard does not.



##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -1084,25 +1489,70 @@ 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.
-        import warnings as _warnings
-
-        from pyspark.sql.types import StructField, StructType
+        # Python's `None and x` short-circuits to None, which Spark's 
three-valued
+        # `null AND false` (false) does not reproduce. An operand before the 
last
+        # that `_is_never_null_boolean` cannot prove non-NULL -- a literal 
None, or
+        # a ternary with a None branch -- must fall back rather than diverge, 
and
+        # so must a literal None in last position.
+        long_schema = "a long"
 
         def none_and(x):
             return None and (x > 0)
 
-        long_schema = StructType([StructField("a", LongType(), nullable=True)])
+        def and_none(x):
+            return (x > 0) and None
+
+        def nullable_ternary_and(x):
+            return (True if x > 0 else None) and (x > 0)
+
+        def nullable_ternary_body_and(x):
+            return (None if x > 0 else True) and (x < 0)
+
         with self.sql_conf(_TRANSPILE_ON):
-            with _warnings.catch_warnings(record=True):
-                _warnings.simplefilter("always")
-                pudf = UserDefinedFunction(none_and, BooleanType())
-            self.assertEqual([], pudf.transpiled, "literal None in and/or must 
not transpile")
-            df = self.spark.createDataFrame([Row(a=-5)], schema=long_schema)
-            [result] = df.select(pudf("a")).collect()
-            self.assertIsNone(result[0])
+            # Python returns None for x = 5 where an `&` fold would say False.

Review Comment:
   **Nit (P3):** This comment now sits above four cases but describes only the 
last one. `none_and` and `nullable_ternary_and` are probed at x = -5, and at x 
= 5 `(x > 0) and None` is NULL under `&` just as Python returns None, so 
`and_none` falls back only because a literal None last operand has no boolean 
type. Wording such as 'Each case is probed where Python returns None; an `&` 
fold would return False there for every case but `and_none`, which falls back 
because a literal None last operand has no boolean type' would match the table.
   
   **Verification:**
   - **Inspection:** The comment describes, for every case in the table, a 
probe where Python returns None and why the case falls back, including the 
literal-None last operand.



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