spark-test commented on code in PR #59722:
URL: https://github.com/apache/spark/pull/59722#discussion_r4606165582
##########
python/pyspark/sql/transpile.py:
##########
@@ -1145,36 +1201,50 @@ def _annotation_category(annotation: Optional[ast.AST])
-> Optional[str]:
return "bool"
if name == "bytes":
return "binary"
+ if name in ("dict", "Dict", "Mapping"):
Review Comment:
**Blocking (P1):** With transpilation on, this pin, like the
`list`/`List`/`Sequence` ones and the new `MapType`/`ArrayType` arms in
`ResolveTranspiledPythonUDFOptions`, keeps a native option for a call whose
container parameter is bound to a map or array column. That option now reaches
a gap in category inference: `_is_definitely_basic_type` (lines 192-212) has no
case for a comparison, a boolean operation or a ternary, so
`_is_definitely_boolean` rejects a comparison or identity test whose operand is
one of those (a null test included, or a `not` of one), and `_safe_category`
and `_category` fall through to the numeric catch-all. The container refusals
this PR adds check only an operand's own category, which a null test (`bool`)
never is.
Reading the code, that gives two outcomes for calls the base branch ran in
Python:
- Returned under a non-decimal numeric type, the return-type gate accepts
the body and casts a boolean to that type. `def f(a: dict, b: dict): return (a
is None) != (b is None)` declared `LongType()` on two map columns returns 0 or
1, where interpreted Python returns NULL because its `LongType` converter nulls
a bool; `(a is None) is None` always returns 0.
- Used as an `if` or ternary test, the test gets the numeric truthiness
lowering `<bool> != 0`, which ANSI analysis rejects, so `if (a is None) == (b
is None): return "same"` on two array columns fails the whole query. Arithmetic
such as `((a is None) != (b is None)) * 2` fails the same way.
The comparison does not have to read the container: in `def f(a: list, b:
int, c: int): return (b > 0) == (c > 0)` declared `LongType()`, an array column
bound to `a` is enough to keep the option, which returns 0 or 1.
Scalar-annotated and untyped parameters already reach this lowering on the base
branch.
This extends an [existing
discussion](https://github.com/apache/spark/pull/59722#discussion_r4506470847).
**Recommended change:** In python/pyspark/sql/transpile.py, extend
_is_definitely_basic_type (lines 192-212) so that a comparison, a boolean
operation, and a ternary count as basic when all of their operands or branches
are basic. _is_definitely_boolean (lines 228-230) then accepts a comparison or
identity test whose operands are such comparisons (null tests included),
boolean operations, ternaries or a `not` of one of them, so _safe_category and
_category classify it as bool: the return-type gate (lines 1094-1114) refuses
it under a numeric return type, arithmetic refuses it as an operand, and
_convert_if_like (lines 415-426) lowers an if/ternary test over it with
coalesce(test, false) instead of the numeric != 0 test. Keep the
container-branch refusal at lines 437-441, added in commit a892f6b43c4, and the
map and array refusals in _lower_eq and _lower_value_compare. Add PySpark UDF
transpilation tests for these shapes on map, array and scalar columns.
**Why this works:** The built-in transpiler classifies a node as bool only
through these two predicates, so counting comparisons, boolean operations and
ternaries over basic values as basic operands makes every comparison over them
bool, and the existing rules then apply unchanged: a bool body is refused under
a numeric return type, a bool operand is refused by arithmetic and by
comparison with a number, and a boolean if/ternary test is lowered with
coalesce(test, false), which matches how Python treats a bool test.
**Compatibility:** Bare is None and is not None tests on map- and
array-category parameters, bodies that ignore a container argument, and every
lowering whose comparison operands are names, constants, arithmetic or len keep
the options they produce today.
**Risks:** Plans change for scalar inputs that reach the same shapes:
numeric-declared returns and arithmetic over a comparison of comparisons, such
as (x > 0) == (y > 0), which today return 0 or 1 or fail analysis, fall back to
interpreted Python, while BooleanType-declared returns and `not`, `and` or `or`
over such comparisons, which today fall back, and if/ternary tests over them,
which today fail analysis, now lower natively; removing the added predicate
cases restores today's behavior.
**Constraints:** Count a comparison, boolean operation or ternary as basic
only when every operand or branch is basic, so a comparison over a subscript,
call or attribute stays unclassified and keeps falling back.
**Exclusions:**
- Recognizing Optional-, Union- and | None-wrapped container annotations,
which depends on the author's answer to the open question about those spellings.
**Verification:**
- **Regression:** With transpilation on, for each of ==, !=, <, <=, >, >=,
is None and is not None, a UDF declared LongType that returns that comparison
with an operand that is a null test of a list- or dict-annotated parameter, an
`and` or `or` of such null tests, a ternary choosing between them, or a `not`
of one, on map or array columns, produces no transpiled option and returns NULL
for every row, matching transpilation off; so does a UDF that returns (b > 0)
== (c > 0) for non-NULL b and c while its list-annotated parameter is bound to
an array column.
- **Regression:** With transpilation on, on two array columns, UDFs whose if
statement or ternary tests (a is None) == (b is None), ((a is None) or (b is
None)) == False, or (a is None) < (b is None) run without an analysis error and
return the same values as with transpilation off for rows where neither, one,
or both arrays are NULL.
- **Regression:** With transpilation on, a UDF declared LongType that
returns ((a is None) != (b is None)) * 2 over two map columns falls back to
interpreted Python and returns 0 or 2 as Python does.
- **Behavior:** With transpilation on, a UDF declared BooleanType that
returns (a is None) != (b is None) over two map columns runs without a Python
evaluation step and returns the same values as with transpilation off.
- **Compatibility:** The same shapes over str-annotated and untyped
parameters on string columns return the values transpilation off returns, and
bare is None and is not None tests on map and array columns still run without a
Python evaluation step.
##########
python/pyspark/sql/transpile.py:
##########
@@ -30,8 +30,10 @@
untyped parameter is transpiled into one option per input-type category
(numeric and string) and the JVM picks the one matching the bound column
types -- falling back to interpreted Python when none fit. Annotating the
-UDF's parameters (e.g. ``def f(a: int, b: str)``) pins each category and
-keeps the option matrix small; prefer doing so. To bound plan growth,
+UDF's parameters (e.g. ``def f(a: int, b: str)``) pins each category --
+numeric, string, bool, binary, or map/array for dict/list annotations --
+and keeps the option matrix small; prefer doing so. A ``Sequence``
+annotation is tried as both array and string, since a ``str`` is one too. To
bound plan growth,
functions with more than three untyped parameters only emit the
all-numeric and all-string variants.
Review Comment:
**Nit (P3):** The cap sentence still counts only untyped parameters, but
`_param_category_combos` counts a `Sequence` parameter as unpinned (line 1244)
and, past three unpinned parameters, gives it only the integer, float and
string fills (lines 1245-1251). So by this docstring `def f(s: Sequence, a, b,
c)` gets the full product with `s` tried as an array, while the code emits
three scalar variants, and an array column bound to `s` always runs as
interpreted Python with no warning to say why. The `_param_category_combos`
docstring already states the real rule.
```suggestion
and keeps the option matrix small; prefer doing so. To bound plan growth,
functions with more than three unpinned (untyped or ``Sequence``) parameters
only emit the all-integer, all-float and all-string variants; below that cap
a ``Sequence`` annotation is tried as both array and string, since a ``str``
is one too.
```
**Verification:**
- **Inspection:** The module docstring's description of the plan-growth cap
and of Sequence annotations matches what the combo builder emits for a Sequence
parameter at and past the cap, including a four-parameter UDF with one Sequence
and three untyped parameters.
--
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]