spark-test commented on code in PR #59216:
URL: https://github.com/apache/spark/pull/59216#discussion_r4604184880
##########
python/pyspark/sql/transpile.py:
##########
@@ -187,6 +299,52 @@ def _transpile_from_ast(
pass
+def _expansion_compounds(body: ast.AST, atomic: bool) -> bool:
+ """Return True when some subtree of ``body`` weighs more than
+ ``_COMPOUND_RATIO`` times its AST node count.
+
+ References that multiply per nesting level make a subtree's weight outgrow
+ its node count geometrically, whereas a flat run of terms keeps the ratio
of
+ one term however many there are, so its size stays proportional to the
+ source; such a flat body is not bounded by ``_MAX_MATERIALIZED_WEIGHT``. A
+ single term that nests two multi-read lowerings, such as
+ ``x % (y % z) == 0``, already passes the ratio and counts as compounding.
+ """
+ return any(
+ _materialized_weight(node, atomic) > _COMPOUND_RATIO * sum(1 for _ in
ast.walk(node))
Review Comment:
**Non-blocking (P2):** This recomputes `_materialized_weight(node)` and an
`ast.walk` count from scratch for every node of the body, so the check does
work equal to the sum of all subtree sizes, quadratic in the body's nesting
depth. `_transpile_func` runs it before lowering for every UDF defined with the
transpiler and ANSI on, flat bodies included, which it then exempts. By the
review's estimate that is about a tenth of a second for the 129-level ternary
ladder in `test_udf_transpile_many_flat_comparisons` and about half a second
for a 400-term flat sum, both bodies the base branch lowered without it. An
800-term sum, whose lowering passes Python's recursion limit on both branches,
still falls back as before but now spends about two seconds here first. Query
execution and results are unaffected.
Each node's weight depends only on its children's weights, so one post-order
pass that records the weight and node count of every node gives the same
decision and root weight in linear time.
**Verification:**
- **Regression:** Counting the work done per UDF definition shows each AST
node of the body weighed and counted once, and the compounding decision and
root weight stay the same for the lowering-caps and flat-comparison test
bodies, including an 800-term flat sum and a 129-level ternary ladder.
##########
python/pyspark/sql/tests/test_udf_transpile_unit.py:
##########
@@ -549,39 +550,516 @@ def gte_zero(x):
self.assertEqual(row_lte[0], lte_expected)
self.assertEqual(row_gte[0], gte_expected)
- def test_udf_transpile_chained_comparison_falls_back(self):
- # ``a < b < c`` is a chained comparison: Python evaluates it as
- # ``(a < b) and (b < c)``. The transpiler refuses chained Compare
- # nodes (``len(ops) != 1``) and must fall back to interpreted Python.
- import warnings as _warnings
+ def test_udf_transpile_chain_short_circuits(self):
+ # THE test for the chained lowering. Python's chain short-circuits:
when
+ # ``a < b`` is false, ``b < c`` is never evaluated, so a NULL ``c``
cannot
+ # raise. The chain's CASE WHEN only reaches a later link once every
earlier
+ # one is true, so the fold matches. Nullable *columns* are required: a
+ # literal `None` has no column category, so `1 < 0 < None` just falls
back.
+ #
+ # Both of `CaseWhen`'s laziness implementations are exercised:
`doGenCode`
+ # under the default FALLBACK factory mode, and `eval` under NO_CODEGEN.
+ # `spark.sql.codegen.wholeStage=false` is NOT enough for the latter --
it
+ # disables whole-stage fusion, but expressions are still compiled
through
+ # the codegen factory, so `doGenCode` runs either way. Survival
through the
+ # OPTIMIZER is separate; see
test_udf_transpile_chain_survives_optimizer.
+ B = BooleanType()
+ chain3 = lambda a, b, c: a < b < c # noqa: E731
+ chain4 = lambda a, b, c, d: a < b < c < d # noqa: E731
+ chain_or = lambda a, b: (0 < a < 10) or (b > 0) # noqa: E731
+ abc, abcd = "a long, b long, c long", "a long, b long, c long, d long"
+ for factory_mode in ("FALLBACK", "NO_CODEGEN"):
+ conf = {"spark.sql.codegen.factoryMode": factory_mode}
+ with self.subTest(factory_mode=factory_mode), self.sql_conf(conf):
+ # An earlier link is false, so the NULL in a later one is never
+ # evaluated -- from the first link, and from an interior one.
+ self.assertEqual(self._vals(chain3, B, abc, [(1, 0, None)]),
[False])
+ self.assertEqual(self._vals(chain4, B, abcd, [(1, 2, 1,
None)]), [False])
+ # ... but when every earlier link IS true the last one is
reached
+ # and its NULL guard fires, exactly as Python raises TypeError.
+ with self.assertRaisesRegex(Exception, "cannot compare NULL"):
+ self._vals(chain3, B, abc, [(0, 1, None)])
+ with self.assertRaisesRegex(Exception, "cannot compare NULL"):
+ self._vals(chain4, B, abcd, [(1, 2, 3, None)])
+ # The CASE WHEN fold of `or`: a true earlier operand decides
the
+ # result and the later operand's NULL guard is never evaluated.
+ self.assertEqual(self._vals(chain_or, B, "a long, b long",
[(5, None)]), [True])
+
+ def test_udf_transpile_chain_survives_optimizer(self):
+ # A chain folds to a sequential CASE WHEN, and so do the `and` / `or`
of a
+ # body holding a chain or a comparison over a non-basic operand. That
fold
+ # is atomic to `splitConjunctivePredicates` and
`BooleanSimplification`;
+ # an `&` / `|` fold lets BooleanSimplification move a later operand's
NULL
+ # guard ahead of the operands that gate it, or drop one, as it still
does
+ # for the `and` / `or` bodies that keep `&` / `|` (see the module
+ # docstring). Each body must return Python's answer, or raise like
+ # Python, fully lowered, under generated and interpreted evaluation.
+ abc = "a long, b long, c long"
+ # Common factor: `(p && g) || (q && g) => g && (p || q)` hoists the
shared
+ # guarded operand to the front, where its NULL raises.
+ factor_chains = lambda a, b, c, d: (a < b < c) or (d < b < c) # noqa:
E731
+
+ def factor_and(a, b):
+ return (0 <= a <= 10 and b > 0) or (20 <= a <= 30 and b > 0)
+
+ def factor_nested(a, b, c):
+ return ((b > 0 and a > 0) or (c > 0 and a > 0)) == True # noqa:
E712
+
+ # Absorption: `(p && g) || g => g` drops the guard in `p`, returning
True
+ # where Python raises.
+ absorb_chain = lambda a, b, c: (a < b < c) or (b < c) # noqa: E731
+ absorb_and = lambda a, b: (0 <= a <= 10 and b > 0) or (b > 0) # noqa:
E731
+ # (body, schema, row, Python's answer or None where Python raises
TypeError)
+ # `SimplifyConditionals` replaces a CASE WHEN whose values all equal
its
+ # ELSE: a last operand that is or folds to the fold's stop value must
not
+ # delete the earlier operands' guards.
+ and_false = lambda a: (0 < a < 10) and False # noqa: E731
+ or_true = lambda a, b: (0 < a < b) or True # noqa: E731
+ constant_link = lambda a: a < 5 < 3 # noqa: E731
+ nested_or_true = lambda a: ((a > 0) or True) == True # noqa: E731,E712
+ cases = [
+ (and_false, "a long", (None,), None),
+ (or_true, "a long, b long", (None, 5), None),
+ (constant_link, "a long", (None,), None),
+ (nested_or_true, "a long", (None,), None),
+ (factor_chains, abc + ", d long", (5, 1, None, 7), False),
+ (factor_and, "a long, b long", (15, None), False),
+ (factor_nested, abc, (None, -1, -1), False),
+ (absorb_chain, abc, (None, 0, 1), None),
+ (absorb_and, "a long, b long", (None, 5), None),
+ ]
+ for factory_mode in ("FALLBACK", "NO_CODEGEN"):
+ conf = {**_TRANSPILE_ON, "spark.sql.codegen.factoryMode":
factory_mode}
+ for i, (func, schema, row, expected) in enumerate(cases):
+ with self.subTest(factory_mode=factory_mode, case=i),
self.sql_conf(conf):
+ df = self.spark.createDataFrame([row], schema)
+ projected = df.select(self._transpiled_udf(func,
BooleanType())(*df.columns))
+ self.assertEqual(0, self._eval_python_count(projected),
"must stay lowered")
+ if expected is None:
+ with self.assertRaisesRegex(Exception, "cannot compare
NULL"):
+ projected.collect()
+ else:
+ self.assertEqual([expected], [r[0] for r in
projected.collect()])
- from pyspark.sql.types import StructField, StructType
+ # A chain as a filter over an Aggregate: the group (b=1, c=NULL, sa=6)
has
+ # `sa < b` false, so Python never touches `b < c`. Since SPARK-60633
an `&`
+ # fold passes this too; it pins the chain over an aggregate.
+ from pyspark.sql.functions import sum as sum_
- def chained(x):
- return 0 < x < 10
+ with self.sql_conf(_TRANSPILE_ON):
+ chain_over_agg = lambda sa, b, c: sa < b < c # noqa: E731
+ udf = self._transpiled_udf(chain_over_agg, BooleanType())
+ agg = (
+ self.spark.createDataFrame([(1, 1, None), (5, 1, None), (2, 2,
3)], abc)
+ .groupBy("b", "c")
+ .agg(sum_("a").alias("sa"))
+ )
+ filtered = agg.filter(udf("sa", "b", "c"))
+ self.assertEqual([], filtered.select("b", "c").collect())
+ self.assertEqual(0, self._eval_python_count(filtered), "chain must
stay lowered")
+
+ # An if/ternary whose branches lower to one expression would
collapse
+ # the same way and drop its test, so it falls back.
+ same_branches = lambda x, y: y if (0 < x < 10) else y # noqa: E731
+ u, reasons = self._udf_and_warnings(same_branches, LongType())
+ self.assertEqual([], u.transpiled)
+ self.assertIn("same expression", reasons)
+
+ def test_udf_transpile_and_or_fold_choice(self):
+ # Only a body that holds a chain or a comparison over a non-basic
operand
+ # takes the CASE WHEN fold for its `and` / `or`; every other body keeps
+ # `&` / `|`, and with it per-conjunct pushdown.
+ import ast as _ast
- schema = StructType([StructField("a", LongType(), nullable=False)])
- with self.sql_conf(
- {
- "spark.sql.experimental.optimizer.transpilePyUDFs": True,
- "spark.sql.ansi.enabled": True,
- }
+ from pyspark.sql.transpile import _needs_atomic_boolops
+
+ for src, atomic in [
+ ("a > 0 and c > 0", False),
+ ("(a == 1 or a == 2) and not (c < 0)", False),
+ ("(0 < a < 10) and c > 0", True),
+ ("((a > 0 and c > 0) or c > 1) == True", True),
+ ("(a if c > 0 else 1) == 1 and c > 0", True),
+ ]:
+ with self.subTest(src=src):
+ self.assertEqual(atomic, _needs_atomic_boolops(_ast.parse(src,
mode="eval")))
+
+ df = self.spark.createDataFrame([(1, 2)], "a long, c long")
+ with self.sql_conf(_TRANSPILE_ON):
+ plain = lambda a, c: a > 0 and c > 0 # noqa: E731
+ chained = lambda a, c: (0 < a < 10) and c > 0 # noqa: E731
+ for func, splittable in [(plain, True), (chained, False)]:
+ udf = self._transpiled_udf(func, BooleanType())
+ plan = self._optimized_plan(df.select(udf("a", "c")))
+ self.assertEqual(splittable, " AND " in plan, plan)
+
+ def test_udf_transpile_boolop_short_circuits(self):
+ # The `and` / `or` counterpart of the chain short-circuit: a NULL
guard in
+ # the second operand must not fire when the first already decided the
+ # result.
+ def both_positive(a, c):
+ return a > 0 and c > 0
+
+ def either_positive(a, c):
+ return a > 0 or c > 0
+
+ # Under both factory modes, so `And` / `Or`'s `doGenCode` and `eval`
+ # laziness are both covered (see
test_udf_transpile_chain_short_circuits).
+ B, schema = BooleanType(), "a long, c long"
+ for factory_mode in ("FALLBACK", "NO_CODEGEN"):
+ conf = {"spark.sql.codegen.factoryMode": factory_mode}
+ with self.subTest(factory_mode=factory_mode), self.sql_conf(conf):
+ self.assertEqual(self._vals(both_positive, B, schema, [(-5,
None)]), [False])
+ self.assertEqual(self._vals(either_positive, B, schema, [(5,
None)]), [True])
+
+ # The same across a join, with the NULL operand entirely on the right
+ # side: the regression test for SPARK-58627. Before `RaiseError`
overrode
+ # `Expression.throwable`, `splitConjunctivePredicates` decomposed the
+ # `And` and `PushPredicateThroughJoin` pushed the guard to one side of
the
+ # join, where it fired on rows Python short-circuits past.
+ # BooleanSimplification and subexpression elimination, listed in the
+ # module docstring, remain open. No AQE and no broadcast, so the
+ # pushed-down guard either exists or does not, rather than racing AQE
+ # eliminating the empty join.
+ deterministic = {
+ **_TRANSPILE_ON,
+ "spark.sql.adaptive.enabled": False,
+ "spark.sql.autoBroadcastJoinThreshold": -1,
+ }
+ with self.sql_conf(deterministic):
+ and_udf = self._transpiled_udf(both_positive, B)
+ left = self.spark.createDataFrame([(1, -5)], "k long, a long")
+ right = self.spark.createDataFrame([(1, None)], "k long, c long")
+ joined = left.join(right, "k")
+ # Results alone do not prove the lowering ran -- interpreted Python
+ # returns the same -- so also assert zero EvalPython nodes.
+ joined_select = joined.select(and_udf("a", "c"))
+ self.assertEqual([False], [r[0] for r in joined_select.collect()])
+ self.assertEqual(0, self._eval_python_count(joined_select),
"joined select lowered")
+ filtered = joined.filter(and_udf("a", "c"))
+ self.assertEqual([], filtered.select("k").collect())
+ self.assertEqual(0, self._eval_python_count(filtered), "joined
filter lowered")
+
+ def test_udf_transpile_chain_operator_mix_and_eq_nulls(self):
+ # Mixed operators in one chain, and `x == y == z` over every NULL
pattern.
+ # Equality never raises in Python (`None == None` is True, `None == 0`
is
+ # False), so every pattern has a defined answer to match exactly.
+ B = BooleanType()
+ chained_eq = lambda a, b, c: a == b == c # noqa: E731
+
+ # (a, b, c, expected) -- every NULL pattern plus value cases.
+ eq_cases = [
+ (None, None, None, True),
+ (None, None, 1, False),
+ (None, 1, None, False),
+ (None, 1, 2, False),
+ (1, None, None, False),
+ (1, None, 2, False),
+ (1, 2, None, False),
+ (1, 1, None, False),
+ (1, 1, 1, True),
+ (1, 1, 2, False),
+ (1, 2, 3, False),
+ ]
+ self.assertEqual(
+ self._vals(chained_eq, B, "a long, b long, c long", [c[:3] for c
in eq_cases]),
+ [c[3] for c in eq_cases],
+ "a == b == c over the NULL patterns",
+ )
+
+ # Operator mixes, on non-NULL rows so the ordering guards stay quiet.
+ lt_eq = lambda a, b, c: a < b == c # noqa: E731
+ eq_lt = lambda a, b, c: a == b < c # noqa: E731
+ gt_gte = lambda a, b, c: a > b >= c # noqa: E731
+ lte_lte = lambda a, b, c: a <= b <= c # noqa: E731
+ four_ops = lambda a, b, c, d, e: a < b < c < d < e # noqa: E731
+ for label, func, rows, expected in [
+ ("a < b == c", lt_eq, [(1, 2, 2), (1, 2, 3), (2, 1, 1)], [True,
False, False]),
+ ("a == b < c", eq_lt, [(1, 1, 2), (1, 1, 0), (1, 2, 3)], [True,
False, False]),
+ ("a > b >= c", gt_gte, [(3, 2, 2), (3, 2, 5), (1, 2, 2)], [True,
False, False]),
+ ("a <= b <= c", lte_lte, [(1, 1, 2), (1, 2, 2), (2, 1, 3)], [True,
True, False]),
+ ]:
+ with self.subTest(func=label):
+ self.assertEqual(
+ self._vals(func, B, "a long, b long, c long", rows),
expected, label
+ )
+ self.assertEqual(
+ self._vals(
+ four_ops,
+ B,
+ "a long, b long, c long, d long, e long",
+ [(1, 2, 3, 4, 5), (1, 2, 3, 5, 4)],
+ ),
+ [True, False],
+ "a chain of four operators is well under the cap and must
transpile",
+ )
+
+ def test_udf_transpile_comparison_fallbacks(self):
+ # Comparison forms the transpiler must REFUSE. Each case asserts both
that
+ # nothing transpiled and that a query using the UDF still returns
Python's
+ # answer. The second half matters because an option that survives is
+ # type-checked by CheckAnalysis as a child of TranspiledPythonUDF: a
+ # half-refused form would fail the whole query rather than fall back,
so
+ # "did not transpile" alone is not enough to prove the fallback works.
+ #
+ # `in` / `not in` are refused wholesale, so those cases all take the
same
+ # branch; they are kept because the reasons differ. `in` on a str is
+ # substring containment rather than equality, a container of runtime
+ # values would need runtime NULL analysis, and `in` can appear as a
link
+ # in a chain (`a < b in (1, 2)` is one Compare), which the refusal also
+ # covers. Membership needs its own NULL analysis and is deferred to its
+ # own ticket (SPARK-56925 is the unrelated bare-`if` truthiness work).
+ str_in = lambda x: x in "abc" # noqa: E731
+ runtime_in = lambda x, y: x in (y, 2) # noqa: E731
+ chained_in = lambda a, b: a < b in (1, 2) # noqa: E731
+ # Short-circuits for non-positive inputs.
+ cross_chain = lambda x: 0 < x < "z" # noqa: E731
+ # Boolean bodies declared LongType return NULL through interpreted
Python.
+ chain_long_rt = lambda x: 0 < x < 10 # noqa: E731
+ in_long_rt = lambda x: x in (1, 2) # noqa: E731
+
+ B, L = BooleanType(), LongType()
+ # (func, return type, schema, rows, what interpreted Python produces)
+ cases = [
+ (str_in, B, "a string", [("b",), ("z",)], [True, False]),
+ (runtime_in, B, "a long, b long", [(1, 1), (3, 5)], [True, False]),
+ (chained_in, B, "a long, b long", [(0, 1), (1, 0)], [True, False]),
+ (cross_chain, B, "a long", [(0,)], [False]),
+ (chain_long_rt, L, "a long", [(0,)], [None]),
+ (in_long_rt, L, "a long", [(0,)], [None]),
+ ]
+ with self.sql_conf(_TRANSPILE_ON):
+ for i, (func, return_type, schema, rows, expected) in
enumerate(cases):
+ with self.subTest(case=i):
+ pudf, _ = self._fallback_reason(func, return_type)
+ df = self.spark.createDataFrame(rows, schema)
+ self.assertEqual(
+ [r[0] for r in
df.select(pudf(*df.columns)).collect()], expected
+ )
+
+ def test_udf_transpile_boolean_body_requires_boolean_return_type(self):
+ # A comparison body is boolean whatever its operands look like, so it
must
+ # not satisfy a numeric declared return type. `_is_definitely_boolean`
says
+ # False for a comparison over a ternary / comparison / boolean op (it
also
+ # demands basic-type operands), and those used to fall through
`_category`'s
+ # numeric catch-all: `_transpile_from_ast` then accepted `LongType`
and the
+ # option returned `cast(<boolean> as bigint)` -- 1 or 0 -- where the
+ # interpreted path returns NULL. `_category` now classifies every
+ # `ast.Compare` as "bool" directly.
+ def ternary_compare(c, x, y):
+ return (x if c > 0 else y) == 1
+
+ def eq_true(a, b):
+ return (a < b) == True # noqa: E712
+
+ def compare_of_compares(a, b, c):
+ return (a < b) <= (b < c)
+
+ cases = [
+ (ternary_compare, "c long, x long, y long", (1, 1, 9)),
+ (eq_true, "a long, b long", (1, 2)),
+ (compare_of_compares, "a long, b long, c long", (1, 2, 3)),
+ ]
+ for func, schema, row in cases:
+ with self.subTest(func=func.__name__),
self.sql_conf(_TRANSPILE_ON):
+ # Declared LongType it falls back, and the interpreted path
+ # returns NULL for a bool.
+ pudf, _ = self._fallback_reason(func, LongType())
+ df = self.spark.createDataFrame([row], schema)
+ self.assertEqual([None], [r[0] for r in
df.select(pudf(*df.columns)).collect()])
+ # Declared BooleanType it runs natively and keeps its NULL
guard.
+ self.assertEqual(self._vals(func, BooleanType(), schema,
[row]), [func(*row)])
+ with self.assertRaisesRegex(Exception, "cannot compare NULL"):
+ self._vals(func, BooleanType(), schema, [(None, *row[1:])])
+
+ def test_udf_transpile_lowering_caps(self):
+ # The bounds on comparison lowering: the per-chain operator cap, and
the
+ # materialized size of everything one application of the UDF builds.
+ import ast as _ast
+
+ from pyspark.sql.transpile import (
+ _MAX_COMPARISON_OPS,
+ _MAX_MATERIALIZED_WEIGHT,
+ CatalystTranspiler,
+ _materialized_weight,
+ )
+
+ weight_msg = f"more than {_MAX_MATERIALIZED_WEIGHT}"
+
+ def weight(src):
+ return _materialized_weight(_ast.parse(src, mode="eval").body)
+
+ def build(src, params="x"):
+ func = self._function_from_source(f"def f({params}):\n return
{src}\n")
+ return self._udf_and_warnings(func, BooleanType())
+
+ def chain(n):
+ # n operators over n + 1 operands: x < 0 < 1 < ... < n - 1
+ return " < ".join(["x"] + [str(i) for i in range(n)])
+
+ def right_nested(depth, leaf="(x < 0)", op="<"):
+ # ONE operand of a single comparison per level: 2d + 1 links but
~2^d
+ # materialized nodes, since a link reads each operand Column twice
+ # (four times for `==`) and the JVM converter does not memoize.
+ src = leaf
+ for _ in range(depth):
+ src = f"{leaf} {op} ({src})"
+ return src
+
+ def chain_nested(depth):
+ src = "(x < 0)"
+ for _ in range(depth):
+ src = f"((x < 0) < {src} < (x < 0))"
+ return src
+
+ lowers = [
+ chain(_MAX_COMPARISON_OPS),
+ right_nested(2),
+ chain_nested(2),
+ # One level over a ternary.
+ "(x < 0) < ((x < 1) if x > 0 else (x < 2))",
+ # `is None` reads only its subject, so an identity nest stays
linear.
+ "(" * 20 + "x < 0" + ") is None" * 20,
+ ]
+ # The nest routed through a ternary: its Column is read as often as any
+ # other operand, in each of its three positions.
+ ternary_nests = []
+ for shape in (
+ "(x < 0) {op} (True if ({inner}) else False)",
+ "(x < 0) {op} (({inner}) if x > 0 else (x < 0))",
+ "(x < 0) {op} ((x < 0) if x > 0 else ({inner}))",
):
- with _warnings.catch_warnings(record=True) as caught:
- _warnings.simplefilter("always")
- pudf = UserDefinedFunction(chained, BooleanType())
- self.assertEqual([], pudf.transpiled, "chained comparison must NOT
transpile")
- fallback = [
- w
- for w in caught
- if "Unable to transpile" in str(w.message) or "Errors
encountered" in str(w.message)
- ]
- self.assertTrue(fallback, "expected a fallback warning")
- for value, expected in [(5, True), (0, False), (10, False), (-3,
False)]:
- with self.subTest(value=value):
- df = self.spark.createDataFrame([Row(a=value)],
schema=schema)
- [row] = df.select(pudf("a")).collect()
- self.assertEqual(row[0], expected)
+ for op in ("<", "=="):
+ src = "(x < 0)"
+ for _ in range(20):
+ src = shape.format(op=op, inner=src)
+ ternary_nests.append(src)
+ # Modulo reads its divisor five times and `len` its argument twice.
+ modulo = "x"
+ for _ in range(10):
+ modulo = f"x % ({modulo})"
+ too_heavy = [
Review Comment:
**Nit (P3):** None of these refusals depends on the fold's double-read
charges in `_materialized_weight` (`2 * sum(links) - links[-1]` for chain links
and `1 + 2 * sum(weights) - weights[-1]` for `and` / `or` in bodies that take
the fold): recomputing the estimate with either arm removed leaves every case
here refused. A chain whose first operand is the previous level, `(<previous>)
< (x < i) < (x < i + 1)` nested 8 deep, is refused today at about 2.7 million
estimated nodes but would weigh about 20,000 and lower without the chain
doubling. A 12-level `((<previous>) and (0 < x < 10))` nest is refused at about
250,000 and stops counting as compounding without the `and` / `or` doubling.
Adding both as refusal cases here would make a regression in either charge
fail the suite, rather than letting such nests expand their full trees on every
application of the UDF, outside the transpiler's fallback.
This extends an [existing
discussion](https://github.com/apache/spark/pull/59216#discussion_r4602666075).
**Verification:**
- **Regression:** A first-operand chain nest and an `and` nest over a chain
are refused with the materialized-weight message, and each one lowers instead
when the doubling charge it depends on is removed.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -730,8 +730,11 @@ object SQLConf {
.doc("Controls how the Python UDF transpiler handles null/None semantics
for ordering " +
"comparisons (``<``, ``<=``, ``>``, ``>=``). Under ``strict`` (the
default) a NULL " +
"operand causes the expression to raise an error, matching Python's
TypeError. Under " +
- "``loose`` a NULL operand silently propagates as NULL instead of
raising, which allows " +
- "more UDFs to be transpiled at the cost of minor semantic divergence on
NULL inputs.")
+ "``loose`` a NULL operand silently propagates as NULL instead of
raising, at the cost of " +
+ "minor semantic divergence on NULL inputs. ``loose`` also changes how
chained " +
+ "comparisons and ``and`` / ``or`` are lowered: a body that holds a
chained or nested " +
+ "comparison together with a call or arithmetic falls back to interpreted
Python, so " +
+ "``loose`` does not always transpile more UDFs than ``strict``.")
Review Comment:
**Nit (P3):** Under `loose` the only fallback is in `_fold_boolean`, and it
fires only when two or more operands fold atomically: a chained comparison, or
an `and` / `or` in a body holding a chained or nested comparison. A body whose
comparisons are all single links and that has no `and` / `or` never reaches it,
so `(a < b) == (len(s) > 0)` transpiles under `loose` although this text says
it falls back. `_holds_raising_lowering` also counts a unary `+` / `-`, so `-90
<= lat <= 90` falls back for its negative literal, which "a call or arithmetic"
does not suggest. Wording that matches the code:
```suggestion
"comparisons and ``and`` / ``or`` are lowered: a chained comparison,
or an ``and`` / " +
"``or`` in a body holding a chained or nested comparison, falls back
to interpreted " +
"Python when the body also holds a call, arithmetic or a unary ``+`` /
``-`` (including " +
"a negative literal), so ``loose`` does not always transpile more UDFs
than ``strict``.")
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/59216#discussion_r4602666141).
**Verification:**
- **Inspection:** The `transpileNullStrictness` description states the same
loose fallback `_fold_boolean` applies: chained comparisons, and `and` / `or`
in bodies holding a chained or nested comparison, when the body also holds a
call, arithmetic or a unary `+` / `-`.
--
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]