spark-test commented on code in PR #60684:
URL: https://github.com/apache/spark/pull/60684#discussion_r4624668360
##########
python/pyspark/sql/transpile.py:
##########
@@ -234,6 +246,9 @@ def _is_definitely_boolean(node: ast.AST) -> bool:
case ast.IfExp(body=body, orelse=orelse):
# Ternary is boolean only if both branches are.
return _is_definitely_boolean(body) and
_is_definitely_boolean(orelse)
+ case ast.Call(func=ast.Attribute(attr=method)) if method in
_STRING_METHODS:
Review Comment:
**Blocking (P1):** This arm makes a bare `s.startswith(p)` or
`s.endswith(p)` boolean, but the Compare arm above (lines 238-240) still
requires every operand to pass `_is_definitely_basic_type`, which knows `len()`
and none of the four new calls. So with transpilation and ANSI on, `'y' if
s.upper() == 'ABC' else 'n'` gets the numeric category from the catch-all in
`_category_uncached` (lines 736-740), and `_convert_if_like` lowers its test to
`coalesce(<boolean> != 0, false)` (lines 272-273). ANSI coercion has no rule
that reconciles a boolean with an integer, and the option is type-checked as a
child of TranspiledPythonUDF before ConvertToCatalyst can drop it, so analysis
fails the whole query with DATATYPE_MISMATCH; on the base branch the same UDF
runs as interpreted Python. The same label lets `return s.upper() == 'A'`
declared `bigint` return 1/0 where the interpreted converter returns NULL for a
Python bool, and makes `(s.upper() == 'A') + 1` fail analysis. A call wrapped
in
`len()` is unaffected, and the base branch already fails this way for a
comparison over a comparison or a ternary, such as `(a < b) == True`. The new
tests use only a bare `s.startswith('a')` as an if test, so none of these
shapes is exercised.
**Recommended change:** In `_category_uncached` in
python/pyspark/sql/transpile.py, add an arm ahead of the final catch-all that
returns bool for every comparison node, so a comparison over a lowered
string-method call, or over a ternary or another comparison, is classified as
the boolean column its lowering produces; leave `_is_definitely_boolean` and
`_is_definitely_basic_type` unchanged. Add transpiler unit tests for
comparisons over a lowered call used as an if-statement test, a ternary test
and a return value.
**Why this works:** With comparisons classified as bool, an if or ternary
test over such a comparison lowers to `coalesce(test, false)` instead of
comparing a boolean column with 0, the return-type gate lowers it only for a
BooleanType declaration and lets a numeric declaration fall back to the
interpreted path, which returns NULL, and the binary-operator check refuses a
boolean plus an integer so `(s.startswith('a') == True) + 1` falls back instead
of failing analysis.
**Risks:** UDFs declared BooleanType that return a comparison over a lowered
call, which run as interpreted Python today, will lower to Catalyst and change
their plans; setting spark.sql.experimental.optimizer.transpilePyUDFs to false
restores interpreted execution. Comparisons over a ternary or another
comparison used as an if or ternary test, which fail analysis on the base
branch, will lower correctly or fall back instead, a behavior change beyond the
string-method calls.
**Constraints:** Keep `_is_definitely_boolean` unchanged, so `not`, `and`
and `or` over comparisons with lowered calls keep falling back until and/or
chains carry None-check narrowing.
**Exclusions:**
- Lowering `not`, `and` and `or` over comparisons with lowered calls, which
should wait for the and/or narrowing fix.
**Verification:**
- **Regression:** With transpilation and ANSI on over UTF8_BINARY string
columns, UDFs whose if-statement test or ternary test compares a lowered
string-method call (for example `s.startswith('a') == False` or
`s.startswith('a') == t.endswith('b')`) run, evaluate no Python UDF and return
the interpreted Python result for every row.
- **Behavior:** A UDF returning such a comparison lowers and matches Python
under BooleanType, falls back and returns NULL under LongType, and one that
adds 1 to the comparison falls back and matches Python.
- **Compatibility:** A comparison over a ternary operand used as an if test,
which fails analysis on the base branch, now runs and matches Python, and
comparisons whose operands are parameters, literals or len() keep their current
lowering.
##########
python/pyspark/sql/transpile.py:
##########
@@ -299,6 +314,15 @@ def _null_narrowed(params: List[str], test_node: ast.AST)
-> Tuple[frozenset, fr
return frozenset(), frozenset()
+# ``str`` method -> (Catalyst function, argument count, result category).
+_STRING_METHODS: dict[str, Tuple[Callable[..., Column], int, str]] = {
+ "upper": (upper, 0, "string"),
Review Comment:
**Non-blocking (P2):** Catalyst `upper` and `lower` do not use CPython's
case data. For non-ASCII UTF8_BINARY input they call ICU's one-argument
`UCharacter.toUpperCase(String)` and `toLowerCase(String)`
(CollationAwareUTF8String.java:403-407, 439-443), which ICU documents as using
the JVM default locale and which carry ICU4J 78.3's Unicode data, or, with
spark.sql.icu.caseMappings.enabled off, `String.toUpperCase()` and
`toLowerCase()` (UTF8String.java:828-829, 859-860) with Java's tables; the
interpreted UDF uses the worker CPython's own, locale-independent database. The
Unicode versions differ: CPython 3.11 to 3.13 ship Unicode 14.0 to 15.1, which
give U+019B no uppercase, while ICU 78's data maps it to U+A7DC, and Java 17's
Unicode 13 tables leave U+2C2F unchanged where CPython 3.12 lowercases it to
U+2C5F. Under a Turkish or Azeri default locale, 'i' followed by U+00DF also
uppercases to U+0130 followed by 'SS' instead of CPython's 'ISS'. With
transpilation on, those rows sil
ently differ from the Python result; pure-ASCII strings take Spark's
locale-independent fast path. The module docstring (transpile.py:42-48) says
both sides apply the same mappings, while the new property tests avoid exactly
these characters because, as their comment says, CPython and ICU can ship
different Unicode versions.
**Recommended change:** Remove the `upper` and `lower` entries from
`_STRING_METHODS` in python/pyspark/sql/transpile.py and their imports, keeping
`startswith` and `endswith`; rewrite the module docstring paragraph at
transpile.py:42-48 to describe only the affix lowering and to say that
`upper()`/`lower()` stay interpreted because Spark's case mapping (ICU or the
JDK, under the JVM default locale) can differ from CPython's; in the transpiler
unit tests assert that `upper`/`lower` UDFs fall back while the affix cases
keep their value and NULL checks, and drop the `upper`/`lower` property-based
tests and their restricted case alphabet.
**Why this works:** Without table entries, `s.upper()` and `s.lower()` reach
no lowering arm, so every such UDF runs as interpreted Python and returns
CPython's result for every character and every executor locale.
**Risks:** UDFs that call `s.upper()` or `s.lower()` go back to running in a
Python worker, as on the base branch, losing the JVM speedup this PR adds for
them; re-adding the table entries later restores it.
**Constraints:** Keep the startswith/endswith lowering, its NULL guard and
its tests, changing only fixtures that used `upper()` or `lower()`.
**Exclusions:**
- Changing Spark's own upper/lower to use the root locale, which would
affect every SQL and DataFrame caller.
- A parity-gated case-mapping lowering.
**Verification:**
- **Behavior:** With transpilation and ANSI on, UDFs calling `upper()` and
`lower()` build no transpiled option, run as interpreted Python and return
CPython's result, including for code points whose case mapping changed in
Unicode 14 and 16.
- **Compatibility:** startswith/endswith UDFs keep lowering, with no Python
evaluation in the executed plan, and keep their value and NULL behavior.
- **Inspection:** The module docstring and the test comments no longer state
that upper/lower results match interpreted Python.
##########
python/pyspark/sql/transpile.py:
##########
@@ -993,6 +1028,27 @@ def _convert_chunk(self, params: List[str], body: ast.AST
| None) -> Column:
)
self._null_guard_emitted = True
return when(arg_col.isNull(),
raise_error(err)).otherwise(length(arg_col))
+ case ast.Call(
+ func=ast.Attribute(value=receiver, attr=method), args=args,
keywords=[]
+ ) if method in _STRING_METHODS and len(args) ==
_STRING_METHODS[method][1]:
+ # SPARK-59816: Python raises on a ``None`` receiver or
argument,
+ # while the Catalyst function returns NULL, so guard like
``len``.
+ self._category(params, body) # raises for a non-string operand
+ operands = [receiver, *args]
+ cols = [self._convert_chunk(params, n) for n in operands]
+ func = _STRING_METHODS[method][0]
+ if all(self._is_nonnull_node(params, n) for n in operands):
Review Comment:
**Non-blocking (P2):** `_is_nonnull_node` recognizes literals, narrowed
parameters and `len(x)` but none of the new calls, so this check is False
whenever an operand is itself a lowered string-method call, as are the `len()`
and ordering-comparison guards that consult it (transpile.py:1022 and 591).
With transpilation on, `s.lower().startswith('http') if s is not None else
False` lowers the inner `lower(s)` unguarded but wraps the outer call in
`when(isnull(lower(s)) | isnull('http'), raise_error(...))`, which can never
fire. It still sets the NULL-guard flag, so building the UDF warns the user to
add the `is not None` guard they already wrote; it keeps the lowered predicate
throwable, so the None check does not restore pushdown below joins; and each
row computes `lower(s)` twice, since CaseWhen exposes only its first condition
to subexpression elimination. Without the None check the inner guarded call
repeats at every level, so a chain of depth d evaluates its innermost call 2^(d
-1) times. A lowered call never yields NULL, because its lowering either has
non-null operands or raises, so results stay correct; only the guard decision
is wrong.
**Verification:**
- **Behavior:** With transpilation and ANSI on, a narrowed body that passes
a lowered string-method call to another guarded lowering lowers with no Python
UDF in its executed plan, builds with no NULL-guard warning, has no raise_error
in its optimized plan, and returns the interpreted result on non-NULL and NULL
rows; examples are an ordering comparison of two affix results inside an `if s
is not None` ternary, which lowers only once comparisons over lowered calls are
classified as boolean, and, while case-mapping calls are lowered, a chained
`lower()` followed by `startswith`.
- **Regression:** The same comparison without the `is not None` branch
contains each affix call once in its optimized plan and still raises the
transpiler's NULL-operand error for a NULL row.
##########
python/pyspark/sql/transpile.py:
##########
@@ -993,6 +1028,27 @@ def _convert_chunk(self, params: List[str], body: ast.AST
| None) -> Column:
)
self._null_guard_emitted = True
return when(arg_col.isNull(),
raise_error(err)).otherwise(length(arg_col))
+ case ast.Call(
+ func=ast.Attribute(value=receiver, attr=method), args=args,
keywords=[]
+ ) if method in _STRING_METHODS and len(args) ==
_STRING_METHODS[method][1]:
+ # SPARK-59816: Python raises on a ``None`` receiver or
argument,
+ # while the Catalyst function returns NULL, so guard like
``len``.
+ self._category(params, body) # raises for a non-string operand
+ operands = [receiver, *args]
+ cols = [self._convert_chunk(params, n) for n in operands]
+ func = _STRING_METHODS[method][0]
+ if all(self._is_nonnull_node(params, n) for n in operands):
+ return func(*cols)
+ null_guard = cols[0].isNull()
+ for c in cols[1:]:
+ null_guard = null_guard | c.isNull()
+ err = lit(
+ f"Python UDF transpiler: cannot call str.{method}() with a
NULL "
+ "operand; Python would raise here. Add an `is not None`
guard "
+ "or filter NULLs upstream."
+ )
+ self._null_guard_emitted = True
+ return when(null_guard,
raise_error(err)).otherwise(func(*cols))
Review Comment:
**Non-blocking (P2):** The BoolOp arm converts every `and`/`or` operand with
the same set of narrowed parameters (transpile.py:787-832), so after `s is not
None and`, each later call keeps this guard. In `df.select(f('s'))` with `f =
udf(lambda s: s is not None and (s.lower().startswith('http') or
s.lower().startswith('ftp')), 'boolean')`, both `or` operands test `isnull(G)`
for the identical guarded `G = CASE WHEN s IS NULL THEN raise_error(...) ELSE
lower(s) END`. With spark.sql.subexpressionElimination.skipForShortcutExpr
false by default, EquivalentExpressions treats both operands of And and Or as
always evaluated and counts `isnull(G)` twice
(EquivalentExpressions.scala:129-170), and whole-stage ProjectExec evaluates
every common subexpression before the projection
(basicPhysicalOperators.scala:76-98). Reading that code, a NULL row therefore
reaches `raise_error` and fails the query with 'cannot call str.lower() with a
NULL operand', where Python short-circuits and returns Fa
lse; the base branch runs this body as interpreted Python. The same applies to
`s is None or ...` chains and to the same affix call written twice, while a
filter probably keeps the short circuit because FilterExec emits a common
subexpression just before the predicate that first uses it. The base branch
already lowers `s is not None and (len(s) > 10 or len(s) < 2)` to the same
shape, and no test runs such a chain over a NULL row.
**Recommended change:** In the BoolOp arm of `_convert_chunk` in
python/pyspark/sql/transpile.py, convert each `and` operand with
`_nonnull_params` extended by the true-branch narrowing of the operands before
it, and each `or` operand with it extended by their false-branch narrowing,
using `_null_narrowed` as the ternary and if arms do, and restore the previous
set afterwards. Add transpiler unit tests that project such chains over a
column containing NULL.
**Why this works:** A parameter that an earlier `and` operand proves
non-null, or that the failure of an earlier `or` operand proves non-null, is
non-null in the later operands, so calls that take that parameter directly
lower without raise_error guards and no hoisted common subexpression can raise
on a row that Python's short circuit would have skipped; a chained call such as
`s.lower().startswith('http')` also loses its outer guard once lowered
string-method calls are treated as non-null.
**Risks:** Bodies such as `s is not None and s.startswith('x')`, and the
base branch's `s is not None and len(s) > 3`, lower without a guard in their
later operands, so their plans change: the predicate becomes pushable and the
NULL-guard warning no longer fires for them; setting transpilePyUDFs to false
restores interpreted execution.
**Constraints:** Apply narrowing only to parameters that a preceding operand
proves non-null in Python's left-to-right short-circuit order, and keep falling
back for a literal None operand as the BoolOp arm does today. Land it with the
non-null treatment of lowered string-method calls while `upper()` and `lower()`
stay lowered: without that, a chained call repeated after the None check keeps
an outer guard that tests the inner call for NULL, which the projection can
still evaluate ahead of the short circuit.
**Exclusions:**
- Changing how subexpression elimination treats And/Or or throwable
expressions.
**Verification:**
- **Regression:** With transpilation and ANSI on, projecting `s is not None
and (len(s) > 10 or len(s) < 2)`, an and/or chain that repeats the same affix
call after the None check and, while case-mapping calls are lowered, `s is not
None and (s.lower().startswith('http') or s.lower().startswith('ftp'))` over a
column containing NULL returns the interpreted result for every row.
- **Behavior:** An `or` chain starting with `s is None` returns True for
NULL rows without raising, the optimized plans have no raise_error in operands
after the None check (for a chained call, once lowered string-method calls are
treated as non-null), and an operand that no earlier None check covers still
raises the transpiler's NULL-operand error on a NULL row.
##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -2631,6 +2631,47 @@ def test_udf_transpile_string_len(self):
self._raises(strlen, "a string", [(None,)], needle="len()")
self._raises(strlen, "a long", [(5,)], needle="")
+ def test_udf_transpile_string_methods(self):
+ # SPARK-59816: upper/lower/startswith/endswith lower to Catalyst and
match
+ # Python, including full Unicode case mappings (sharp s, final sigma).
A NULL
+ # receiver or argument raises like CPython, a proven-non-null branch
skips
+ # the guard, and a non-string column or a start index falls back to
Python.
+ S, B = StringType(), BooleanType()
+ up = lambda s: s.upper() # noqa: E731
+ low = lambda s: s.lower() # noqa: E731
+ starts = lambda s, p: s.startswith(p) # noqa: E731
+ ends = lambda s: s.endswith("ab") # noqa: E731
+ branch = lambda s: "y" if s.startswith("a") else "n" # noqa: E731
+ negated = lambda s: not s.startswith("a") # noqa: E731
+ both = lambda s: s.startswith("a") and s.endswith("c") # noqa: E731
+ up_guarded = lambda s: s.upper() if s is not None else None # noqa:
E731
+ starts_at = lambda s: s.startswith("a", 1) # noqa: E731
+ words = [("",), ("abc",), ("straße",), ("ΟΔΟΣ",)]
+ pairs = [("abc", "ab"), ("abc", "b"), ("abc", ""), ("", "a")]
+ for func, rt, schema, rows in [
+ (up, S, "s string", words),
+ (low, S, "s string", words),
+ (starts, B, "s string, p string", pairs),
+ (ends, B, "s string", [("cab",), ("abc",), ("",)]),
+ (branch, S, "s string", [("ab",), ("ba",)]),
+ (negated, B, "s string", [("ab",), ("ba",)]),
+ (both, B, "s string", [("abc",), ("ab",), ("bc",)]),
+ ]:
+ with self.subTest(func=func):
+ expected = [func(*r) for r in rows]
+ self.assertEqual(self._vals(func, rt, schema, rows), expected)
+ self.assertEqual(self._vals(up_guarded, S, "s string", [("a",),
(None,)]), ["A", None])
+ self._raises(up, "s string", [(None,)], needle="str.upper()",
return_type=S)
+ self._raises(
+ starts, "s string, p string", [("abc", None)],
needle="str.startswith()", return_type=B
+ )
Review Comment:
**Nit (P3):** These two `_raises` calls are the only NULL-guard assertions
for the new arm: one receiver-only call and one NULL column argument with an
unnarrowed receiver. The literal-argument cases (`ends`, `branch`, `negated`,
`both`) never see a NULL row, no case narrows the receiver while the argument
is NULL (`s.startswith(p) if s is not None else None` with `p` NULL), and no
assertion checks the NULL-guard warning the arm triggers at transpile.py:1050;
test_udf_transpile_null_guard_warning builds only `x > 0`. The property tests
do not fill the gap, because `_run` replaces the interpreted value with the
transpiled one whenever only the interpreted side raised
(test_udf_transpile_hypothesis.py:507-508). So changing the skip at
transpile.py:1040 from `all(...)` to `any(...)`, or deciding it from the
receiver alone, would make `s.endswith('ab')` on a NULL row, or a NULL `p`,
return NULL instead of raising, and dropping the flag would silence the
warning, with every test still
passing.
**Verification:**
- **Regression:** Under transpilation, a NULL receiver of `s.endswith('ab')`
and a NULL `p` in `s.startswith(p) if s is not None else None` each raise the
transpiler's NULL-operand error naming the method, and building
`s.endswith('ab')` as a UDF emits the NULL-guard warning; each assertion fails
if the corresponding guard or flag is removed.
##########
python/pyspark/sql/transpile.py:
##########
@@ -993,6 +1028,27 @@ def _convert_chunk(self, params: List[str], body: ast.AST
| None) -> Column:
)
self._null_guard_emitted = True
return when(arg_col.isNull(),
raise_error(err)).otherwise(length(arg_col))
+ case ast.Call(
+ func=ast.Attribute(value=receiver, attr=method), args=args,
keywords=[]
+ ) if method in _STRING_METHODS and len(args) ==
_STRING_METHODS[method][1]:
+ # SPARK-59816: Python raises on a ``None`` receiver or
argument,
+ # while the Catalyst function returns NULL, so guard like
``len``.
+ self._category(params, body) # raises for a non-string operand
+ operands = [receiver, *args]
+ cols = [self._convert_chunk(params, n) for n in operands]
+ func = _STRING_METHODS[method][0]
+ if all(self._is_nonnull_node(params, n) for n in operands):
+ return func(*cols)
+ null_guard = cols[0].isNull()
+ for c in cols[1:]:
+ null_guard = null_guard | c.isNull()
+ err = lit(
+ f"Python UDF transpiler: cannot call str.{method}() with a
NULL "
+ "operand; Python would raise here. Add an `is not None`
guard "
+ "or filter NULLs upstream."
+ )
+ self._null_guard_emitted = True
+ return when(null_guard,
raise_error(err)).otherwise(func(*cols))
Review Comment:
**Non-blocking (P2):** This `raise_error` makes the lowered call throwable
(misc.scala:87, inherited through Expression.throwable), and ConvertToCatalyst
substitutes it before predicate pushdown runs, so `splitMovable`
(Optimizer.scala:3359-3367) keeps a filter such as `a.join(b,
'k').where(starts(a.s))`, with `starts = udf(lambda s: s.startswith('x'),
'boolean')` and a nullable `a.s`, above the join and out of its condition. On
the base branch that body is not lowered, and the deterministic, non-throwable
Python UDF is pushed to `a`, so `a` is filtered before its shuffle. With
transpilation on, every row of `a` is now shuffled and joined before the native
filter runs, an AQE broadcast that the filtered side allowed can be lost, and a
stream-stream join keeps the unfiltered rows in state. This trades against the
Python evaluation the lowering removes, so the net effect depends on
selectivity and fan-out and was not measured. The same holds above a non-outer
explode and, after a co
njunct that cannot move, above an aggregate, window or union. The existing
`len()` and comparison guards already behave this way, but neither the
transpilePyUDFs description nor the module docstring mentions the cost.
**Recommended change:** Add a sentence to the transpilePyUDFs description in
SQLConf.scala and to the NULL guard text of the module docstring in
python/pyspark/sql/transpile.py stating that a lowered UDF whose NULL guard is
kept is not pushed below joins, non-outer generates, or aggregates, windows and
unions behind a condition that cannot move, where the interpreted UDF would be,
because Catalyst never moves a raise_error there, and that an `if x is not
None` (or ternary) branch around the call removes the guard; extend the
NULL-guard warning in `_transpile_from_ast` (transpile.py:1142-1150) with the
same pointer.
**Why this works:** The disclosure makes the placement cost a stated cost of
the default-off feature and tells users the narrowing that gives a lowered
predicate the interpreted UDF's placement back.
**Risks:** Plans do not change, so selective predicates over joins keep
shuffling the rows the base branch filtered first until users add the narrowing
or a later change adds placement-aware fallback.
**Constraints:** Promise the workaround only for forms that drop the guard
when the change lands: an `if x is not None` or ternary branch around a single
call, plus chained calls and `and` chains only if their narrowing fixes land
with it.
**Exclusions:**
- Placement-aware fallback to the interpreted UDF above joins.
- A benchmark of the net cost against interpreted execution.
**Verification:**
- **Inspection:** The transpilePyUDFs description, the module docstring and
the NULL-guard warning each state the placement cost of a kept NULL guard and
the narrowing that removes it, and the warning still contains the NULL guard
wording that existing warning assertions look for.
--
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]