spark-test commented on code in PR #60682:
URL: https://github.com/apache/spark/pull/60682#discussion_r4624943962
##########
python/pyspark/sql/transpile.py:
##########
@@ -991,6 +1083,15 @@ def _transpile_from_ast(
"interpreted Python"
)
converted = self._convert_chunk(params, function_body[0])
+ if self._null_guard_emitted:
+ warnings.warn(
+ "Python UDF transpiler: the transpiled UDF includes a NULL
guard "
Review Comment:
**Non-blocking (P2):** The message names neither the UDF nor the operation
that kept its guard, and `stacklevel=2` attributes it to the
`_transpile_from_ast` call at transpile.py:1566 rather than the user's `udf()`
call, so an application with several UDFs gets identical warnings pointing into
pyspark. It is issued once per input-type variant that keeps a guard (twice for
an untyped `x > 0` under an 'always' filter), and its advice to guard
comparisons is also given when the only guard comes from `len()` (the flag set
at transpile.py:994), so `def f(s): return len(s)` is told to guard comparisons
it does not contain. The sibling warnings in udf.py (lines 292, 315 and 327)
interpolate the UDF, and the PR description promises one named
construction-time warning.
See **Shared repair plan 1** in the review body.
##########
python/pyspark/sql/transpile.py:
##########
@@ -991,6 +1083,15 @@ def _transpile_from_ast(
"interpreted Python"
)
converted = self._convert_chunk(params, function_body[0])
+ if self._null_guard_emitted:
+ warnings.warn(
Review Comment:
**Blocking (P1):** This `warnings.warn` runs inside the per-variant `try ...
except Exception` in `_transpile_func` (transpile.py:1563-1575), and
`UserWarning` is an `Exception`, so a filter that escalates the advisory makes
that handler drop the option this call just built.
Reading the code: with `warnings.filterwarnings("error", message="Python UDF
transpiler:")`, or a filter on `module="pyspark.sql.transpile"`, building `def
f(x: int): return x > 0` as a BooleanType UDF keeps no option, udf.py:315 only
warns 'Unable to transpile UDF ...', and every row then runs in a Python
worker, where the base branch lowers it natively and the user asked for an
error. Under `-W error` or pytest `filterwarnings = error`, construction
instead fails with 'Exception transpiling UDF ...: Unable to transpile UDF
...', reporting a successful lowering as a transpilation failure. The PR
description says the advisory is emitted after transpilation, outside the
fallback handler, so that escalating it cannot discard options; the new test
uses only an 'always' filter, so nothing catches this.
See **Shared repair plan 1** in the review body.
##########
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=[]):
+ # len() always returns an int: CPython raises if __len__ returns
anything else.
+ return True
Review Comment:
**Blocking (P1):** Accepting `len(...)` here makes `len(s) > 3` definitely
boolean, so the and/or lowering (transpile.py:752-797) now admits chains such
as `s is not None and len(s) > 3 and len(s) < 10` and converts every operand
with its guards. Each later comparison becomes `CASE WHEN isnull(L) ... THEN
raise_error ... END` with `L = CASE WHEN isnull(s) THEN raise_error('cannot
call len() on NULL ...') ELSE length(s) END`. With
`spark.sql.subexpressionElimination.skipForShortcutExpr` at its default of
false, EquivalentExpressions treats both AND operands and each CASE's first
condition as always evaluated, so `isnull(L)` is counted twice and
ProjectExec's whole-stage codegen evaluates it before the projection. Reading
that code, a NULL `s` read from a table or another codegen source therefore
raises where Python returns False, and two such single-len chains over one
column in one select share the guard the same way. The PR's tests use
createDataFrame data, which ConvertToLocalRe
lation evaluates with a lazy interpreted projection, so they cannot see this.
The PR description says a len-comparison chain whose later operand still emits
a guard falls back; nothing in this diff does that.
**Verification:**
- **Regression:** With transpilation and ANSI on, `x > 0 and len(s) > 3 and
len(s) < 10` over a string column derived from spark.range returns False for x
= -1 and s NULL instead of raising 'cannot call len() on NULL'.
- **Behavior:** An ordering-only chain keeps its current lowering, and a
len() chain whose later operands carry no guard still runs natively.
##########
python/pyspark/sql/transpile.py:
##########
@@ -256,6 +259,46 @@ def _truthiness_col(cat: Optional[str], c: Column) ->
Optional[Column]:
return None
+def _null_narrowed(params: List[str], test_node: ast.AST) -> Tuple[frozenset,
frozenset]:
+ """Return ``(body_nonnull, else_nonnull)`` — frozensets of parameter names
+ that are proven non-null in the true branch and the false branch
+ respectively of an ``if``/ternary with this test.
+
+ Recognised patterns (``p`` must be in ``params``):
+ ``p is not None`` → body: {p}
+ ``p is None`` → else: {p}
+ ``None is not p`` → body: {p}
+ ``None is p`` → else: {p}
+ ``A and B and …`` → body: union of each clause's body set
Review Comment:
**Nit (P3):** This docstring introduces an em dash, right arrows and an
ellipsis, and the comment at transpile.py:293 has the same arrow and ellipsis;
the rest of the file is ASCII, as AGENTS.md asks, and the similar table in
`_truthiness_col` uses `->` and `--`. The comment at line 293 needs the same
change.
```suggestion
"""Return ``(body_nonnull, else_nonnull)`` -- frozensets of parameter
names
that are proven non-null in the true branch and the false branch
respectively of an ``if``/ternary with this test.
Recognised patterns (``p`` must be in ``params``):
``p is not None`` -> body: {p}
``p is None`` -> else: {p}
``None is not p`` -> body: {p}
``None is p`` -> else: {p}
``A and B and ...`` -> body: union of each clause's body set
```
**Verification:**
- **Inspection:** transpile.py contains no character outside ASCII, as on
the base branch.
##########
python/pyspark/sql/transpile.py:
##########
@@ -284,6 +329,24 @@ def _convert_branch(self, params: List[str], statements:
List[ast.stmt], slot: s
return lit(None)
return self._convert_chunk(params, statements[0])
+ def _is_nonnull_node(self, params: List[str], node: ast.AST) -> bool:
+ """Return True when ``node`` is statically known to produce a non-null
value.
+
+ A non-None literal constant is always non-null. A parameter name is
+ non-null when proven so by an enclosing ``is not None`` guard recorded
+ in ``self._nonnull_params``. ``len(x)`` is non-null when ``x`` is
non-null
+ because ``length`` of a non-null string always returns a non-null
integer.
+ """
+ match node:
+ case ast.Constant(value=v):
+ return v is not None
+ case ast.Name(id=name) if name in params:
+ return name in self._nonnull_params
+ case ast.Call(func=ast.Name(id="len"), args=[arg], keywords=[]):
+ return self._is_nonnull_node(params, arg)
+ case _:
Review Comment:
**Non-blocking (P2):** Everything other than a non-None constant, a proven
parameter, or len() of one falls through to this `False`, and proofs are
recorded only around if/ternary branches; the and/or lowering converts every
operand with the outer set (transpile.py:786). So the common idiom `x is not
None and x > 0`, its `or` form `x is None or x > 0`, and `if x is not None:
return x + 1 > 0` / `return None` keep a raise_error guard that a NULL cannot
reach, which keeps the larger plan this PR sets out to remove and emits the
advisory telling the user to add the `is not None` guard they already have.
Results are unaffected. The PR description says proofs cover and/or operands
and arithmetic whose operands are all proven non-null.
**Verification:**
- **Behavior:** With transpilation and ANSI on, the four shapes above run
natively over bigint columns with no raise_error in the plan, emit no
NULL-guard advisory, and return Python's results for NULL and non-NULL rows.
- **Regression:** `x > 0 and x is not None` still raises the comparison's
NULL error for a NULL x, as Python raises TypeError.
##########
python/pyspark/sql/transpile.py:
##########
@@ -908,11 +984,14 @@ def _convert_chunk(self, params: List[str], body: ast.AST
| None) -> Column:
"types fall back to interpreted Python"
)
arg_col = self._convert_chunk(params, arg)
+ if self._is_nonnull_node(params, arg):
Review Comment:
**Nit (P3):** After this skip, `if x is not None: return len(x)` lowers to a
bare `length(x)`, but the comment at transpile.py:979-980 still says such a
caller takes the guard's otherwise branch. It should describe the skip for a
proven argument.
See **Shared repair plan 3** in the review body.
##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -2750,6 +2750,148 @@ 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):
+ # When a parameter is guarded by `x is not None` in an
+ # if/ternary test, the transpiler should skip the raise_error null
guard
+ # for ordering comparisons on that parameter within the guarded branch.
+ def if_guard_gt(x):
+ return (x > 0) if x is not None else None
+
+ def if_guard_and_lt(a, b):
+ return (a < b) if a is not None and b is not None else None
+
+ def ternary_guard_ge(x):
+ return (x >= 0) if x is not None else None
+
+ def is_none_ternary(x):
+ return None if x is None else x > 0
+
+ cases_if = [
+ # if/else with `is not None` guard
+ ("if_guard_gt", if_guard_gt),
+ # if/else with `is not None` and-chain (two params)
+ ("if_guard_and_lt", if_guard_and_lt),
+ # ternary with `is not None` guard
+ ("ternary_guard_ge", ternary_guard_ge),
+ # `is None` guard: non-null in the else branch
+ ("is_none_ternary", is_none_ternary),
+ ]
+ with self.sql_conf(_TRANSPILE_ON):
+ for name, func in cases_if:
+ 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}")
+ arity = func.__code__.co_argcount
+ if arity == 1:
+ df = self.spark.createDataFrame([(1,), (-1,),
(None,)], "a long")
+ plan = self._optimized_plan(df.select(u("a")))
+ self.assertNotIn("raise_error", plan, f"{name}: plan
had raise_error")
+ self.assertEqual(
+ [True, False, None],
+ [r[0] for r in df.select(u("a")).collect()],
+ name,
+ )
+ else:
+ df = self.spark.createDataFrame(
+ [(1, 2), (2, 1), (None, 1)], "a long, b long"
+ )
+ plan = self._optimized_plan(df.select(u("a", "b")))
+ self.assertNotIn("raise_error", plan, f"{name}: plan
had raise_error")
+ self.assertEqual(
+ [True, False, None],
+ [r[0] for r in df.select(u("a", "b")).collect()],
+ name,
+ )
+
+ 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}")
+ df = self.spark.createDataFrame(rows, "a long")
+ plan = self._optimized_plan(df.select(u("a")))
+ self.assertNotIn("raise_error", plan, f"{name}: plan had
raise_error")
+ self.assertEqual(
+ expected,
+ [r[0] for r in df.select(u("a")).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, "unguarded_gt should transpile
(under strict or loose)")
Review Comment:
**Nit (P3):** There is no strict or loose null-strictness mode on this
branch (no such setting in python/pyspark/sql or SQLConf.scala), and the test
runs under the single `_TRANSPILE_ON` configuration, so the parenthetical sends
someone reading a failure looking for a switch that does not exist; dropping it
leaves `"unguarded_gt should transpile"`.
See **Shared repair plan 1** in the review body.
##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -2750,6 +2750,148 @@ 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):
+ # When a parameter is guarded by `x is not None` in an
+ # if/ternary test, the transpiler should skip the raise_error null
guard
+ # for ordering comparisons on that parameter within the guarded branch.
+ def if_guard_gt(x):
+ return (x > 0) if x is not None else None
+
+ def if_guard_and_lt(a, b):
+ return (a < b) if a is not None and b is not None else None
+
+ def ternary_guard_ge(x):
+ return (x >= 0) if x is not None else None
+
+ def is_none_ternary(x):
+ return None if x is None else x > 0
+
+ cases_if = [
+ # if/else with `is not None` guard
+ ("if_guard_gt", if_guard_gt),
+ # if/else with `is not None` and-chain (two params)
Review Comment:
**Nit (P3):** `if_guard_gt` and `if_guard_and_lt` are conditional
expressions (`(x > 0) if x is not None else None`), the same shape as
`ternary_guard_ge`, so despite these labels this test never reaches the
`ast.If` narrowing arm (transpile.py:812-829); only the normalized early
returns in the other tests do. Relabel them, and add a real single-statement
if/else fixture if the if-statement form should be covered here.
```suggestion
# ternary with `is not None` guard
("if_guard_gt", if_guard_gt),
# ternary with `is not None` and-chain (two params)
```
See **Shared repair plan 2** in the review body.
##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -2750,6 +2750,148 @@ 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):
Review Comment:
**Non-blocking (P2):** In every fixture here, the branch the test does not
prove is a constant, so these tests pass even if narrowing leaks into it.
Nothing checks that `(x > 0) if x is not None else (x < 0)` keeps the guard in
its else branch and raises for a NULL `x`, that an or-chain test or the else of
an and-chain proves nothing, that the reversed `None is not x` / `None is x`
forms narrow the right branch, or that the per-variant reset at
transpile.py:1021 keeps one variant's proofs out of the next. Any of those
regressions would return NULL where Python raises TypeError while this suite
stays green; the `_raises` helper (test_udf_transpile_unit.py:1597-1603)
already supports such checks.
See **Shared repair plan 2** in the review body.
##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -2750,6 +2750,148 @@ 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):
+ # When a parameter is guarded by `x is not None` in an
+ # if/ternary test, the transpiler should skip the raise_error null
guard
+ # for ordering comparisons on that parameter within the guarded branch.
+ def if_guard_gt(x):
+ return (x > 0) if x is not None else None
+
+ def if_guard_and_lt(a, b):
+ return (a < b) if a is not None and b is not None else None
+
+ def ternary_guard_ge(x):
+ return (x >= 0) if x is not None else None
+
+ def is_none_ternary(x):
+ return None if x is None else x > 0
+
+ cases_if = [
+ # if/else with `is not None` guard
+ ("if_guard_gt", if_guard_gt),
+ # if/else with `is not None` and-chain (two params)
+ ("if_guard_and_lt", if_guard_and_lt),
+ # ternary with `is not None` guard
+ ("ternary_guard_ge", ternary_guard_ge),
+ # `is None` guard: non-null in the else branch
+ ("is_none_ternary", is_none_ternary),
+ ]
+ with self.sql_conf(_TRANSPILE_ON):
+ for name, func in cases_if:
+ 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}")
+ arity = func.__code__.co_argcount
+ if arity == 1:
+ df = self.spark.createDataFrame([(1,), (-1,),
(None,)], "a long")
+ plan = self._optimized_plan(df.select(u("a")))
+ self.assertNotIn("raise_error", plan, f"{name}: plan
had raise_error")
Review Comment:
**Nit (P3):** `assertNotIn("raise_error", plan)` and the value check also
pass when the options are pruned and the UDF runs as interpreted Python,
because the plan then holds a PythonUDF with no raise_error and Python returns
the same values. Adding `self.assertEqual(0,
self._eval_python_count(df.select(u("a"))))`, as `_vals` does
(test_udf_transpile_unit.py:1589-1594), makes these tests fail when the
lowering does not run; the same applies to the other three new narrowing tests.
See **Shared repair plan 2** in the review body.
##########
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 `len(...)` basic, a comparison such as `len(t) > 3`
is definitely boolean and `_category_uncached` labels it 'bool'
(transpile.py:695-700), but the repeat rules at transpile.py:641-644 and
920-923 still accept only an 'integer' or 'numeric' count. So `s * (len(t) >
3)`, `(len(t) > 3) * s`, `s * (len(t) == len(u))`, `s * (len(t) + 1 > 3)` and
`s * ((len(t) > 3) if flag else (len(t) > 5))`, which the base branch lowered
to `repeat(s, cast(<comparison> as int))` (a cast ANSI allows), now produce no
option, and every row is evaluated in a Python worker instead of in codegen.
The PR description says these counts are kept in both operand orders while
ordinary counts such as `s * (x > 0)` keep falling back; accepting a comparison
over a len() result, and a ternary of two such comparisons, as an integral
count in both rules restores that.
**Verification:**
- **Regression:** With transpilation and ANSI on, each of `s * (len(t) >
3)`, `(len(t) > 3) * s`, `s * (len(t) + 1 > 3)`, and `s * ((len(t) > 3) if flag
else (len(t) > 5))` over string columns runs with no Python evaluation in the
executed plan and returns Python's strings for non-NULL rows.
- **Behavior:** `s * (x > 0)` and `s * ((len(t) > 3) if flag else None)`
still fall back to interpreted Python.
##########
python/pyspark/sql/transpile.py:
##########
@@ -938,7 +1017,20 @@ def _transpile_from_ast(
# Category inference depends on the per-variant assumptions above.
Cache
# each AST node only for this lowering so recursive conversion stays
linear.
self._category_cache = {}
+ # Reset per-transpilation null-narrowing state.
+ self._nonnull_params = frozenset()
+ self._null_guard_emitted = False
function_body = function_ast.body
+ # Normalize `if <test>: return y\nreturn body` (2-stmt early-return)
+ # into a single if/else so null narrowing can apply to the main body.
+ match function_body:
+ case [
+ ast.If(test=test, body=[ast.Return() as early_ret], orelse=[])
as if_node,
Review Comment:
**Blocking (P1):** This pattern matches every `if <test>: return a` followed
by `return b`, whatever the test, so early returns whose test proves no
parameter non-null stop falling back and start lowering. Reading the code with
the conf and ANSI on: `def f(x, y): if x > 0: return x + y` / `return 0` lowers
to `CASE WHEN coalesce(<guarded x > 0>, false) THEN x + y ELSE 0 END`, so the
row (1, NULL) returns NULL where Python raises TypeError, and `def f(x: float):
if x > 10: return 10.0` / `return x` returns 10.0 for NaN (Spark orders NaN
above every double) where Python returns nan. On the base branch both bodies
hit the one-statement check at transpile.py:1034-1038 and ran in Python. The PR
description says the rewrite applies only when the test proves a parameter
non-null; gating it on `_null_narrowed(params, test)` proving a parameter in
either branch restores the fallback for these bodies.
**Verification:**
- **Regression:** With transpilation and ANSI on, `if x > 0: return x + y` /
`return 0` builds no option and raises TypeError for the row (1, NULL), and `if
x > 10: return 10.0` / `return x` returns nan for a NaN input, as Python does.
- **Behavior:** The PR's null-guard early returns (`if x is None: return
None` / `return x > 0` over bigint, `if x is not None: return len(x) > 3` /
`return None` over string) still lower with no raise_error in the plan.
##########
python/pyspark/sql/transpile.py:
##########
@@ -501,12 +564,15 @@ def _lower_value_compare(
)
left_col = self._convert_chunk(params, left_node)
right_col = self._convert_chunk(params, right_node)
+ if self._is_nonnull_node(params, left_node) and
self._is_nonnull_node(params, right_node):
Review Comment:
**Nit (P3):** With this early return, a caller that proved both operands
non-null gets the bare comparison, but the docstring at transpile.py:539-544
still says such callers (`if x is not None: x > 0`) take the guarded CASE's
otherwise branch. It should say the guard is omitted when both operands are
proven non-null (non-None constants, narrowed parameters, or len() of those)
and kept otherwise.
See **Shared repair plan 3** in the review body.
##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -2750,6 +2750,148 @@ 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):
+ # When a parameter is guarded by `x is not None` in an
+ # if/ternary test, the transpiler should skip the raise_error null
guard
+ # for ordering comparisons on that parameter within the guarded branch.
+ def if_guard_gt(x):
+ return (x > 0) if x is not None else None
+
+ def if_guard_and_lt(a, b):
+ return (a < b) if a is not None and b is not None else None
+
+ def ternary_guard_ge(x):
+ return (x >= 0) if x is not None else None
+
+ def is_none_ternary(x):
+ return None if x is None else x > 0
+
+ cases_if = [
+ # if/else with `is not None` guard
+ ("if_guard_gt", if_guard_gt),
+ # if/else with `is not None` and-chain (two params)
+ ("if_guard_and_lt", if_guard_and_lt),
+ # ternary with `is not None` guard
+ ("ternary_guard_ge", ternary_guard_ge),
+ # `is None` guard: non-null in the else branch
+ ("is_none_ternary", is_none_ternary),
+ ]
+ with self.sql_conf(_TRANSPILE_ON):
+ for name, func in cases_if:
+ 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}")
+ arity = func.__code__.co_argcount
+ if arity == 1:
+ df = self.spark.createDataFrame([(1,), (-1,),
(None,)], "a long")
+ plan = self._optimized_plan(df.select(u("a")))
+ self.assertNotIn("raise_error", plan, f"{name}: plan
had raise_error")
+ self.assertEqual(
+ [True, False, None],
+ [r[0] for r in df.select(u("a")).collect()],
+ name,
+ )
+ else:
+ df = self.spark.createDataFrame(
+ [(1, 2), (2, 1), (None, 1)], "a long, b long"
+ )
+ plan = self._optimized_plan(df.select(u("a", "b")))
+ self.assertNotIn("raise_error", plan, f"{name}: plan
had raise_error")
+ self.assertEqual(
+ [True, False, None],
+ [r[0] for r in df.select(u("a", "b")).collect()],
+ name,
+ )
+
+ 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}")
+ df = self.spark.createDataFrame(rows, "a long")
+ plan = self._optimized_plan(df.select(u("a")))
+ self.assertNotIn("raise_error", plan, f"{name}: plan had
raise_error")
+ self.assertEqual(
+ expected,
+ [r[0] for r in df.select(u("a")).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")
Review Comment:
**Non-blocking (P2):** Under `simplefilter("always")` this test can only
show that some advisory appears for `x > 0`. It cannot catch the advisory
discarding the lowering under an escalating filter (the suite already builds
UDFs under `simplefilter("error")` in
test_udf_transpile_does_not_mask_char_varchar_ddl), a lost flag at the len()
site (transpile.py:994), or an advisory wrongly emitted for a fully narrowed
UDF, although the narrowing tests already capture `warnings_text`.
See **Shared repair plan 1** in the review body.
--
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]