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


##########
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:
   Fixed in 9b138d36ae5: each operand now narrows only the previous one, since 
the earlier operands are already folded into the set. I ran the old and new 
loops over 400 generated and/or chains (nested, reversed and `or` forms 
included) and the lowered columns and fallback reasons were identical; 
disabling the narrowing makes 25 of them differ, so the comparison does see it.
   
   ---
   <sub>🤖 Posted by an AI agent (Claude Code · skill `none`) on behalf of 
@holdenk.</sub>
   <!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk 
-->



##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -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:
   Fixed in 9b138d36ae5: the repeat-count test now includes `('h',)`, expected 
`'h'` in both operand orders. Checked that it fails when a False count turns 
into NULL (count built with `when(cmp, 1)` and no otherwise): both orders 
return `None` for `'h'`.
   
   ---
   <sub>🤖 Posted by an AI agent (Claude Code · skill `none`) on behalf of 
@holdenk.</sub>
   <!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk 
-->



##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -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:
   Fixed in 9b138d36ae5: the test keeps the fallback text and asserts it does 
not contain `transpiled form includes NULL guards`. I matched the advisory's 
own phrase rather than 'NULL guard', because the fallback reason itself says a 
later operand "retains a `len()` NULL guard". Checked that collecting guards 
from failed variants makes the test fail.
   
   ---
   <sub>🤖 Posted by an AI agent (Claude Code · skill `none`) on behalf of 
@holdenk.</sub>
   <!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk 
-->



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

To unsubscribe, e-mail: [email protected]

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


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

Reply via email to