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


##########
python/pyspark/sql/transpile.py:
##########
@@ -568,13 +643,18 @@ def _category_uncached(self, params: List[str], node: 
ast.AST) -> str:
                 if isinstance(op, ast.Mult):
                     if _is_numeric_cat(lc) and _is_numeric_cat(rc):
                         return _wider_numeric(lc, rc)
-                    # repeat(str, n): second operand must be integral (not 
float).
-                    # Python raises TypeError for `str * float`, so we allow 
only
-                    # "integer" or the legacy "numeric" catch-all (which the 
JVM
-                    # will validate against the actual column type at query 
time).
-                    if lc == "string" and rc in ("integer", "numeric"):
+                    # Python's bool repeat counts are integers too. A lowered
+                    # comparison always produces a non-null bool, so casting it
+                    # to int preserves that behavior.
+                    if lc == "string" and (
+                        rc in ("integer", "numeric")
+                        or (rc == "bool" and isinstance(right, ast.Compare))

Review Comment:
   **Blocking (P1):** This accepts any comparison as a repeat count, not only 
the `len()` comparisons whose category this change moved from numeric to 
`'bool'`. So counts the base branch refused now lower too: running the base and 
head `transpile.py` with stubbed Column builders, `def f(s, x): return s * (x > 
1)` goes from no transpiled option to string/integer and string/float options, 
and `(x >= y) * s` and `word + 's' * (n != 1)` lower as well. On the base 
branch these UDFs ran as interpreted Python with Python's results. Once 
lowered, a row with a NULL `s` gets NULL from `repeat(NULL, 1)` where Python 
raises TypeError for `None * True`. The float option evaluates Spark's `NaN > 
1` as true, so ('ab', NaN) gives 'ab' where Python gives ''. The earlier 
suggestion to accept every comparison count assumed their results match Python, 
which holds only for non-NULL strings and, for ordering comparisons, only 
without NaN. The mirrored arm in `_convert_chunk` has the same check.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59978#discussion_r4466812391).
   
   See **Shared repair plan 1** in the review body.



##########
python/pyspark/sql/transpile.py:
##########
@@ -841,9 +946,15 @@ def _convert_chunk(self, params: List[str], body: ast.AST 
| None) -> Column:
                     case ast.Mult():
                         if _is_numeric_cat(lc) and _is_numeric_cat(rc):
                             return left_col.__mul__(right_col)
-                        if lc == "string" and rc in ("integer", "numeric"):
+                        if lc == "string" and (
+                            rc in ("integer", "numeric")
+                            or (rc == "bool" and isinstance(right, 
ast.Compare))

Review Comment:
   **Blocking (P1):** Only a bare comparison passes this check, but a ternary 
whose branches are both `len()` comparisons is now categorized `'bool'` too, 
because each branch is. So `def f(s, flag): return s * ((len(s) > 1) if flag 
else (len(s) > 2))` reaches the type-compatibility raise in every input-type 
variant and gets no transpiled option. The same happens with a comparison test 
such as `n > 0`, and with nested ternaries. The base branch lowered these 
natively to `repeat(s, CAST(CASE WHEN ... END AS INT))`: the truthiness test 
treats a NULL `flag` as false, and the `len()` guards raise for a NULL `s` 
where Python's `len(None)` does. Now every row is sent to a Python worker. 
Results are unchanged, except that a float comparison test on a NaN row now 
takes Python's branch. A ternary count with a `None` branch should keep falling 
back, as `repeat_ternary` pins.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59978#discussion_r4466812391).
   
   See **Shared repair plan 1** in the review body.



##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -2750,6 +2750,406 @@ def 
test_udf_transpile_int_float_annotation_categories(self):
         self.assertEqual(len(combos_u), 3)
         self.assertEqual({c[0] for c in combos_u}, {"integer", "float", 
"string"})
 
+    def test_udf_transpile_null_narrowing_skips_null_guard(self):
+        def statement_guard_gt(x):
+            if x is not None:
+                return x > 0
+            return None
+
+        def ternary_guard_gt(x):
+            return (x > 0) if x is not None else None
+
+        def ternary_guard_and_lt(a, b):
+            return (a < b) if a is not None and b is not None else None
+
+        def reversed_guard_gt(x):
+            return (x > 0) if None is not x else None
+
+        def reversed_none_guard(x):
+            return None if None is x else x > 0
+
+        def elif_guard(x):
+            if x is None:
+                return None
+            elif x > 0:
+                return True
+            else:
+                return False
+
+        cases = [
+            ("statement_guard_gt", statement_guard_gt),
+            ("ternary_guard_gt", ternary_guard_gt),
+            ("ternary_guard_and_lt", ternary_guard_and_lt),
+            ("reversed_guard_gt", reversed_guard_gt),
+            ("reversed_none_guard", reversed_none_guard),
+            ("elif_guard", elif_guard),
+        ]
+        with self.sql_conf(_TRANSPILE_ON):
+            for name, func in cases:
+                with self.subTest(func=name):
+                    u, warnings_text = self._udf_and_warnings(func, 
BooleanType())
+                    self.assertTrue(u.transpiled, f"{name} did not transpile: 
{warnings_text}")
+                    self.assertNotIn("NULL guard", warnings_text)
+                    arity = func.__code__.co_argcount
+                    if arity == 1:
+                        df = self.spark.createDataFrame([(1,), (-1,), 
(None,)], "a long")
+                        projected = df.select(u("a"))
+                    else:
+                        df = self.spark.createDataFrame(
+                            [(1, 2), (2, 1), (None, 1)], "a long, b long"
+                        )
+                        projected = df.select(u("a", "b"))
+                    self.assertNotIn("raise_error", 
self._optimized_plan(projected), name)
+                    self.assertEqual(0, self._eval_python_count(projected), 
name)
+                    self.assertEqual([True, False, None], [r[0] for r in 
projected.collect()], name)
+
+    def test_udf_transpile_narrowing_does_not_change_branches(self):
+        def wrong_branch(x):
+            return (x > 0) if x is None else None
+
+        with self.sql_conf(_TRANSPILE_ON):
+            u = self._transpiled_udf(wrong_branch, BooleanType())
+            df = self.spark.createDataFrame([(None,)], "a long")
+            projected = df.select(u("a"))
+            self.assertIn("raise_error", self._optimized_plan(projected))
+            self.assertEqual(0, self._eval_python_count(projected))
+            with self.assertRaises(Exception) as raised:
+                projected.collect()
+            self.assertIn("cannot compare NULL", str(raised.exception))
+
+    def test_udf_transpile_early_return_null_guard(self):
+        # A 2-statement early-return pattern
+        # `if x is None: return y\nreturn body` is normalized to a single
+        # if/else so null narrowing applies to the main body.
+        def early_return_gt(x):
+            if x is None:
+                return None
+            return x > 0
+
+        def early_return_lt_default(x):
+            if x is None:
+                return False
+            return x < 10
+
+        with self.sql_conf(_TRANSPILE_ON):
+            for name, func, rt, rows, expected in [
+                (
+                    "early_return_gt",
+                    early_return_gt,
+                    BooleanType(),
+                    [(1,), (-1,), (None,)],
+                    [True, False, None],
+                ),
+                (
+                    "early_return_lt_default",
+                    early_return_lt_default,
+                    BooleanType(),
+                    [(5,), (15,), (None,)],
+                    [True, False, False],
+                ),
+            ]:
+                with self.subTest(func=name):
+                    u, warnings_text = self._udf_and_warnings(func, rt)
+                    self.assertTrue(u.transpiled, f"{name} did not transpile: 
{warnings_text}")
+                    self.assertNotIn("NULL guard", warnings_text)
+                    df = self.spark.createDataFrame(rows, "a long")
+                    projected = df.select(u("a"))
+                    self.assertNotIn("raise_error", 
self._optimized_plan(projected), name)
+                    self.assertEqual(0, self._eval_python_count(projected), 
name)
+                    self.assertEqual(expected, [r[0] for r in 
projected.collect()], name)
+
+    def test_udf_transpile_null_guard_warning(self):
+        # When the transpiler still emits a null guard (because
+        # non-null cannot be proven), it emits a UserWarning at construction 
time.
+        import warnings
+
+        def unguarded_gt(x):
+            return x > 0
+
+        with self.sql_conf(_TRANSPILE_ON):
+            with warnings.catch_warnings(record=True) as caught:
+                warnings.simplefilter("always")
+                u = UserDefinedFunction(unguarded_gt, BooleanType())
+            null_guard_warnings = [w for w in caught if "NULL guard" in 
str(w.message)]
+            self.assertTrue(u.transpiled)
+            self.assertTrue(null_guard_warnings, "Expected a UserWarning about 
NULL guard")
+            self.assertIn("NULL guard", str(null_guard_warnings[0].message))
+
+    def test_udf_transpile_null_narrowing_len(self):
+        # A guarded len() call should skip the raise_error null guard.
+        def len_guarded(x):
+            if x is not None:
+                return len(x) > 3
+            return None
+
+        def len_early_return(x):
+            if x is None:
+                return None
+            return len(x) > 3
+
+        with self.sql_conf(_TRANSPILE_ON):
+            for name, func in [
+                ("len_guarded", len_guarded),
+                ("len_early_return", len_early_return),
+            ]:
+                with self.subTest(func=name):
+                    u, warnings_text = self._udf_and_warnings(func, 
BooleanType())
+                    self.assertTrue(u.transpiled, f"{name} did not transpile: 
{warnings_text}")
+                    self.assertNotIn("NULL guard", warnings_text)
+                    df = self.spark.createDataFrame([("hi",), ("hello",), 
(None,)], "a string")
+                    projected = df.select(u("a"))
+                    self.assertNotIn("raise_error", 
self._optimized_plan(projected), name)
+                    self.assertEqual(0, self._eval_python_count(projected), 
name)
+                    self.assertEqual(
+                        [False, True, None],
+                        [r[0] for r in projected.collect()],
+                        name,
+                    )
+
+    def test_udf_transpile_early_return_requires_null_narrowing(self):
+        def early_return_gt(x):
+            if x > 0:
+                return 1
+            return 0
+
+        def early_return_arithmetic(x, y):
+            if x > 0:
+                return x + y
+            return 0
+
+        with self.sql_conf(_TRANSPILE_ON):
+            u, _ = self._fallback_reason(early_return_gt)
+            df = self.spark.createDataFrame([(float("nan"),), (2.0,), 
(-3.0,)], "a double")
+            projected = df.select(u("a"))
+            self.assertGreater(self._eval_python_count(projected), 0)
+            self.assertEqual([0, 1, 0], [r[0] for r in projected.collect()])
+
+            u, _ = self._fallback_reason(early_return_arithmetic)
+            df = self.spark.createDataFrame([(1, None)], "a long, b long")
+            projected = df.select(u("a", "b"))
+            self.assertGreater(self._eval_python_count(projected), 0)
+            with self.assertRaises(Exception) as raised:
+                projected.collect()
+            self.assertIn("TypeError", str(raised.exception))
+
+    def test_udf_transpile_len_comparison_bool_and_if(self):
+        def len_gt(s):
+            return len(s) > 3
+
+        def len_eq(s):
+            return len(s) == 3
+
+        def len_if(s):
+            if len(s) > 3:
+                return True
+            else:
+                return False
+
+        with self.sql_conf(_TRANSPILE_ON):
+            for func in (len_gt, len_eq, len_if):
+                with self.subTest(func=func.__name__):
+                    expected = [False, False] if func is len_eq else [True, 
False]
+                    self.assertEqual(
+                        expected,
+                        self._vals(func, BooleanType(), "s string", 
[("hello",), ("hi",)]),
+                    )
+            self._fallback_reason(len_gt, LongType())
+
+    def test_udf_transpile_len_boolean_chain_guards(self):
+        def guarded_chain(s):
+            return s is not None and len(s) > 3 and len(s) < 10
+
+        def guarded_or_chain(s):
+            return s is None or len(s) < 3 or len(s) > 10
+
+        def unguarded_chain(x, s):
+            return x > 0 and len(s) > 3 and len(s) < 10
+
+        def guarded_gt(s):
+            return s is not None and len(s) > 3
+
+        def guarded_lt(s):
+            return s is not None and len(s) < 10
+
+        with self.sql_conf(_TRANSPILE_ON):
+            rows = [("hello",), ("hi",), ("this is long",), (None,)]
+            self.assertEqual(
+                [True, False, False, False],
+                self._vals(guarded_chain, BooleanType(), "s string", rows),
+            )
+            self.assertEqual(
+                [False, True, True, True],
+                self._vals(guarded_or_chain, BooleanType(), "s string", rows),
+            )
+            df = self.spark.createDataFrame(rows, "s string")
+
+        with self.sql_conf(_TRANSPILE_ON):
+            gt = self._transpiled_udf(guarded_gt, BooleanType())
+            lt = self._transpiled_udf(guarded_lt, BooleanType())
+            projected = df.select(gt("s"), lt("s"))
+            self.assertEqual(0, self._eval_python_count(projected))
+            self.assertEqual(
+                [(True, True), (False, True), (True, False), (False, False)],
+                [tuple(row) for row in projected.collect()],
+            )
+
+            u, _ = self._fallback_reason(unguarded_chain, BooleanType())
+            df = self.spark.createDataFrame([(0, None), (1, "hello")], "x 
long, s string")
+            projected = df.select(u("x", "s"))
+            self.assertGreater(self._eval_python_count(projected), 0)
+            self.assertEqual([False, True], [r[0] for r in 
projected.collect()])
+
+    def test_udf_transpile_short_circuit_and_arithmetic_narrowing(self):
+        def and_guard(x):
+            return x is not None and x > 0
+
+        def or_guard(x):
+            return x is None or x > 0
+
+        def or_early_return(a, b):
+            if a is None or b is None:
+                return None
+            return a < b
+
+        def arithmetic_guard(x):
+            return (x + 1 > 0) if x is not None else None
+
+        with self.sql_conf(_TRANSPILE_ON):
+            for func in (and_guard, or_guard):
+                with self.subTest(func=func.__name__):
+                    self.assertEqual(
+                        [True, False, func(None)],
+                        self._vals(func, BooleanType(), "x long", [(1,), 
(-1,), (None,)]),
+                    )
+            self.assertEqual(
+                [True, False, None, None],
+                self._vals(
+                    or_early_return,
+                    BooleanType(),
+                    "a long, b long",
+                    [(1, 2), (2, 1), (None, 1), (1, None)],
+                ),
+            )
+            self.assertEqual(
+                [True, False, None],
+                self._vals(arithmetic_guard, BooleanType(), "x long", [(1,), 
(-2,), (None,)]),
+            )
+            for func, schema, rows in [
+                (and_guard, "x long", [(1,), (-1,), (None,)]),
+                (or_early_return, "a long, b long", [(1, 2), (None, 1)]),
+                (arithmetic_guard, "x long", [(1,), (None,)]),
+            ]:
+                u, warnings_text = self._udf_and_warnings(func, BooleanType())
+                self.assertNotIn("NULL guard", warnings_text)
+                df = self.spark.createDataFrame(rows, schema)
+                projected = df.select(u(*df.columns))
+                self.assertNotIn("raise_error", 
self._optimized_plan(projected))
+                self.assertEqual(0, self._eval_python_count(projected))
+
+    def test_udf_transpile_len_comparison_repeat_count(self):
+        def repeat_len_comparison(s):
+            return s + "*" * (len(s) > 1)
+
+        def reversed_repeat_len_comparison(s):
+            return (len(s) > 1) * "*" + s
+
+        with self.sql_conf(_TRANSPILE_ON):
+            for func in (repeat_len_comparison, 
reversed_repeat_len_comparison):
+                with self.subTest(func=func.__name__):
+                    expected = (
+                        ["*hi", "*hello"]
+                        if func is reversed_repeat_len_comparison
+                        else ["hi*", "hello*"]
+                    )
+                    self.assertEqual(
+                        expected,
+                        self._vals(func, StringType(), "s string", [("hi",), 
("hello",)]),
+                    )
+
+    def test_udf_transpile_null_guard_warning_is_single_and_named(self):
+        import warnings
+
+        from pyspark.sql.transpile import _transpile_func
+
+        def unguarded_gt(x):
+            return x > 0
+
+        def unguarded_len(s):
+            return len(s)
+
+        with self.sql_conf(_TRANSPILE_ON):
+            with warnings.catch_warnings(record=True) as caught:
+                warnings.simplefilter("always")
+                u = UserDefinedFunction(unguarded_gt, BooleanType())
+            messages = [str(w.message) for w in caught if "NULL guard" in 
str(w.message)]
+            self.assertEqual(len(messages), 1)
+            self.assertIn("unguarded_gt", messages[0])
+            self.assertIn("ordering comparisons", messages[0])
+            self.assertTrue(u.transpiled)
+
+            with warnings.catch_warnings():
+                warnings.simplefilter("error")
+                result = _transpile_func(self.spark, unguarded_gt, 
BooleanType())
+            self.assertEqual(len(result[0]), len(u.transpiled))
+            self.assertEqual([str(c) for c in result[0]], [str(c) for c in 
u.transpiled])
+
+            with warnings.catch_warnings():
+                warnings.filterwarnings("error", message=".*NULL guard")
+                with self.assertRaises(UserWarning) as raised:
+                    UserDefinedFunction(unguarded_gt, BooleanType())
+            self.assertIn("unguarded_gt", str(raised.exception))
+            self.assertIn("ordering comparisons", str(raised.exception))
+
+            with warnings.catch_warnings(record=True) as caught:
+                warnings.simplefilter("always")
+                u = UserDefinedFunction(unguarded_len, LongType())
+            messages = [str(w.message) for w in caught if "NULL guard" in 
str(w.message)]
+            self.assertEqual(len(messages), 1)
+            self.assertIn("unguarded_len", messages[0])
+            self.assertIn("len()", messages[0])
+            self.assertNotIn("ordering comparisons", messages[0])
+            self.assertTrue(u.transpiled)
+
+    def test_udf_transpile_narrowing_boundaries(self):

Review Comment:
   **Non-blocking (P2):** The new negative narrowing cases cover a leak into a 
ternary's body under `x is None` (`wrong_branch`), an operand before its guard 
(`before_guard`), and the true branch of an `or` of `is None` checks 
(`true_or_branch`). The other narrowing sites have none, so each of these 
mutations would turn Python's TypeError into NULL or False on a NULL row while 
every test still passes:
   - adding the false-branch set to an if statement's body, so `if x is None: 
return x > 0` / `return None` drops its guard;
   - unioning both sets in the `and`/`or` loop, so `x is not None or x > 0` 
lowers to `isnotnull(x) OR x > 0`;
   - skipping the restore after a narrowed ternary, so `(0 if s is None else 
len(s)) + len(s)` drops the second `len()` guard;
   - treating arithmetic as non-null when either operand is, so `(x + y > 0) if 
x is not None else None` drops its guard for (1, NULL).
   
   Negative cases for those four shapes would close the gap, along with a 
ternary's else arm under `is not None` (`True if x is not None else x > 0`), a 
later `and` operand after `x is None` (`x is None and x > 0`), and an `or` of 
`is not None` checks used as a test. Each should keep `raise_error` in its plan 
and raise on the NULL row.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/59978#discussion_r4466812345), 
[2](https://github.com/apache/spark/pull/59978#discussion_r4466812402).
   
   **Verification:**
   - **Regression:** With transpilation and ANSI on, each listed shape, run 
over a NULL row the proof does not cover, keeps raise_error in its optimized 
plan, runs lowered, and fails with the transpiler's NULL error where Python 
raises TypeError.



##########
python/pyspark/sql/transpile.py:
##########
@@ -203,6 +203,9 @@ def _is_definitely_basic_type(node: ast.AST) -> bool:
             return _is_definitely_basic_type(operand)
         case ast.Name():
             return True
+        case ast.Call(func=ast.Name(id="len"), args=[_], keywords=[]):

Review Comment:
   **Blocking (P1):** With this arm, a `len()` comparison is classified boolean 
even when no None check narrows its argument. So bodies the base branch ran as 
interpreted Python now lower whenever they use such a comparison as a boolean. 
That matters when the body also contains an operation with one of the 
transpiler's documented differences. Examples are `len(s) > 3 and x > 0.5`, 
`len(s) < limit`, and `not (len(s) < limit)` over a float, `(len(s) > 3) if x > 
0.5 else False`, and `x + 1 == len(s)`. For a (string, double) row ('hello', 
NaN), the first evaluates `true AND (NaN > 0.5)`, which Spark treats as true 
because NaN orders above every value; Python's `True and (nan > 0.5)` is False. 
`x + 1 == len(s)` with `x: int` returns False for a NULL `x`, because the 
equality lowering treats the NULL sum as None, where Python raises TypeError at 
`None + 1`. If and ternary tests over a `len()` comparison failed analysis on 
the base branch, and they now return these values without an error. 
 Shapes such as `return len(s) > 3`, with no float comparison and no arithmetic 
over an unproven parameter, keep Python's results. The description accepts 
these differences only for lowered null-guard early returns, and these bodies 
fall outside that idiom.
   
   **Recommended change:** Make a variant fall back to interpreted Python when 
it uses, anywhere outside a string-repeat count, a len() comparison whose len() 
argument no None check proves non-null (as or inside an and/or or `not` 
operand, as an if or ternary test, or as the BooleanType result or one of its 
branches), and the same variant also lowers an operation with a documented 
difference: an ordering comparison with an operand that contains a float 
parameter or a float literal, or `+`, `-`, `*`, `%`, unary minus, or string 
concatenation over a parameter no None check proves non-null. Judge float 
exposure from the parameters and literals an operand contains, not from its 
category: the transpiler labels a len() call, and arithmetic over one, 
'numeric', although len() always returns an integer that is never NaN. Record 
both facts while lowering and refuse the variant at the end of 
`_transpile_from_ast`, as the later-operand len() check refuses its chains. Add 
UDF transpiler tests fo
 r the refused shapes and for the shapes that keep lowering.
   
   **Why this works:** The check refuses every body admitted only by the 
reclassification whose lowering could return Spark's NaN-ordered or 
NULL-derived value, so those bodies return to Python's results; it also refuses 
some whose lowering already matches Python, such as arithmetic that only feeds 
an ordering comparison, whose guard raises like Python. Bodies with neither 
kind of operation, whose lowering equals Python, and narrowed len() 
comparisons, which the PR targets and whose documented differences it accepts, 
keep lowering.
   
   **Scope:** Add a per-variant fallback for boolean uses of unguarded len() 
comparisons that also carry a documented difference, with unit tests.
   
   **Compatibility:** Shapes that use no float comparison and no arithmetic or 
concatenation over an unproven parameter, every narrowed len() comparison, and 
every position the base branch already lowered keep the lowering they have now.
   
   **Risks:** Variants that combine an unguarded len() comparison with a float 
comparison or unproven arithmetic run as interpreted Python, as the base branch 
did for the and/or, `not`, and BooleanType forms (if and ternary tests over a 
len() comparison failed analysis there instead), giving up the lowering this 
change added for them, including some whose lowering matches Python, such as 
`len(s) + x > 3` over a BIGINT `x`; removing the check restores it.
   
   **Constraints:** Judge NaN exposure by whether an operand contains a float 
parameter or a float literal, and treat a len() result as an integer, because 
each parameter carries a concrete category in every variant while the 
transpiler labels len() calls and arithmetic over them 'numeric' whatever the 
other operand's type. Leave the check inactive for string-repeat counts and 
other positions the base branch already lowered, so no base-lowered shape newly 
falls back.
   
   **Exclusions:**
   - Narrowed len() comparisons in the null-guard idiom keep lowering with the 
documented differences the PR description accepts.
   - Which comparison-valued string-repeat counts lower is left to the 
repeat-count fix.
   
   **Success:** A variant that uses an unguarded len() comparison outside a 
string-repeat count and also lowers an ordering comparison over a float 
parameter or float literal, or arithmetic or concatenation over an unproven 
parameter, produces no transpiled option, so the UDF returns Python's results. 
BooleanType bodies such as `len(s) > 3`, `len(s) == 3`, `if len(s) > 3:`, and 
`len(s) < limit` over a BIGINT `limit`, and every narrowed len() comparison, 
keep their native lowering.
   
   **Verification:**
   - **Regression:** With transpilation and ANSI on, `len(s) > 3 and x > 0.5`, 
`len(s) < limit`, `not (len(s) < limit)`, `(x > 0.5) if len(s) > 3 else False`, 
and `(len(s) > 3) if x > 0.5 else False` over a DOUBLE column holding NaN 
return Python's results with Python evaluation in the executed plan.
   - **Regression:** `x + 1 == len(s)` with `x: int` and `s: str` over a row 
with NULL x raises the TypeError interpreted Python raises instead of returning 
False.
   - **Compatibility:** BooleanType `len(s) > 3`, `len(s) == 3`, `if len(s) > 
3:`, and `len(s) < limit` over a BIGINT `limit` column, the narrowed len() 
shapes, and `s + '*' * (len(s) > 1)` keep lowering with no Python evaluation in 
the executed plan and return Python's values.



##########
python/pyspark/sql/udf.py:
##########
@@ -329,6 +331,15 @@ def _conf_is_true(key: str, default: Optional[str] = None) 
-> bool:
             self._transpiled_param_names = []
             self._transpiled_input_categories = []
             self._positional_only_param_names = frozenset()
+        if guarded_constructs:
+            constructs = " and ".join(guarded_constructs)
+            warnings.warn(
+                f"Python UDF {func}: its transpiled form includes NULL guards 
for "
+                f"{constructs}. They raise when the transpiled form runs on 
NULL "

Review Comment:
   **Nit (P3):** The constructs listed here come from every guard narrowing 
cannot remove, including guards the UDF's own truthiness test already keeps 
away from NULL. For `def f(s): return len(s) > 3 if s else False`, the lowered 
form is `CASE WHEN coalesce(length(s) > 0, false) THEN <guarded len(s) > 3> 
ELSE false END`, so a NULL `s` returns False just as Python does. Yet 
construction warns that its guards for `len()` and ordering comparisons raise 
on NULL input, and tells the user to add `is not None` guards. Wording it as 
"each guard raises if its operand is NULL when the guard is evaluated" would 
match what the transpiler knows. That wording keeps the 'NULL guard' phrase, 
the UDF name, and the construct list that the tests and warning filters match.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59978#discussion_r4466812438).
   
   **Verification:**
   - **Inspection:** The advisory text states that a guard raises only when its 
operand is NULL as the guard is evaluated, and keeps the 'NULL guard' phrase, 
the UDF's name, and the construct list that the existing escalation filters and 
assertions match.



##########
python/pyspark/sql/transpile.py:
##########
@@ -717,7 +797,22 @@ def _convert_chunk(self, params: List[str], body: ast.AST 
| None) -> Column:
                         "short-circuit-return-operand semantics, so the UDF "
                         "falls back to interpreted Python"
                     )
-                cols = [self._convert_chunk(params, v) for v in values]
+                cols = []
+                saved_nonnull = self._nonnull_params
+                try:
+                    for index, value in enumerate(values):
+                        for previous in values[:index]:
+                            narrowed = _null_narrowed(params, previous)
+                            self._nonnull_params |= narrowed[0 if 
isinstance(op, ast.And) else 1]
+                        previous_len_guards = self._len_null_guard_count
+                        cols.append(self._convert_chunk(params, value))
+                        if index > 0 and self._len_null_guard_count > 
previous_len_guards:

Review Comment:
   **Non-blocking (P2):** This counts only `len()` NULL guards, but the chains 
the `len()` reclassification newly admits can keep an ordering-comparison guard 
in a later operand. `def f(s: str, x: int): return len(s) > 3 and x > 0` now 
lowers to `<guarded len(s) > 3> AND CASE WHEN isnull(x) OR isnull(0) THEN 
raise_error(...) ELSE x > 0 END`. `def g(s: str, y: int): return s is not None 
and y > len(s)` keeps `CASE WHEN isnull(y) OR isnull(length(s)) THEN 
raise_error(...)` in its second operand. The base branch ran both as 
interpreted Python. With the default 
`spark.sql.subexpressionElimination.skipForShortcutExpr=false`, 
EquivalentExpressions treats both And operands as always evaluated and accepts 
the deterministic `raise_error`. So in `df.select(f('a', 'x'), f('b', 'x'))` 
the shared guarded comparison can be hoisted, raising `cannot compare NULL` on 
a row with a short `a` and a NULL `x`, where Python returns False. This is the 
mechanism the `len()` check exists for; it was traced th
 rough the source rather than run. Chains the base branch already lowers, such 
as `a > 3 and x > 0`, have the same exposure there and need not change.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59978#discussion_r4466812337).
   
   **Recommended change:** In the and/or lowering, also count the 
ordering-comparison NULL guards that `_lower_value_compare` emits, and when the 
chain contains a len() comparison, refuse it, so the variant falls back, 
whenever an operand after the first adds either kind of guard after narrowing. 
Chains without a len() comparison, which the base branch already lowers, keep 
their behavior. Add UDF transpiler tests for two calls that share a guarded 
later operand.
   
   **Why this works:** Every chain containing a len() comparison ran as 
interpreted Python on the base branch, so refusing those whose later operand 
still holds a raising guard keeps Python's short-circuit for exactly the chains 
this change newly admits, whatever subexpression elimination shares across 
expressions; chains whose later operands are fully narrowed carry no raising 
guard and keep lowering.
   
   **Scope:** Extend the and/or later-operand check to ordering-comparison 
guards for chains that contain a len() comparison, with unit tests.
   
   **Compatibility:** Chains without a len() comparison lower exactly as on the 
base branch, and narrowed len() chains whose later operands carry no guard keep 
their native lowering.
   
   **Risks:** Chains such as `len(s) > 3 and x > 0` and `s is not None and y > 
len(s)` run as interpreted Python again, as on the base branch; removing the 
check restores their lowering.
   
   **Constraints:** Count only guards that remain after narrowing, so a chain 
whose earlier None checks prove every later operand non-null still lowers. 
Leave chains without a len() comparison unchanged, because the base branch 
lowers them.
   
   **Exclusions:**
   - The same hoisting exposure in chains the base branch already lowers, such 
as `a > 3 and x > 0`, is left as it is.
   
   **Success:** No lowered and/or chain that contains a len() comparison keeps 
a raising NULL guard in an operand after the first. Narrowed len() chains whose 
later operands carry no guard, and chains without a len() comparison, lower as 
they do now.
   
   **Verification:**
   - **Regression:** With transpilation and ANSI on and default subexpression 
elimination, selecting `len(s) > 3 and x > 0` over two different string columns 
that share x returns Python's False on a row where both strings are short and x 
is NULL, and pairing `s is not None and y > len(s)` with another call whose 
later operand is `y > len(s)` returns Python's False on a row with NULL s.
   - **Compatibility:** `x is not None and y > 0` and `a > 3 and x > 0` still 
lower exactly as on the base branch.
   - **Behavior:** `s is not None and len(s) > 3 and len(s) < 10` and `s is 
None or len(s) < 3 or len(s) > 10` still lower with no raise_error and no 
Python evaluation, alone and as two calls in one select.



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