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


##########
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:
   That works for me. Master's advisory makes the same claim, so rewording it 
there first and then backporting keeps the two branches consistent. Since the 
wording affects only the advisory text, not any result, this backport doesn't 
need to change it.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4577202327","thread_id":"inline:4577202327","verdict_sha256":"8213463545a4c47a6d87fabb4b3827b00223b071fe51aa8edce0a9a86b2334e5"}
 -->



##########
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 chains that 
now lower because `len()` comparisons count as boolean can keep an 
ordering-comparison guard in a later operand. `len(s) > 3 and x > 0` lowers to 
`<guarded len(s) > 3> AND CASE WHEN isnull(x) OR isnull(0) THEN 
raise_error(...) ELSE x > 0 END`, and `s is not None and len(s) > n` keeps a 
guard on `length(s) > n`, because narrowing removes the `len()` guard this 
check counts.
   
   Besides the two-call route raised earlier on this line, where subexpression 
elimination hoists a guard that `f('a', 'x')` and `f('b', 'x')` share, one call 
is enough when an `or` repeats the guarded comparison in both arms. `(s is not 
None and len(s) > 3 and x > 0) or (t is not None and len(t) > 3 and x > 0)` 
lowers with the same guard in each arm, and BooleanSimplification's 
common-factor rule (expressions.scala:606-629) rewrites `(A AND G) OR (B AND 
G)` to `G AND (A OR B)`. G then runs first and raises for a row whose `s`, `t`, 
and `x` are NULL, where Python returns False. Both routes are traced through 
the source; neither was run against a Spark build.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59978#discussion_r4577202321).
   
   **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 and for a guarded comparison repeated in both arms of an `or`.
   
   **Why this works:** A second per-lowering counter, incremented where 
`_lower_value_compare` emits its guard, lets the arm see whether each later 
operand's lowering added any raising guard. Refusing such chains when they 
contain a `len()` comparison keeps every raising guard of a newly admitted 
chain in its first operand, which Python evaluates unconditionally too, so no 
Catalyst rewrite can move one ahead of a short-circuit Python takes.
   
   **Scope:** Extend the and/or later-operand refusal to ordering-comparison 
guards for chains that contain a `len()` comparison, with unit tests.
   
   **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, including 
single-call uses that never share the guarded operand; 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 `(s is not None and len(s) > 3 and x > 0) or (t is not None 
and len(t) > 3 and x > 0)` returns Python's False on a row whose `s`, `t`, and 
`x` are all NULL.
   - **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.



##########
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 negative cases here cover a ternary body under `x 
is None`, an operand before its guard, and the true branch of an `or` of `is 
None` checks. No UDF body in this suite lowers differently when another 
narrowing site over-applies its proof: the And or Or arm of `_null_narrowed` 
returning both branch sets, the and/or loop unioning both sets, an else arm 
keeping the body set, the if-statement body receiving the false-branch set, the 
ternary skipping its restore, or arithmetic proven when either operand is. Each 
of those leaks would drop a needed guard and return NULL or False where Python 
raises TypeError, and every test would still pass.
   
   Besides the shapes listed earlier on this line, an `and` of `is None` checks 
used as a test is uncovered: `None if x is None and y is None else x < y` pins 
the And arm, and `if a is None and b is None: return None` / `return a < b` 
pins the early-return gate, which must keep refusing that body. One negative 
case per site, each run over a NULL row the proof does not cover, would close 
the gap.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59978#discussion_r4577202324).
   
   **Verification:**
   - **Regression:** With transpilation and ANSI on, each listed shape, run 
over a NULL row the narrowing does not cover, keeps raise_error in its 
optimized plan, runs lowered, and fails with the transpiler's NULL error where 
Python raises TypeError, while the early-return shape whose test is an `and` of 
`is None` checks produces no transpiled option and returns Python's TypeError.
   - **Regression:** Changing any one narrowing site to over-apply its proof 
(the if-statement body taking the false-branch set, an else arm keeping the 
body set, the And or Or arm of `_null_narrowed` returning both sets, the and/or 
loop using both sets, the ternary skipping its restore, or arithmetic proven 
when either operand is) makes at least one of these cases fail.



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

Review Comment:
   **Nit (P3):** Before each operand, this loop re-narrows every earlier 
operand and unions the result into `self._nonnull_params`, but nothing resets 
that set between iterations, so it already holds the narrowing of every operand 
except the previous one. An n-operand chain therefore makes n(n-1)/2 
`_null_narrowed` passes and frozenset copies per input-type variant, so 
construction time for long generated chains grows quadratically, against the 
linear conversion the comment at lines 1053-1054 promises. Narrowing only 
`values[index - 1]` before each later operand gives the same lowerings in one 
pass.
   
   **Verification:**
   - **Behavior:** For narrowed and/or chains, including `or` chains of `is 
None` checks, reversed `None is not p` forms, nested chains, and chains whose 
earlier operand proves nothing, the lowered expressions are identical to the 
current ones.
   - **Regression:** Lowering a generated chain of several hundred operands 
evaluates each operand's narrowing once, so construction time grows linearly 
with the chain instead of quadratically.



##########
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",)]),

Review Comment:
   **Nit (P3):** Both inputs are longer than one character, so `len(s) > 1` is 
always True here and each operand order only sees a repeat count of 1. A 
lowering that mishandled a False count, for example `when(cmp, s)` without an 
otherwise branch, would return NULL for a one-character string, where Python 
returns the string unchanged, and this test would still pass. Adding a 
one-character input such as `('h',)`, expected as `'h'` for both orders, pins 
the zero count.
   
   **Verification:**
   - **Regression:** For `s + '*' * (len(s) > 1)` and `(len(s) > 1) * '*' + s`, 
a one-character input returns the input unchanged on the lowered path, so a 
lowering that mishandles a False count fails.



##########
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())

Review Comment:
   **Nit (P3):** `_fallback_reason` asserts only that no option was produced 
and that some warning text exists. The failed variants of `unguarded_chain` 
record both 'len()' and 'ordering comparisons' guards before the later-operand 
check refuses them, and the advisory stays silent only because 
`_transpile_func` collects guards on success. If that collection moved outside 
the success branch, constructing this UDF, which only ever runs as interpreted 
Python, would tell users its transpiled form includes NULL guards, and no test 
would notice. Keeping the returned warning text and asserting that it contains 
no 'NULL guard' advisory pins it.
   
   **Verification:**
   - **Regression:** Constructing a fallback UDF whose failed variants recorded 
both guard kinds emits the fallback warning and no NULL-guard advisory, so 
collecting guards from failed variants fails the test.



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