spark-test commented on code in PR #59216:
URL: https://github.com/apache/spark/pull/59216#discussion_r4602666075
##########
python/pyspark/sql/transpile.py:
##########
@@ -238,6 +401,93 @@ def _is_definitely_boolean(node: ast.AST) -> bool:
return False
+def _is_never_null_boolean(node: ast.AST) -> bool:
+ """Return True when ``node`` lowers to a boolean column that is never NULL.
+
+ Stricter than ``_is_definitely_boolean``, which also accepts operands that
+ may evaluate to NULL. ``and`` / ``or`` need that of every operand before
the
+ last: Spark's ``NULL AND false`` is ``false`` where Python's ``None and
+ False`` is ``None``, and rejecting a bare ``None`` operand is not enough
+ because a ternary can evaluate to one (``(True if c else None) and x``).
The
+ last operand is returned as it is, NULL included, so it may be NULL.
+
+ ``not`` and if/ternary *tests* do not need this: both wrap the operand in
+ ``coalesce``, so both handle NULL explicitly. ``not`` gates on
+ ``_is_definitely_boolean``; an if/ternary test that fails that gate falls
to
+ ``_truthiness_col`` (SPARK-56925), which coalesces in every category, so a
+ bare ``if x`` is total too.
+
+ This answers "would it be NULL?", not "can it be lowered at all" -- it says
+ True for shapes ``_convert_chunk`` goes on to refuse, such as ``x in
"abc"``.
+ """
+ match node:
+ case ast.Constant(value=v):
+ # A literal None is "boolean" for coalesce purposes but IS NULL.
+ return isinstance(v, bool)
+ case ast.Compare():
+ # Under strict null strictness every comparison lowering is total
+ # (see ``_lower_compare_pair``), so only the operand shapes still
+ # need checking. Under loose an ordering comparison can be NULL,
+ # which is that setting's documented difference from Python.
+ return _is_definitely_boolean(node)
+ case ast.UnaryOp(op=ast.Not()):
+ # Lowered as ``coalesce(~operand, lit(True))``, which is total.
+ return True
+ case ast.BoolOp(values=values):
+ return all(_is_never_null_boolean(v) for v in values)
+ case ast.IfExp(body=body, orelse=orelse):
+ return _is_never_null_boolean(body) and
_is_never_null_boolean(orelse)
+ case _:
+ return False
+
+
+def _is_none_constant(node: ast.AST) -> bool:
+ """Return True for the literal ``None``."""
+ return isinstance(node, ast.Constant) and node.value is None
+
+
+def _needs_atomic_boolops(body: ast.AST) -> bool:
+ """Return True when ``body`` holds a chained comparison or a comparison
over
+ a non-basic operand (a comparison, ``and`` / ``or``, ternary, ...).
+
+ Such a body only lowers since chained and nested comparisons do, so it has
no
+ ``&`` / ``|`` plan to preserve, and its ``and`` / ``or`` take the
sequential
+ CASE WHEN fold that the optimizer cannot split (see the module docstring).
+ """
+ return any(
+ isinstance(n, ast.Compare) and (len(n.ops) > 1 or not
_is_definitely_boolean(n))
+ for n in ast.walk(body)
+ )
+
+
+def _holds_raising_lowering(body: ast.AST) -> bool:
+ """Conservatively flag calls and arithmetic that can raise under loose
too."""
+ return any(
+ isinstance(n, (ast.Call, ast.BinOp))
+ or (isinstance(n, ast.UnaryOp) and isinstance(n.op, (ast.UAdd,
ast.USub)))
+ for n in ast.walk(body)
+ )
+
+
+def _short_circuit(operands: List[Column], stop_on: bool) -> Column:
+ """Fold boolean ``operands`` so that each is evaluated only when every
+ earlier one differs from ``stop_on``, which is then the result:
+ ``CASE WHEN NOT o1 THEN false ... ELSE oN END`` for ``stop_on=False``
+ (``and``, chain links) and ``CASE WHEN o1 THEN true ... ELSE oN END`` for
+ ``stop_on=True`` (``or``). Every operand before the last must be non-NULL:
a
+ NULL condition takes no branch, so the fold would skip it. That holds only
+ under strict null strictness (see ``CatalystTranspiler._fold_boolean``).
+ """
+ *earlier, last = operands
+ if not earlier:
+ return last
+ conditions = earlier if stop_on else [~o for o in earlier]
+ fold = when(conditions[0], lit(stop_on))
+ for condition in conditions[1:]:
+ fold = fold.when(condition, lit(stop_on))
+ return fold.otherwise(last)
Review Comment:
**Blocking (P1):** Under the default strict null strictness this fold gives
every earlier operand the branch value `lit(stop_on)` and makes the last
operand the ELSE. When that operand is, or constant-folds to, the stop value,
every result value is equal, and SimplifyConditionals
(optimizer/expressions.scala:858-877) replaces the whole CASE WHEN with it.
`RaiseError` keeps the default `deterministic`, so nothing stops the rule, and
the earlier operands' NULL guards are deleted.
Reading the code, `(0 < x < 10) and False` declared BooleanType lowers to
`CASE WHEN NOT (<chain>) THEN false ELSE false END`, which the
operator-optimization batch rewrites to `false`. A row with x = NULL therefore
returns False where Python raises TypeError at `0 < None`. `(0 < x < y) or
True` returns True there, `x < 5 < 3` returns False once ConstantFolding
reduces `5 < 3`, and as a filter `... or True` keeps those rows. The same
happens to folds in bodies with no chain, such as `((x > 0) or True) == True`,
and to an if/ternary with equal branches such as `y if (0 < x < 10) else y`.
The base branch ran all of these bodies as interpreted Python, which raises.
The CASE WHEN fold exists so that these newly lowered bodies keep Python's
errors through optimizer rewrites, and the module docstring's statement that it
is atomic to the optimizer does not hold for this rule. This applies only with
transpilePyUDFs and ANSI on, under strict null strictness.
This extends existing discussions
[1](https://github.com/apache/spark/pull/59216#discussion_r4260389154),
[2](https://github.com/apache/spark/pull/59216#discussion_r4584336045).
**Recommended change:** Make the strict fold return each earlier operand on
its own stop branch: `CASE WHEN NOT o1 THEN o1 ... ELSE oN END` for `and` and
for chain links, and `CASE WHEN o1 THEN o1 ... ELSE oN END` for `or`. In a body
that takes this fold, make an if/ternary fall back to interpreted Python when
its two branches could lower to the same expression: identical source,
constants that compare equal, or parameter-free expressions that are not both
constants. Leave a TODO at that check naming branches that only the bound
columns' nullability makes equal. Charge the fold's second reference to each
earlier operand in the materialized-size estimate. Correct the module
docstring's claim that the CASE WHEN is atomic to the optimizer, and add Python
UDF transpiler unit tests for folds whose last operand is or folds to the stop
value, in chain-holding and nested-comparison bodies, and for an if/ternary
with equal branches.
**Why this works:** On the branch where an earlier operand decides the
result, that operand is exactly the stop value: false where `NOT o` holds, true
where `o` holds, and never NULL under strict null strictness. Returning it
gives the same answer, and SimplifyConditionals can drop a condition only when
every branch value equals the ELSE value. With operand-valued branches that
happens only when every earlier operand is the same expression as the last one,
and then the remaining ELSE still evaluates that operand and its guard. An
if/ternary has no such value to return, so the bodies where its branches can be
equal fall back, as they did on the base branch.
**Scope:** Change the strict fold's branch values and the if/ternary
lowering in the bodies that take the fold, charge the fold's added reference in
the size estimate, and cover the collapsing shapes in the transpiler's unit
tests.
**Compatibility:** Every lowered chain and chain-holding `and` / `or` keeps
Python's short-circuit order and answers, single comparisons keep their
lowering, and the loose fold is unchanged.
**Risks:** On the row where an earlier operand decides a strict fold, that
operand is evaluated a second time. The estimated size of chains, and of `and`
/ `or` in chain-holding bodies, grows by each earlier operand, so a nested body
close to the 65,536-node bound can now fall back to Python. Restoring the
literal-valued fold rolls this back. An if/ternary in a chain-holding body
whose two branches could lower to the same expression now runs as interpreted
Python, as it did on the base branch.
**Constraints:** Earlier operands of the fold stay never-NULL booleans,
which holds only under strict null strictness; the loose `&` / `|` fold and its
fallback are unchanged. Bodies the base branch lowers, with no chain and no
comparison over a non-basic operand, keep their `&` / `|` expressions and
plans. The materialized-size estimate charges the added reference to each
earlier operand, and whatever decides whether a body is bounded must see that
charge, so nests of folds stay bounded.
**Exclusions:**
- The base branch's BooleanSimplification and subexpression-elimination
divergences for `&` / `|` bodies stay with the separately tracked optimizer
work.
- An if/ternary whose branches differ in source but fold to the same
expression only through the bound columns' nullability or a later optimizer
rule, such as `(x is not None) if 0 < y < 9 else True` over a non-nullable `x`,
still collapses and returns its branch value on rows where Python raises; the
transpiler cannot see column nullability, so a TODO at the branch check names
the case.
**Success:** Under strict null strictness, a chain or `and` / `or` fold
whose last operand is, or folds to, its stop value raises like Python when an
earlier operand's NULL guard fires, and stays lowered. An if/ternary whose two
branches could lower to the same expression, in a body holding a chain or a
comparison over a non-basic operand, falls back to interpreted Python and
returns Python's answer. Every other lowered chain and `and` / `or` in such
bodies returns the same answers as before, and bodies without them emit the
same expressions as before. Nests of folds past the materialized-size bound are
still refused. The module docstring explains why the fold returns each operand,
instead of claiming the CASE WHEN is atomic to every optimizer rule.
**Verification:**
- **Regression:** Under strict null strictness and both expression factory
modes, every fold in a body holding a chain or a comparison over a non-basic
operand whose last operand is or folds to its stop value raises like Python on
a NULL earlier operand, in a projection and as a filter, with no Python
evaluation node. Cases include `(0 < x < 10) and False`, `(0 < x < y) or True`,
`x < 5 < 3`, `(0 < y < 10) or (x is not None)` over a non-nullable `x`, and the
chain-free `((x > 0) or True) == True`.
- **Regression:** An if/ternary with identical branches whose test is a
chained comparison, such as `y if (0 < x < 10) else y`, falls back to
interpreted Python and raises TypeError for a NULL `x` as Python does.
- **Compatibility:** Chain short-circuit cases, every `==` NULL pattern, the
common-factor, absorption and aggregate shapes, the nullable-last-operand cases
and the loose-mode cases keep their answers and their lowering. Bodies without
a chain or nested comparison keep their `&` / `|` expressions.
- **Behavior:** With the fold's added reference charged, nests of chains and
`and` / `or` folds past the materialized-size bound are refused with the weight
message, and the shallow nests the bound admits still lower.
##########
python/pyspark/sql/transpile.py:
##########
@@ -187,6 +288,63 @@ def _transpile_from_ast(
pass
+def _multi_read_operands(node: ast.AST) -> List[ast.AST]:
+ """The operands whose Column the lowering of ``node`` reads more than
once."""
+ match node:
+ case ast.Compare(left=left, ops=ops, comparators=comps):
+ nodes = [left, *comps]
+ return [
+ operand
+ for i, op in enumerate(ops)
+ if _OPERAND_READS.get(type(op), 2) > 1
Review Comment:
**Non-blocking (P2):** `is` / `is not` count as a single read here, so their
operands never enter this list. But the chain lowering hands each interior
operand's Column to both adjacent links, so in `None is X is None` both links
read X and the fold references it twice. For a nest such as `def f(y): return
None is (None is (... y ...) is None) is None`, `_expansion_compounds` is
therefore False at every depth, `_transpile_func` sets the weight to 0, and
neither size check runs, while `_materialized_weight` charges the 20-level
nest, about 360 characters, roughly 12.6 million nodes.
Reading the code, each of its three options (integer, float and string for
`y`) expands to about 7.3 million nodes at depth 20, doubling per level.
ColumnNodeToExpressionConverter (columnNodeSupport.scala:47-89) rebuilds that
tree with no cache every time the UDF is applied, outside the transpiler's
fallback. The base branch refuses chains, so the same UDF ran there as
interpreted Python. The `==` / `!=` and ordering variants are flagged and
refused; only nests of identity chains escape.
This extends an [existing
discussion](https://github.com/apache/spark/pull/59216#discussion_r4260389170).
See **Shared repair plan 1** in the review body.
##########
python/pyspark/sql/transpile.py:
##########
@@ -187,6 +288,63 @@ def _transpile_from_ast(
pass
+def _multi_read_operands(node: ast.AST) -> List[ast.AST]:
+ """The operands whose Column the lowering of ``node`` reads more than
once."""
+ match node:
+ case ast.Compare(left=left, ops=ops, comparators=comps):
+ nodes = [left, *comps]
+ return [
+ operand
+ for i, op in enumerate(ops)
+ if _OPERAND_READS.get(type(op), 2) > 1
+ for operand in nodes[i : i + 2]
+ ]
+ case ast.BinOp(op=ast.Mod(), right=right):
+ return [right]
+ case ast.Call(func=ast.Name(id="len"), args=[arg], keywords=[]):
+ return [arg]
+ case _:
+ return []
+
+
+def _expansion_compounds(body: ast.AST) -> bool:
+ """Return True when an operand that a lowering reads more than once itself
+ holds such a lowering, so the materialized size multiplies per nesting
level.
+
+ Otherwise each lowering adds a constant per term and the size stays
+ proportional to the source, however many options the body keeps; such a
flat
+ body is not bounded by ``_MAX_MATERIALIZED_WEIGHT``.
+ """
+ return any(
Review Comment:
**Non-blocking (P2):** This returns True as soon as one operand that a
lowering reads more than once holds another such lowering anywhere below it. So
one fixed-depth term such as `len(s) > 0` or `x % 2 == 0` marks the whole body
as compounding, and the body is refused once `_materialized_weight` of the
whole body times the options kept passes 65,536. Its size still grows only
linearly with the number of terms, like the flat `==` bodies this change keeps
native.
By the code's own estimate, `def f(a, b, c): return (len(a) == 0 or ... or
len(a) == 181) and b is not None and c is not None` declared BooleanType weighs
7,304 and keeps nine options. `too_heavy(9)` sees 65,736, so the UDF runs as
interpreted Python with an 'Unable to transpile UDF' warning, while the base
branch has no bound and lowers the same nine options natively. 54 `x % 7 == r`
terms over three untyped parameters are refused the same way. One such term
also pulls an otherwise exempt flat body under the bound: `len(s) > 0 and (x ==
0 or ... or x == 4099)` over `s: str, x: int` weighs 65,635 and is refused,
while the larger 4,200-term `x == i` body alone (67,208) lowers.
Results are unchanged, and whether the Python fallback is slower than the
native options at these sizes has not been measured. The change's stated rule,
though, is that flat bodies keep their native eligibility.
This extends an [existing
discussion](https://github.com/apache/spark/pull/59216#discussion_r4597548274).
See **Shared repair plan 1** in the review body.
##########
python/pyspark/sql/transpile.py:
##########
@@ -591,6 +843,97 @@ def _lower_value_compare(
self._null_guard_emitted = True
return when(null_guard, raise_error(err)).otherwise(op(left_col,
right_col))
+ def _fold_boolean(self, operands: List[Column], is_or: bool, atomic: bool)
-> Column:
+ """Fold the lowered operands of an ``and`` / ``or``, or the links of a
+ chain (``is_or=False``): the sequential CASE WHEN when ``atomic``,
+ otherwise ``&`` / ``|`` (see the module docstring).
+
+ The CASE WHEN needs every operand before the last non-NULL, which
+ comparison links are only under strict null strictness. Under loose an
+ ordering link is NULL for a NULL operand, and a CASE WHEN would skip it
+ and answer from the later operands, so loose folds with ``&`` / ``|``:
+ their three-valued logic propagates the NULL, and no ordering
+ ``raise_error`` guard is left for the optimizer to move. Calls and
+ arithmetic can still raise under loose, though, and
BooleanSimplification,
+ subexpression elimination and partition pruning can drop or hoist an
+ ``&`` / ``|`` operand, so an atomic fold in such a body falls back.
+ TODO (SPARK-54783): take the CASE WHEN there when every operand before
+ the last is never NULL under loose.
+ """
+ if not atomic or len(operands) == 1:
+ return functools.reduce(operator.or_ if is_or else operator.and_,
operands)
+ if self._null_strictness != "loose":
+ return _short_circuit(operands, stop_on=is_or)
+ if self._holds_raising_lowering:
Review Comment:
**Nit (P3):** Under `loose`, this makes an atomic fold in a body holding any
call, binary arithmetic or unary `+` / `-` fall back to interpreted Python,
while `strict` lowers the same body as a CASE WHEN. So `loose` now transpiles
fewer bodies than `strict` for chains such as `0 < x + 1 < 10`, `0 < len(s) <
10` and `-90 <= lat <= 90`, whose `-90` parses as a unary minus.
The config's public description (SQLConf.scala:730-734), which this change
leaves as it is, still says the setting controls NULL handling for ordering
comparisons and that `loose` 'allows more UDFs to be transpiled at the cost of
minor semantic divergence on NULL inputs'. Nothing in it says that `loose` also
changes how chains and `and` / `or` fold, or when they fall back, so a user who
sets `loose` to widen transpilation gets the opposite for these bodies.
`_lower_value_compare`'s docstring repeats the same claim.
**Verification:**
- **Inspection:** The transpileNullStrictness description and the
transpiler's ordering-comparison docstring describe the loose fold and its
fallback for bodies holding calls, arithmetic or a unary sign, and neither
claims that loose transpiles more UDFs than strict.
##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -1084,25 +1531,237 @@ def wrapper(x):
self.assertEqual(result[0], 60, "must run the wrapper, not the
wrapped source")
def test_udf_transpile_falls_back_for_none_in_boolop(self):
- # Python's `None and x` short-circuits to None; Spark's three-valued
- # `null AND false` is false. A literal None operand must force a
- # fallback rather than silently diverge.
- import warnings as _warnings
-
- from pyspark.sql.types import StructField, StructType
+ # Python's `None and x` short-circuits to None, which Spark's
three-valued
+ # `null AND false` (false) does not reproduce. An operand before the
last
+ # that `_is_never_null_boolean` cannot prove non-NULL -- a literal
None, or
+ # a ternary with a None branch -- must fall back rather than diverge,
and
+ # so must a literal None in last position.
+ long_schema = "a long"
def none_and(x):
return None and (x > 0)
- long_schema = StructType([StructField("a", LongType(), nullable=True)])
+ def and_none(x):
+ return (x > 0) and None
+
+ def nullable_ternary_and(x):
+ return (True if x > 0 else None) and (x > 0)
+
+ def nullable_ternary_body_and(x):
+ return (None if x > 0 else True) and (x < 0)
+
+ # A nested `and` whose last operand may be NULL, used before the last
+ # operand: only `_is_never_null_boolean`'s BoolOp arm refuses it.
+ def nullable_nested_and(x):
+ return ((x > 0) and (True if x > 5 else None)) and (x > 10)
+
with self.sql_conf(_TRANSPILE_ON):
- with _warnings.catch_warnings(record=True):
- _warnings.simplefilter("always")
- pudf = UserDefinedFunction(none_and, BooleanType())
- self.assertEqual([], pudf.transpiled, "literal None in and/or must
not transpile")
- df = self.spark.createDataFrame([Row(a=-5)], schema=long_schema)
- [result] = df.select(pudf("a")).collect()
- self.assertIsNone(result[0])
+ # Each case is probed where Python returns None. An `&` fold would
+ # return False there for every case but `and_none`, which falls
back
+ # because a literal None last operand has no boolean type.
+ for func, value in [
+ (none_and, -5),
+ (and_none, 5),
+ (nullable_ternary_and, -5),
+ (nullable_ternary_body_and, 5),
+ (nullable_nested_and, 1),
+ ]:
+ with self.subTest(func=func.__name__):
+ pudf, _ = self._fallback_reason(func, BooleanType())
+ df = self.spark.createDataFrame([(value,)], long_schema)
+ [result] = df.select(pudf("a")).collect()
+ self.assertIsNone(result[0])
+
+ def test_udf_transpile_nullable_last_boolop_operand(self):
+ # `and` / `or` return their last operand as it is, so it may be NULL:
+ # `false AND v` is false without evaluating `v` and `true AND v` is
`v`,
+ # like Python's `False and v` and `True and v`. Returned, as an
if/ternary
+ # test and under `not`, with both the `&` and the CASE WHEN fold.
+ B, L = BooleanType(), LongType()
+ rows = [(1, 1), (1, -1), (-1, 1), (-1, -1), (-1, None)]
+ and_last = lambda x, y: (x > 0) and (True if y > 0 else None) # noqa:
E731
+ or_last = lambda x, y: (x < 0) or (True if y > 0 else None) # noqa:
E731
+ guarded = lambda x, y: (x > 0) and ((y < 10) if y is not None else
None) # noqa: E731
+ as_test = lambda x, y: 1 if ((x > 0) and (True if y > 0 else None))
else 0 # noqa: E731
+ negated = lambda x, y: not ((x > 0) and (True if y > 0 else None)) #
noqa: E731
+ chain_and = lambda x, y: (0 < x < 10) and (True if y > 0 else None) #
noqa: E731
+ chain_negated = lambda x, y: not ((0 < x < 10) and (True if y > 0 else
None)) # noqa: E731
+ # Earlier operands of each shape the never-NULL gate accepts besides a
+ # comparison: a `not`, a ternary with never-NULL branches, a literal.
+ not_first = lambda x, y: (not (x < 0)) and (True if y > 0 else None)
# noqa: E731
+ ternary_first = lambda x, y: ((x > 0) if x > -5 else (x < -9)) and (x
< 9) # noqa: E731
+ literal_first = lambda x, y: True and (x > 0) # noqa: E731
+ cases = [
+ (not_first, B, rows),
+ (ternary_first, B, rows),
+ (literal_first, B, rows),
+ (and_last, B, rows),
+ (or_last, B, rows),
+ (guarded, B, rows + [(1, None)]),
+ (as_test, L, rows),
+ (negated, B, rows),
+ (chain_and, B, rows),
+ (chain_negated, B, rows),
+ ]
+ for factory_mode in ("FALLBACK", "NO_CODEGEN"):
+ conf = {"spark.sql.codegen.factoryMode": factory_mode}
+ for i, (func, return_type, func_rows) in enumerate(cases):
+ with self.subTest(factory_mode=factory_mode, case=i),
self.sql_conf(conf):
+ self.assertEqual(
+ self._vals(func, return_type, "a long, b long",
func_rows),
+ [func(*row) for row in func_rows],
+ )
+
+ def test_udf_transpile_loose_null_strictness_folds_with_and_or(self):
+ # Under loose null strictness an ordering comparison is NULL for a NULL
+ # operand. A sequential CASE WHEN would skip that NULL link and answer
from
+ # the later ones, so chains and every `and` / `or` fold with `&` / `|`
+ # there: each body returns what its `&` / `|` spelling does.
+ B, L = BooleanType(), LongType()
+ chain = lambda x, y, z: x < y < z # noqa: E731
+ chain_spelled = lambda x, y, z: (x < y) and (y < z) # noqa: E731
+ negated = lambda x, y, z: not (x < y < z) # noqa: E731
+ negated_spelled = lambda x, y, z: not ((x < y) and (y < z)) # noqa:
E731
+ as_test = lambda x, y, z: 1 if (x < y < z) else 0 # noqa: E731
+ as_test_spelled = lambda x, y, z: 1 if ((x < y) and (y < z)) else 0 #
noqa: E731
+ chain_and = lambda x, y, z: (0 < x < 10) and (y > 0) # noqa: E731
+ chain_or = lambda x, y, z: (0 < x < 10) or (y < 0) # noqa: E731
+ compared = lambda x, y, z: ((x > 0) and (y > 0)) == True # noqa:
E731,E712
+ rows = [(None, 1, 2), (None, 5, 1), (1, None, 3), (1, 2, 3), (3, 2, 1)]
+ cases = [
+ (chain, chain_spelled, B, [None, False, None, True, False]),
+ (negated, negated_spelled, B, [True, True, True, False, True]),
+ (as_test, as_test_spelled, L, [0, 0, 0, 1, 0]),
+ (chain_and, None, B, [None, None, None, True, True]),
+ (chain_or, None, B, [None, None, True, True, True]),
+ (compared, None, B, [False, False, False, True, True]),
+ ]
+ loose = {"spark.sql.experimental.optimizer.transpileNullStrictness":
"loose"}
+ # `len()` and `%` still raise under loose, and the optimizer can drop
or
+ # hoist an `&` / `|` operand, so a chain-holding body with either falls
+ # back; absorption would reduce `absorbed` to `x > 0`.
+ absorbed = lambda s, x: (0 < len(s) < 10 and x > 0) or (x > 0) #
noqa: E731
+ modulo = lambda x, y: y != 0 and 0 < x % y < 3 # noqa: E731
+ with self.sql_conf({**_TRANSPILE_ON, **loose}):
+ for func in (absorbed, modulo):
+ u, reasons = self._udf_and_warnings(func, B)
+ self.assertEqual([], u.transpiled)
+ self.assertIn("transpileNullStrictness=loose", reasons)
+
+ # Without a chain the body keeps the `&` fold it had before chains.
+ def flat(s):
+ return s is not None and len(s) > 3
+
+ self.assertTrue(self._transpiled_udf(flat, B).transpiled)
+ for factory_mode in ("FALLBACK", "NO_CODEGEN"):
+ conf = {**loose, "spark.sql.codegen.factoryMode": factory_mode}
+ for i, (func, spelled, return_type, expected) in enumerate(cases):
+ with self.subTest(factory_mode=factory_mode, case=i),
self.sql_conf(conf):
+ schema = "a long, b long, c long"
+ self.assertEqual(self._vals(func, return_type, schema,
rows), expected)
+ if spelled is not None:
+ self.assertEqual(self._vals(spelled, return_type,
schema, rows), expected)
+
+ def test_loose_atomic_folds_with_throwing_operands_fall_back(self):
+ def length(a: int, b: int, s: str):
+ return (a is not None and 0 < len(s) < 10) or (b is not None and 0
< len(s) < 10)
+
+ def modulo(a: int, b: int, n: int, d: int):
+ return (a is not None and 0 < n % d < 10) or (b is not None and 0
< n % d < 10)
+
+ def length_absorption(s: str, x: int):
+ return (0 < len(s) < 10 and x > 0) or x > 0
+
+ def length_skip(s: str):
+ return s is not None and 0 < len(s) < 10
+
+ def modulo_absorption(n: int, d: int, z: int):
+ return (0 < n % d < 3 and z > 0) or z > 0
+
+ def modulo_skip(n: int, d: int):
+ return d != 0 and 0 < n % d < 3
+
+ def addition_skip(a: int, b: int):
+ return (a is not None and 0 < b + 1 < 10) or (a is not None and 0
< b + 1 < 10)
+
+ cases = [
Review Comment:
**Nit (P3):** These cases exercise calls (`len()`) and binary arithmetic
(`%`, `+`), but no loose-mode test holds a unary `+` / `-`, so deleting the
unary disjunct of `_holds_raising_lowering` leaves the suite green. Without
that disjunct, `y > 0 and 0 < -x < 10` over bigint columns would fold with `&`
under `loose`, with `-x` read by both chain links. Subexpression elimination,
whose skip-for-shortcut setting defaults to false, could then evaluate `-x`
before `y > 0` short-circuits. A projection over x = -2**63 and y = -1 would
raise ARITHMETIC_OVERFLOW where Python returns False, the same skipped-overflow
mechanism that `addition_skip` pins for `b + 1`.
**Verification:**
- **Regression:** Under loose null strictness, a chain-holding body that
reads a negated operand in a position Python skips falls back to interpreted
Python and returns Python's answer, False, for x = -2**63 and y = -1, in a
projection and as a filter. Under strict the same body stays lowered with the
same answers.
--
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]