holdenk commented on code in PR #59731:
URL: https://github.com/apache/spark/pull/59731#discussion_r4580917887
##########
python/pyspark/sql/tests/test_udf_transpile_parity.py:
##########
@@ -102,6 +104,24 @@ def setUpClass(cls):
_enable_transpilation(cls)
[email protected](is_remote_only(), _NON_CONNECT_ONLY)
+class TranspiledJavaUDFParityTests(BaseUDFTestsMixin, ReusedSQLTestCase):
Review Comment:
Fixed in 8d3c694b486: the class now names only `java`, and the docstring
says what the run covers. All 90 inherited tests pass with no skips needed.
Checked that it has teeth: mapping `Add` to the subtract helper fails 5
inherited tests.
---
<sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of
@holdenk.</sub>
<!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk
-->
##########
python/pyspark/sql/tests/test_udf_transpile_java_unit.py:
##########
@@ -0,0 +1,1039 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""
+Unit tests for the ``java`` UDF transpilation target.
+
+Two kinds of test live here. The lowering tests call the transpiler directly
and assert on
+the Java source it produces, which is cheap and says exactly what changed when
one breaks.
+The end-to-end tests run queries and compare against interpreted Python, which
is the only
+thing that can catch a body that lowers but computes the wrong answer.
+
+The companion suites for the Catalyst target are
``test_udf_transpile_unit.py`` and
+``test_udf_transpile_hypothesis.py``; ``test_udf_transpile_parity.py`` re-runs
the shared
+UDF mixins with this target enabled.
+"""
+
+import ast
+import textwrap
+import unittest
+
+from pyspark.errors import UnsupportedOperationException
+from pyspark.sql.functions import col, lit, rand
+from pyspark.sql.types import (
+ BinaryType,
+ BooleanType,
+ DoubleType,
+ LongType,
+ StringType,
+)
+from pyspark.sql.udf import UserDefinedFunction
+from pyspark.testing.sqlutils import ReusedSQLTestCase
+from pyspark.util import is_remote_only
+
+# Transpilation needs both flags; ANSI because the lowerings target ANSI
semantics. The
+# `java` target additionally has to be named in the transpiler list, which is
what makes it
+# opt-in -- the default stays `catalyst`.
+_JAVA_ONLY = {
+ "spark.sql.experimental.optimizer.transpilePyUDFs": True,
+ "spark.sql.ansi.enabled": True,
+ "spark.sql.experimental.optimizer.pyTranspilers": "java",
+}
+
+_CATALYST_THEN_JAVA = dict(
+ _JAVA_ONLY,
+ **{
+ "spark.sql.experimental.optimizer.pyTranspilers": "catalyst,java",
+ },
+)
+
+_CATALYST_ONLY = dict(
+ _JAVA_ONLY,
+ **{
+ "spark.sql.experimental.optimizer.pyTranspilers": "catalyst",
+ },
+)
+
+# A true interpreted baseline. Naming no transpiler is not enough to get one:
the Catalyst
+# target lowers more than it might seem -- `%`, and a body that just returns a
parameter --
+# so a test that wants interpreted Python has to turn transpilation off rather
than assume
+# some particular body defeats it.
+_TRANSPILE_OFF = {
+ "spark.sql.experimental.optimizer.transpilePyUDFs": False,
+ "spark.sql.ansi.enabled": True,
+}
+
+
+def _lower(source: str, return_type, categories: dict) -> str:
+ """Lower ``source``'s function to Java statements, without a session or a
JVM.
+
+ Drives the transpiler below its ``_build_column`` step, which is the only
part that
+ needs a live JVM, so the generated source can be asserted on directly.
+ """
+ from pyspark.sql.transpile import _get_function_from_ast
+ from pyspark.sql.transpile_java import JavaTranspiler, _return_category
+
+ tree = ast.parse(textwrap.dedent(source))
+ function_ast, error = _get_function_from_ast(tree, None)
+ assert function_ast is not None, error
+ transpiler = JavaTranspiler()
+ transpiler._bind([arg.arg for arg in function_ast.args.args], categories)
+ return "\n".join(transpiler._lower_body(function_ast.body,
_return_category(return_type)))
+
+
+class JavaTranspileLoweringTests(unittest.TestCase):
+ """Tests over the generated source. No session, no JVM."""
+
+ def test_arithmetic_goes_through_the_helpers(self):
+ # Never a bare Java operator: `+` would wrap silently where ANSI must
raise, and
+ # `%` and `/` have the wrong sign and the wrong zero behaviour for
Python.
+ lowered = _lower("def f(x):\n return x + 1", LongType(), {0:
"integral"})
+ self.assertIn("TranspiledJavaUDFHelpers.addLong(_udf_arg_0", lowered)
+ self.assertNotIn("_udf_arg_0 +", lowered)
+
+ def test_floor_divide_and_mod_use_the_floor_helpers(self):
+ floor_div = _lower("def f(x):\n return x // 3", LongType(), {0:
"integral"})
+ self.assertIn("floorDivideLong", floor_div)
+ mod = _lower("def f(x):\n return x % 3", LongType(), {0:
"integral"})
+ self.assertIn("modLong", mod)
+
+ def test_true_divide_of_ints_produces_a_float(self):
+ # Python's `/` is always float division, so an int body under a
declared double is
+ # the correct shape and an int return type is refused.
+ lowered = _lower("def f(x):\n return x / 2", DoubleType(), {0:
"integral"})
+ self.assertIn("divideLong", lowered)
+ with self.assertRaises(UnsupportedOperationException):
+ _lower("def f(x):\n return x / 2", LongType(), {0: "integral"})
+
+ def test_multi_statement_body_with_local_and_early_return(self):
+ lowered = _lower(
+ """
+ def f(x):
+ doubled = x * 2
+ if doubled > 10:
+ return 10
+ return doubled + 1
+ """,
+ LongType(),
+ {0: "integral"},
+ )
+ self.assertIn("_doubled =", lowered)
+ self.assertIn("Long _udf_local_0", lowered)
+ self.assertIn("return Long.valueOf(10L);", lowered)
+
+ def test_locals_needing_the_same_sanitised_name_stay_distinct(self):
+ # Sanitising to Java's character set is not injective on its own: a
non-ASCII name
+ # and an underscore name can reduce to the same text, and two locals
sharing one
+ # Java variable would be a silently wrong answer rather than a
failure. The numbering
+ # is what prevents it.
+ # The identifier is spelled with an escape so this file stays ASCII,
per the
+ # project's convention; what `ast.parse` sees is still a non-ASCII
name.
+ accented = "caf\u00e9"
+ lowered = _lower(
+ f"""
+ def f(x):
+ {accented} = x + 1
+ caf_ = x + 2
+ return {accented} + caf_
+ """,
+ LongType(),
+ {0: "integral"},
+ )
+ self.assertIn("_udf_local_0_caf_", lowered)
+ self.assertIn("_udf_local_1_caf_", lowered)
+
+ def test_no_unreachable_return_when_every_path_returns(self):
+ # Java rejects an unreachable statement, so the trailing `return null`
that stands
+ # for Python falling off the end must not be emitted when it cannot be
reached.
+ both = _lower(
+ """
+ def f(x):
+ if x > 0:
+ return 1
+ else:
+ return 2
+ """,
+ LongType(),
+ {0: "integral"},
+ )
+ # Two returns, one per branch, and crucially no third one after the
`if`.
+ self.assertEqual(2, both.count("return "), both)
+ self.assertNotIn("null", both)
+
+ # ... and must be emitted when it can, since `if` alone falls through.
+ falls_through = _lower(
+ """
+ def f(x):
+ if x > 0:
+ return 1
+ """,
+ LongType(),
+ {0: "integral"},
+ )
+ self.assertIn("return ((Long) null);", falls_through)
+
+ def test_int_promotes_to_float_when_mixed(self):
+ lowered = _lower(
+ "def f(a, b):\n return a + b", DoubleType(), {0: "integral", 1:
"fractional"}
+ )
+ self.assertIn("toDouble(_udf_arg_0)", lowered)
+ self.assertIn("addDouble", lowered)
+
+ def test_mixed_int_float_comparison_is_exact_not_widened(self):
+ # Arithmetic widens the int (Python does too), but comparison must
not: widening
+ # 9007199254740993 to a double rounds it to 9007199254740992.0 and
calls them equal
+ # where CPython says they are not. So the helper is direction-aware,
not toDouble.
+ eq_long_double = _lower(
+ "def f(a, b):\n return a == b", BooleanType(), {0: "integral",
1: "fractional"}
+ )
+ self.assertIn("equalsLongDouble(_udf_arg_0, _udf_arg_1)",
eq_long_double)
+ self.assertNotIn("toDouble", eq_long_double)
+ eq_double_long = _lower(
+ "def f(a, b):\n return a == b", BooleanType(), {0:
"fractional", 1: "integral"}
+ )
+ self.assertIn("equalsDoubleLong(_udf_arg_0, _udf_arg_1)",
eq_double_long)
+ self.assertNotIn("toDouble", eq_double_long)
+ neq = _lower(
+ "def f(a, b):\n return a != b", BooleanType(), {0: "integral",
1: "fractional"}
+ )
+ # `!=` is `not(equals)`, so the exact helper still runs and is then
negated.
+ self.assertIn("equalsLongDouble(_udf_arg_0, _udf_arg_1)", neq)
+ self.assertIn("Helpers.not(", neq)
+ lt = _lower(
+ "def f(a, b):\n return a < b", BooleanType(), {0: "integral",
1: "fractional"}
+ )
+ self.assertIn("lessThanLongDouble(_udf_arg_0, _udf_arg_1)", lt)
+ gt = _lower(
+ "def f(a, b):\n return a > b", BooleanType(), {0: "fractional",
1: "integral"}
+ )
+ self.assertIn("greaterThanDoubleLong(_udf_arg_0, _udf_arg_1)", gt)
+
+ def test_string_concat_and_repeat(self):
+ concat = _lower("def f(s):\n return s + 'x'", StringType(), {0:
"string"})
+ self.assertIn("TranspiledJavaUDFHelpers.concat", concat)
+ self.assertIn('UTF8String.fromString("x")', concat)
+ repeat = _lower(
+ "def f(s, n):\n return s * n", StringType(), {0: "string", 1:
"integral"}
+ )
+ self.assertIn("TranspiledJavaUDFHelpers.repeat", repeat)
+
+ def test_repeat_refuses_a_fractional_count(self):
+ # The divergence the Catalyst target documents: there a fractional
count from a
+ # column is truncated by the cast it inserts, where Python raises
TypeError. Here
+ # the count's category is known before any source is emitted, so it is
declined.
+ with self.assertRaises(UnsupportedOperationException):
+ _lower(
+ "def f(s, n):\n return s * n",
+ StringType(),
+ {0: "string", 1: "fractional"},
+ )
+
+ def test_non_ascii_string_literal_is_escaped(self):
+ lowered = _lower("def f(s):\n return s + '\u00e9'", StringType(),
{0: "string"})
+ self.assertIn("\\u00e9", lowered)
+ # The generated source stays ASCII so no compiler has to be asked how
it decodes.
+ self.assertTrue(lowered.isascii(), lowered)
+
+ def test_is_none_lowers_but_eq_none_declines(self):
+ guarded = _lower(
+ """
+ def f(x):
+ if x is not None:
+ return x + 1
+ """,
+ LongType(),
+ {0: "integral"},
+ )
+ self.assertIn("_udf_arg_0 != null", guarded)
+ # `x == None` is False in Python but NULL in SQL. The Catalyst target
lowers it
+ # specially and is tried first, so declining here costs nothing.
+ with self.assertRaises(UnsupportedOperationException):
+ _lower(
+ "def f(x):\n if x == None:\n return 1",
+ LongType(),
+ {0: "integral"},
+ )
+
+ def test_each_ordering_operator_keeps_its_own_operand_order(self):
+ # `>` gets its own helper rather than `<` with the operands swapped.
Swapping is correct
+ # for the result but reverses the order Java evaluates the two sides
in, so when both can
+ # raise the wrong one wins -- `x // 0 > x * x` would report the
overflow, where Python and
+ # a Catalyst GreaterThan both report the division.
+ lowered = _lower("def f(x):\n return x > 5", BooleanType(), {0:
"integral"})
+ self.assertIn("greaterThanLong(_udf_arg_0, Long.valueOf(5L))", lowered)
+ lowered = _lower("def f(x):\n return x >= 5", BooleanType(), {0:
"integral"})
+ self.assertIn("greaterThanOrEqualLong(_udf_arg_0, Long.valueOf(5L))",
lowered)
+ lowered = _lower("def f(x):\n return x < 5", BooleanType(), {0:
"integral"})
+ self.assertIn("lessThanLong(_udf_arg_0, Long.valueOf(5L))", lowered)
+
+ def test_shapes_whose_python_meaning_would_be_changed_are_declined(self):
Review Comment:
Fixed in 8d3c694b486: added a test that the parameter-assignment refusal and
`None is x` are declined with their own messages, an exact-literal test for
backslash, quote, newline, CR, tab, control character, BMP and U+1F600 (plus
the lone-surrogate refusal), an end-to-end round trip of those escapes against
interpreted Python, and an executed same-category conditional over True, False
and NULL rows. Dropping the backslash branch, swapping the conditional's
branches, or removing the parameter guard now fails a test.
---
<sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of
@holdenk.</sub>
<!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk
-->
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/TranspiledJavaUDFHelpersSuite.scala:
##########
@@ -0,0 +1,317 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.expressions
+
+import org.apache.spark.{SparkArithmeticException, SparkFunSuite,
SparkRuntimeException}
+import org.apache.spark.sql.catalyst.expressions.{TranspiledJavaUDFHelpers =>
H}
+import org.apache.spark.unsafe.types.UTF8String
+
+/**
+ * Pins the operators the `java` transpiler emits, one assertion per point
where Python, Java
+ * and ANSI SQL disagree. Everything here is also reachable through the Python
suites, but a
+ * failure there says "a query returned the wrong number" while a failure here
says which
+ * operator, which is the difference between a minute and an afternoon.
+ *
+ * The expected values are CPython's, checked against a real interpreter
rather than reasoned
+ * out.
+ */
+class TranspiledJavaUDFHelpersSuite extends SparkFunSuite {
+
+ private def utf8(s: String): UTF8String = UTF8String.fromString(s)
+
+ test("// and % follow Python's signs, not Java's") {
+ // Python: -7 // 3 == -3 and 7 // -3 == -3. Java's `/` gives -2 for both.
+ assert(H.floorDivideLong(-7L, 3L) === -3L)
+ assert(H.floorDivideLong(7L, -3L) === -3L)
+ assert(H.floorDivideLong(7L, 3L) === 2L)
+ // Python: -7 % 3 == 2 and 7 % -3 == -2. Java's `%` gives -1 and 1.
+ assert(H.modLong(-7L, 3L) === 2L)
+ assert(H.modLong(7L, -3L) === -2L)
+ assert(H.modLong(7L, 3L) === 1L)
+ }
+
+ test("float % follows the divisor's sign") {
+ // Python: -7.0 % 3.0 == 2.0, where Java's `%` gives -1.0.
+ assert(H.modDouble(-7.0d, 3.0d) === 2.0d)
+ assert(H.modDouble(7.0d, -3.0d) === -2.0d)
+ assert(H.floorDivideDouble(7.0d, 2.0d) === 3.0d)
+ assert(H.floorDivideDouble(-7.0d, 2.0d) === -4.0d)
+ }
+
+ test("float % and // are exact, not just correctly signed") {
+ // Getting the sign right is the easy half. `a - b * Math.floor(a / b)`
rounds three times and
+ // is wrong for almost every inexact pair -- it returns 0.0 for the first
case below. Every
+ // expected value here is CPython's.
+ assert(H.modDouble(5.5d, 1.1d) === 1.0999999999999996d)
+ assert(H.modDouble(100.0d, 3.3d) === 1.0000000000000053d)
+ assert(H.modDouble(0.7d, 0.1d) === 0.09999999999999992d)
+ assert(H.modDouble(1.0e16d, 3.0d) === 1.0d)
+ // Past 2^53 the quotient is inexact, so flooring it is off by one.
+ assert(H.floorDivideDouble(9007199254740994.0d, 3.0d) ===
3002399751580330.0d)
+ assert(H.modDouble(9007199254740994.0d, 3.0d) === 1.0d)
+ }
+
+ test("an infinite operand behaves as it does in Python") {
+ // A DoubleType column can hold Infinity -- it is what 1e308 * 10 produces
-- and
+ // `Math.floor(a / b)` gets every one of these wrong.
+ assert(H.modDouble(1.0d, Double.PositiveInfinity) === 1.0d)
+ assert(H.floorDivideDouble(1.0d, Double.PositiveInfinity) === 0.0d)
+ assert(H.modDouble(-1.0d, Double.PositiveInfinity) ===
Double.PositiveInfinity)
+ assert(H.floorDivideDouble(-1.0d, Double.PositiveInfinity) === -1.0d)
+ assert(H.modDouble(1.0d, Double.NegativeInfinity) ===
Double.NegativeInfinity)
+ assert(H.floorDivideDouble(1.0d, Double.NegativeInfinity) === -1.0d)
+ assert(H.floorDivideDouble(Double.PositiveInfinity, 2.0d).isNaN)
+ }
+
+ test("/ on two ints is float division") {
+ // Python: 5 / 2 == 2.5, not 2.
+ assert(H.divideLong(5L, 2L) === 2.5d)
+ assert(H.divideLong(-5L, 2L) === -2.5d)
+ }
+
+ test("/ on large ints rounds once, as CPython's exact-quotient division
does") {
+ // Widening both operands to double first rounds twice and lands a whole
ULP away. Expected
+ // values are CPython's `a / b` on ints, which is exact-rational then
correctly rounded.
+ assert(H.divideLong(9007199254740993L, 3L) === 3002399751580331.0d)
+ assert(H.divideLong(-228370678136506164L, 2709003016019L) ===
-84300.63635444267d)
+ // Still exact where both operands are representable, which is the fast
path.
+ assert(H.divideLong(1L << 53, 2L) === 4503599627370496.0d)
+ // A quotient sitting exactly on a tie, which needs a dyadic value and so
a terminating
+ // expansion: rounding to 34 digits and then to a double rounds twice and
lands 1 ULP out, so
+ // the exact divide has to be tried first. Compared as bits, because the
two candidates are
+ // adjacent doubles and `===` on the wrong one would still read as "close
enough". CPython's
+ // answer for this pair, and for 22k others swept alongside it.
+ assert(java.lang.Double.doubleToRawLongBits(
+ H.divideLong(14410791856275153L, -4611686018427387904L)) ===
0xbf699944f8c33f68L)
+ // A quotient a hair above a tie: 34 digits (DECIMAL128) round the
+ // intermediate onto the tie and the result lands a ulp down; 40 do not.
+ // CPython's answer.
+ assert(H.divideLong(2525447105329283886L, 1152921504606846997L) ===
2.1904761904761907d)
+ }
+
+ test("division by zero raises for both categories") {
+ // Java gives Infinity for the double case; Python raises for both.
+ Seq[() => Any](
+ () => H.divideLong(1L, 0L),
+ () => H.modLong(1L, 0L),
+ () => H.floorDivideLong(1L, 0L),
+ () => H.divideDouble(1.0d, 0.0d),
+ () => H.modDouble(1.0d, 0.0d),
+ () => H.floorDivideDouble(1.0d, 0.0d)
+ ).foreach { op =>
+ intercept[ArithmeticException](op())
+ }
+ }
+
+ test("integral overflow raises rather than wrapping") {
+ intercept[ArithmeticException](H.addLong(Long.MaxValue, 1L))
+ intercept[ArithmeticException](H.subtractLong(Long.MinValue, 1L))
+ intercept[ArithmeticException](H.multiplyLong(Long.MaxValue, 2L))
+ intercept[ArithmeticException](H.negateLong(Long.MinValue))
+ // The one floorDiv overflow, which Math.floorDiv wraps through silently.
+ intercept[ArithmeticException](H.floorDivideLong(Long.MinValue, -1L))
+ // Guarded before MathUtils.floorDiv, which would report a zero divisor as
an overflow.
+ assert(intercept[SparkArithmeticException](H.floorDivideLong(1L,
0L)).getCondition
+ === "DIVIDE_BY_ZERO")
+ }
+
+ test("float arithmetic overflows to infinity, as Python's does") {
+ assert(H.multiplyDouble(1.0e308d, 10.0d) === Double.PositiveInfinity)
+ }
+
+ test("null propagates through arithmetic") {
+ assert(H.addLong(null, 1L) === null)
+ assert(H.addLong(1L, null) === null)
+ assert(H.multiplyDouble(null, 1.0d) === null)
+ assert(H.concat(null, utf8("a")) === null)
+ assert(H.repeat(utf8("a"), null) === null)
+ assert(H.negateLong(null) === null)
+ assert(H.toDouble(null) === null)
+ // The promotion itself rounds, like Python's float(int): past 2^53 the
double
+ // is the nearest, not the exact, long.
+ assert(H.toDouble(9007199254740993L) === 9007199254740992.0d)
+ }
+
+ test("equality is null-safe, because Python's is") {
+ // `None == None` is True and `None == 1` is False in Python -- definite
booleans, never None.
+ // SQL's `=` would answer NULL to both, which comes back out of the UDF as
`None` where Python
+ // produced a bool: `x != 1` over a NULL column would be NULL instead of
True. These are SQL's
+ // `<=>`, which coincides with Python exactly, and the Catalyst target
hand-rolls the same four
+ // cases in `_lower_eq`.
+ assert(H.equalsLong(null, null) === true)
+ assert(H.equalsLong(null, 1L) === false)
+ assert(H.equalsLong(1L, null) === false)
+ assert(H.equalsLong(1L, 1L) === true)
+ assert(H.equalsDouble(null, null) === true)
Review Comment:
Fixed in 8d3c694b486: the helper suite now pins `equalsDouble(NaN, NaN)` as
false and `equalsDouble(0.0, -0.0)` as true, adds NaN and signed-zero ordering
cases, and compares `modDouble(1.0, -1.0)`, `modDouble(-1.0, -1.0)` and
`floorDivideDouble(-0.0, 5.0)` by raw bits (plus the positive-zero
counterparts).
---
<sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of
@holdenk.</sub>
<!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk
-->
##########
python/pyspark/sql/tests/test_udf_transpile_java_unit.py:
##########
@@ -0,0 +1,1039 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""
+Unit tests for the ``java`` UDF transpilation target.
+
+Two kinds of test live here. The lowering tests call the transpiler directly
and assert on
+the Java source it produces, which is cheap and says exactly what changed when
one breaks.
+The end-to-end tests run queries and compare against interpreted Python, which
is the only
+thing that can catch a body that lowers but computes the wrong answer.
+
+The companion suites for the Catalyst target are
``test_udf_transpile_unit.py`` and
+``test_udf_transpile_hypothesis.py``; ``test_udf_transpile_parity.py`` re-runs
the shared
+UDF mixins with this target enabled.
+"""
+
+import ast
+import textwrap
+import unittest
+
+from pyspark.errors import UnsupportedOperationException
+from pyspark.sql.functions import col, lit, rand
+from pyspark.sql.types import (
+ BinaryType,
+ BooleanType,
+ DoubleType,
+ LongType,
+ StringType,
+)
+from pyspark.sql.udf import UserDefinedFunction
+from pyspark.testing.sqlutils import ReusedSQLTestCase
+from pyspark.util import is_remote_only
+
+# Transpilation needs both flags; ANSI because the lowerings target ANSI
semantics. The
+# `java` target additionally has to be named in the transpiler list, which is
what makes it
+# opt-in -- the default stays `catalyst`.
+_JAVA_ONLY = {
+ "spark.sql.experimental.optimizer.transpilePyUDFs": True,
+ "spark.sql.ansi.enabled": True,
+ "spark.sql.experimental.optimizer.pyTranspilers": "java",
+}
+
+_CATALYST_THEN_JAVA = dict(
+ _JAVA_ONLY,
+ **{
+ "spark.sql.experimental.optimizer.pyTranspilers": "catalyst,java",
+ },
+)
+
+_CATALYST_ONLY = dict(
+ _JAVA_ONLY,
+ **{
+ "spark.sql.experimental.optimizer.pyTranspilers": "catalyst",
+ },
+)
+
+# A true interpreted baseline. Naming no transpiler is not enough to get one:
the Catalyst
+# target lowers more than it might seem -- `%`, and a body that just returns a
parameter --
+# so a test that wants interpreted Python has to turn transpilation off rather
than assume
+# some particular body defeats it.
+_TRANSPILE_OFF = {
+ "spark.sql.experimental.optimizer.transpilePyUDFs": False,
+ "spark.sql.ansi.enabled": True,
+}
+
+
+def _lower(source: str, return_type, categories: dict) -> str:
+ """Lower ``source``'s function to Java statements, without a session or a
JVM.
+
+ Drives the transpiler below its ``_build_column`` step, which is the only
part that
+ needs a live JVM, so the generated source can be asserted on directly.
+ """
+ from pyspark.sql.transpile import _get_function_from_ast
+ from pyspark.sql.transpile_java import JavaTranspiler, _return_category
+
+ tree = ast.parse(textwrap.dedent(source))
+ function_ast, error = _get_function_from_ast(tree, None)
+ assert function_ast is not None, error
+ transpiler = JavaTranspiler()
+ transpiler._bind([arg.arg for arg in function_ast.args.args], categories)
+ return "\n".join(transpiler._lower_body(function_ast.body,
_return_category(return_type)))
+
+
+class JavaTranspileLoweringTests(unittest.TestCase):
+ """Tests over the generated source. No session, no JVM."""
+
+ def test_arithmetic_goes_through_the_helpers(self):
+ # Never a bare Java operator: `+` would wrap silently where ANSI must
raise, and
+ # `%` and `/` have the wrong sign and the wrong zero behaviour for
Python.
+ lowered = _lower("def f(x):\n return x + 1", LongType(), {0:
"integral"})
+ self.assertIn("TranspiledJavaUDFHelpers.addLong(_udf_arg_0", lowered)
+ self.assertNotIn("_udf_arg_0 +", lowered)
+
+ def test_floor_divide_and_mod_use_the_floor_helpers(self):
+ floor_div = _lower("def f(x):\n return x // 3", LongType(), {0:
"integral"})
+ self.assertIn("floorDivideLong", floor_div)
+ mod = _lower("def f(x):\n return x % 3", LongType(), {0:
"integral"})
+ self.assertIn("modLong", mod)
+
+ def test_true_divide_of_ints_produces_a_float(self):
+ # Python's `/` is always float division, so an int body under a
declared double is
+ # the correct shape and an int return type is refused.
+ lowered = _lower("def f(x):\n return x / 2", DoubleType(), {0:
"integral"})
+ self.assertIn("divideLong", lowered)
+ with self.assertRaises(UnsupportedOperationException):
+ _lower("def f(x):\n return x / 2", LongType(), {0: "integral"})
+
+ def test_multi_statement_body_with_local_and_early_return(self):
+ lowered = _lower(
+ """
+ def f(x):
+ doubled = x * 2
+ if doubled > 10:
+ return 10
+ return doubled + 1
+ """,
+ LongType(),
+ {0: "integral"},
+ )
+ self.assertIn("_doubled =", lowered)
+ self.assertIn("Long _udf_local_0", lowered)
+ self.assertIn("return Long.valueOf(10L);", lowered)
+
+ def test_locals_needing_the_same_sanitised_name_stay_distinct(self):
+ # Sanitising to Java's character set is not injective on its own: a
non-ASCII name
+ # and an underscore name can reduce to the same text, and two locals
sharing one
+ # Java variable would be a silently wrong answer rather than a
failure. The numbering
+ # is what prevents it.
+ # The identifier is spelled with an escape so this file stays ASCII,
per the
+ # project's convention; what `ast.parse` sees is still a non-ASCII
name.
+ accented = "caf\u00e9"
+ lowered = _lower(
+ f"""
+ def f(x):
+ {accented} = x + 1
+ caf_ = x + 2
+ return {accented} + caf_
+ """,
+ LongType(),
+ {0: "integral"},
+ )
+ self.assertIn("_udf_local_0_caf_", lowered)
+ self.assertIn("_udf_local_1_caf_", lowered)
+
+ def test_no_unreachable_return_when_every_path_returns(self):
+ # Java rejects an unreachable statement, so the trailing `return null`
that stands
+ # for Python falling off the end must not be emitted when it cannot be
reached.
+ both = _lower(
+ """
+ def f(x):
+ if x > 0:
+ return 1
+ else:
+ return 2
+ """,
+ LongType(),
+ {0: "integral"},
+ )
+ # Two returns, one per branch, and crucially no third one after the
`if`.
+ self.assertEqual(2, both.count("return "), both)
+ self.assertNotIn("null", both)
+
+ # ... and must be emitted when it can, since `if` alone falls through.
+ falls_through = _lower(
+ """
+ def f(x):
+ if x > 0:
+ return 1
+ """,
+ LongType(),
+ {0: "integral"},
+ )
+ self.assertIn("return ((Long) null);", falls_through)
+
+ def test_int_promotes_to_float_when_mixed(self):
+ lowered = _lower(
+ "def f(a, b):\n return a + b", DoubleType(), {0: "integral", 1:
"fractional"}
+ )
+ self.assertIn("toDouble(_udf_arg_0)", lowered)
+ self.assertIn("addDouble", lowered)
+
+ def test_mixed_int_float_comparison_is_exact_not_widened(self):
+ # Arithmetic widens the int (Python does too), but comparison must
not: widening
+ # 9007199254740993 to a double rounds it to 9007199254740992.0 and
calls them equal
+ # where CPython says they are not. So the helper is direction-aware,
not toDouble.
+ eq_long_double = _lower(
+ "def f(a, b):\n return a == b", BooleanType(), {0: "integral",
1: "fractional"}
+ )
+ self.assertIn("equalsLongDouble(_udf_arg_0, _udf_arg_1)",
eq_long_double)
+ self.assertNotIn("toDouble", eq_long_double)
+ eq_double_long = _lower(
+ "def f(a, b):\n return a == b", BooleanType(), {0:
"fractional", 1: "integral"}
+ )
+ self.assertIn("equalsDoubleLong(_udf_arg_0, _udf_arg_1)",
eq_double_long)
+ self.assertNotIn("toDouble", eq_double_long)
+ neq = _lower(
+ "def f(a, b):\n return a != b", BooleanType(), {0: "integral",
1: "fractional"}
+ )
+ # `!=` is `not(equals)`, so the exact helper still runs and is then
negated.
+ self.assertIn("equalsLongDouble(_udf_arg_0, _udf_arg_1)", neq)
+ self.assertIn("Helpers.not(", neq)
+ lt = _lower(
+ "def f(a, b):\n return a < b", BooleanType(), {0: "integral",
1: "fractional"}
+ )
+ self.assertIn("lessThanLongDouble(_udf_arg_0, _udf_arg_1)", lt)
+ gt = _lower(
+ "def f(a, b):\n return a > b", BooleanType(), {0: "fractional",
1: "integral"}
+ )
+ self.assertIn("greaterThanDoubleLong(_udf_arg_0, _udf_arg_1)", gt)
+
+ def test_string_concat_and_repeat(self):
+ concat = _lower("def f(s):\n return s + 'x'", StringType(), {0:
"string"})
+ self.assertIn("TranspiledJavaUDFHelpers.concat", concat)
+ self.assertIn('UTF8String.fromString("x")', concat)
+ repeat = _lower(
+ "def f(s, n):\n return s * n", StringType(), {0: "string", 1:
"integral"}
+ )
+ self.assertIn("TranspiledJavaUDFHelpers.repeat", repeat)
+
+ def test_repeat_refuses_a_fractional_count(self):
+ # The divergence the Catalyst target documents: there a fractional
count from a
+ # column is truncated by the cast it inserts, where Python raises
TypeError. Here
+ # the count's category is known before any source is emitted, so it is
declined.
+ with self.assertRaises(UnsupportedOperationException):
+ _lower(
+ "def f(s, n):\n return s * n",
+ StringType(),
+ {0: "string", 1: "fractional"},
+ )
+
+ def test_non_ascii_string_literal_is_escaped(self):
+ lowered = _lower("def f(s):\n return s + '\u00e9'", StringType(),
{0: "string"})
+ self.assertIn("\\u00e9", lowered)
+ # The generated source stays ASCII so no compiler has to be asked how
it decodes.
+ self.assertTrue(lowered.isascii(), lowered)
+
+ def test_is_none_lowers_but_eq_none_declines(self):
+ guarded = _lower(
+ """
+ def f(x):
+ if x is not None:
+ return x + 1
+ """,
+ LongType(),
+ {0: "integral"},
+ )
+ self.assertIn("_udf_arg_0 != null", guarded)
+ # `x == None` is False in Python but NULL in SQL. The Catalyst target
lowers it
+ # specially and is tried first, so declining here costs nothing.
+ with self.assertRaises(UnsupportedOperationException):
+ _lower(
+ "def f(x):\n if x == None:\n return 1",
+ LongType(),
+ {0: "integral"},
+ )
+
+ def test_each_ordering_operator_keeps_its_own_operand_order(self):
+ # `>` gets its own helper rather than `<` with the operands swapped.
Swapping is correct
+ # for the result but reverses the order Java evaluates the two sides
in, so when both can
+ # raise the wrong one wins -- `x // 0 > x * x` would report the
overflow, where Python and
+ # a Catalyst GreaterThan both report the division.
+ lowered = _lower("def f(x):\n return x > 5", BooleanType(), {0:
"integral"})
+ self.assertIn("greaterThanLong(_udf_arg_0, Long.valueOf(5L))", lowered)
+ lowered = _lower("def f(x):\n return x >= 5", BooleanType(), {0:
"integral"})
+ self.assertIn("greaterThanOrEqualLong(_udf_arg_0, Long.valueOf(5L))",
lowered)
+ lowered = _lower("def f(x):\n return x < 5", BooleanType(), {0:
"integral"})
+ self.assertIn("lessThanLong(_udf_arg_0, Long.valueOf(5L))", lowered)
+
+ def test_shapes_whose_python_meaning_would_be_changed_are_declined(self):
+ # Each of these lowered to something plausible-looking and wrong
before, so they are
+ # pinned as refusals rather than left to a reviewer to notice.
+ cases = {
+ # Python short-circuits `and`; a helper call cannot, so the guard
would not guard.
+ "and": (
+ "def f(a, b):\n return b != 0 and a > 1",
+ BooleanType(),
+ {0: "integral", 1: "integral"},
+ ),
+ "or": (
+ "def f(a, b):\n return b == 0 or a > 1",
+ BooleanType(),
+ {0: "integral", 1: "integral"},
+ ),
+ # Python's `not None` is True; SQL's `NOT NULL` is NULL.
+ "not None": ("def f(x):\n return not None", BooleanType(), {0:
"integral"}),
+ # `None == x` is as much a None comparison as `x == None`.
+ "None on the left": ("def f(x):\n return None == x",
BooleanType(), {0: "integral"}),
+ # An annotation is not a cast: converting would lose precision
past 2**53.
+ "annotation as cast": (
+ "def f(x):\n y: float = x\n return y",
+ DoubleType(),
+ {0: "integral"},
+ ),
+ }
+ for label, (source, return_type, categories) in cases.items():
+ with self.subTest(case=label):
+ with self.assertRaises(UnsupportedOperationException):
+ _lower(source, return_type, categories)
+
+ def test_no_statement_is_emitted_after_a_definite_return(self):
+ # Python just never runs these; Java rejects them as unreachable (JLS
14.21), and a body
+ # that does not compile is a failed query rather than a fallback once
the option is in the
+ # plan. Both shapes below occur in real code -- a defensive trailing
return, and dead code.
+ after_if_else = _lower(
+ """
+ def f(x):
+ if x > 0:
+ return 1
+ else:
+ return 2
+ return 0
+ """,
+ LongType(),
+ {0: "integral"},
+ )
+ # Matched with the `return` and the `;`: the condition `x > 0`
legitimately contains a
+ # bare `Long.valueOf(0L)`, so the looser check would fail on correct
output.
+ self.assertNotIn("return Long.valueOf(0L);", after_if_else)
+ after_return = _lower(
+ """
+ def f(x):
+ return x
+ y = x + 1
+ """,
+ LongType(),
+ {0: "integral"},
+ )
+ self.assertNotIn("_udf_local", after_return)
+
+ def test_refusals_fall_back_rather_than_guess(self):
+ # Each of these is a shape whose Python meaning the target will not
reproduce.
+ cases = {
+ "bitwise": "def f(x):\n return x & 1",
+ "chained comparison": "def f(x):\n return 1 < x < 5",
+ "loop": "def f(x):\n for i in range(3):\n x = x + 1\n
return x",
+ "try": "def f(x):\n try:\n return x\n except
Exception:\n return 0",
+ "truthiness": "def f(x):\n if x:\n return 1\n return
0",
+ "free variable": "def f(x):\n return x + undefined_name",
+ "attribute": "def f(x):\n return x.bit_length()",
+ "augmented assign": "def f(x):\n x += 1\n return x",
+ "unary minus on text": "def f(s):\n return -s",
+ "while": "def f(x):\n while x > 0:\n x = x - 1\n
return x",
+ }
+ for label, source in cases.items():
+ with self.subTest(case=label):
+ with self.assertRaises(UnsupportedOperationException):
+ category = "string" if label == "unary minus on text" else
"integral"
+ return_type = StringType() if category == "string" else
LongType()
+ _lower(source, return_type, {0: category})
+
+ def test_local_reassigned_to_another_category_declines(self):
+ # A Java local has one type. Rather than rename per assignment,
decline.
+ with self.assertRaises(UnsupportedOperationException):
+ _lower(
+ """
+ def f(x):
+ y = x + 1
+ y = 'text'
+ return y
+ """,
+ StringType(),
+ {0: "integral"},
+ )
+
+ def test_local_first_bound_inside_a_branch_declines(self):
+ # Python would have it bound after the `if`; a Java local declared in
the block
+ # would not exist there. Declining is the fail-closed choice.
+ with self.assertRaises(UnsupportedOperationException):
+ _lower(
+ """
+ def f(x):
+ if x > 0:
+ y = 1
+ return y
+ """,
+ LongType(),
+ {0: "integral"},
+ )
+
+ def test_category_combos_split_numeric_and_pin_annotations(self):
+ from pyspark.sql.transpile_java import JavaTranspiler
+
+ annotated = ast.parse("def f(a: int, b: float, c: str): return
a").body[0]
+ combos = JavaTranspiler()._param_category_combos(annotated, ["a", "b",
"c"])
+ self.assertEqual([{0: "integral", 1: "fractional", 2: "string"}],
combos)
+
+ # One untyped parameter is tried as all three categories.
+ untyped = ast.parse("def f(a): return a").body[0]
+ combos = JavaTranspiler()._param_category_combos(untyped, ["a"])
+ self.assertEqual(
+ [{0: "integral"}, {0: "fractional"}, {0: "string"}],
+ combos,
+ )
+
+ def test_category_combos_cap_engages_past_two_untyped(self):
+ from pyspark.sql.transpile_java import JavaTranspiler
+
+ # Both sides of the boundary, because the earlier version of this test
used four untyped
+ # parameters -- collapsed under either threshold -- so the cap could
have moved from two to
+ # three, or vanished, without failing. Two untyped is the largest
uncapped case and the one
+ # that costs the most driver-side compiles.
+ two = ast.parse("def f(a, b): return a").body[0]
+ self.assertEqual(9, len(JavaTranspiler()._param_category_combos(two,
["a", "b"])))
+
+ three = ast.parse("def f(a, b, c): return a").body[0]
+ self.assertEqual(3, len(JavaTranspiler()._param_category_combos(three,
["a", "b", "c"])))
+
+ # And a pinned parameter stays pinned once the cap engages.
+ fn = ast.parse("def f(a: str, b, c, d, e): return a").body[0]
+ combos = JavaTranspiler()._param_category_combos(fn, ["a", "b", "c",
"d", "e"])
+ self.assertEqual(3, len(combos))
+ for combo in combos:
+ self.assertEqual("string", combo[0])
+
+ def test_category_combos_counts_positional_only_parameters(self):
+ from pyspark.sql.transpile_java import JavaTranspiler
+
+ # `function_ast.args.args` alone omits positional-only params, which
would have
+ # undercounted `public_params` here and raised IndexError (or, with a
mix of
+ # positional-only and regular params, silently paired categories with
the wrong
+ # names) rather than returning one combo per annotated category.
+ fn = ast.parse("def f(a: int, b: float, /, c: str): return a").body[0]
+ combos = JavaTranspiler()._param_category_combos(fn, ["a", "b", "c"])
+ self.assertEqual([{0: "integral", 1: "fractional", 2: "string"}],
combos)
+
+ def test_a_none_valued_conditional_keeps_its_condition(self):
+ # `_coerce` used to replace a "none"-category value with a bare
`null`, discarding the code
+ # that produced it -- so this body lowered to `return ((Long) null);`
and the divide
+ # vanished, returning NULL where CPython raises ZeroDivisionError on b
= 0.
+ lowered = _lower(
+ "def f(a, b):\n return None if a // b > 0 else None",
+ LongType(),
+ {0: "integral", 1: "integral"},
+ )
+ self.assertIn("floorDivideLong", lowered)
+
+ def test_unsupported_return_type_declines(self):
+ from pyspark.sql.types import DecimalType, TimestampType
+
+ for return_type in (DecimalType(10, 2), TimestampType()):
+ with self.subTest(return_type=return_type.simpleString()):
+ with self.assertRaises(UnsupportedOperationException):
+ _lower("def f(x):\n return x", return_type, {0:
"integral"})
+
+
[email protected](
+ is_remote_only(),
+ "UDF transpilation is only supported in regular (non-Connect) Spark.",
+)
+class JavaTranspileEndToEndTests(ReusedSQLTestCase):
+ """Tests that actually run the generated code and compare against
interpreted Python."""
+
+ def _plan(self, df) -> str:
+ return df._jdf.queryExecution().optimizedPlan().toString()
+
+ def test_java_target_is_off_by_default(self):
+ # The whole point of the opt-in: with the conf untouched, a body only
this
+ # target can lower must still run as interpreted Python. No
pyTranspilers
+ # override here -- the test pins the default itself, not a spelling of
it.
+ def multi(x):
+ doubled = x * 2
+ return doubled + 1
+
+ with self.sql_conf(
+ {
+ "spark.sql.experimental.optimizer.transpilePyUDFs": True,
+ "spark.sql.ansi.enabled": True,
+ }
+ ):
+ self.assertEqual([], UserDefinedFunction(multi,
LongType()).transpiled)
+
+ def test_catalyst_wins_when_both_can_lower(self):
+ # Ordering is what makes `catalyst,java` safe: a UDF Catalyst can
lower keeps the
+ # Catalyst option, which the optimizer can see into, and never the
opaque one.
+ def plus_one(x):
+ if x is not None:
+ return x + 1
+
+ df = self.spark.range(3).select(col("id").alias("a"))
+ with self.sql_conf(_CATALYST_THEN_JAVA):
+ udf = UserDefinedFunction(plus_one, LongType())
+ plan = self._plan(df.select(udf(col("a"))))
+ self.assertNotIn("TranspiledJavaUDF", plan)
+ self.assertNotIn("BatchEvalPython", plan)
+
+ with self.sql_conf(_JAVA_ONLY):
+ udf = UserDefinedFunction(plus_one, LongType())
+ plan = self._plan(df.select(udf(col("a"))))
+ self.assertIn("TranspiledJavaUDF", plan)
+
+ def test_multi_statement_lowers_only_with_java(self):
+ # The capability that justifies a second target.
+ def clamp(x):
+ doubled = x * 2
+ if doubled > 10:
+ return 10
+ return doubled + 1
+
+ df = self.spark.createDataFrame([(3,), (9,)], "a bigint")
+ with self.sql_conf(_CATALYST_ONLY):
+ udf = UserDefinedFunction(clamp, LongType())
+ self.assertEqual([], udf.transpiled)
+ interpreted = df.select(udf(col("a"))).collect()
+
+ with self.sql_conf(_CATALYST_THEN_JAVA):
+ udf = UserDefinedFunction(clamp, LongType())
+ self.assertTrue(udf.transpiled)
+ result = df.select(udf(col("a")))
+ self.assertIn("TranspiledJavaUDF", self._plan(result))
+ self.assertNotIn("BatchEvalPython", self._plan(result))
+ self.assertEqual([r[0] for r in interpreted], [r[0] for r in
result.collect()])
+
+ def test_repeated_parameter_read_adds_no_projection(self):
+ # A body reading one parameter three times: the reads are inside the
generated
+ # source, so the plan holds one child and nothing has to be hoisted
into a Project
+ # to keep the argument to one evaluation.
+ def thrice(x):
+ return x + x + x
+
+ df = self.spark.range(3).select((col("id") * 2).alias("a"))
+ with self.sql_conf(_JAVA_ONLY):
+ udf = UserDefinedFunction(thrice, LongType())
+ result = df.select(udf(col("a")))
+ plan = self._plan(result)
+ self.assertIn("TranspiledJavaUDF", plan)
+ self.assertNotIn("BatchEvalPython", plan)
+ # The claim in the name: the select's own Project is the only one
--
+ # nothing was hoisted to give the argument a column of its own.
+ self.assertEqual(1, plan.count("Project"))
+ self.assertEqual([0, 6, 12], [r[0] for r in result.collect()])
+
+ def test_results_match_interpreted_python(self):
+ # The check that matters: the same function, run both ways, over
values chosen to
+ # hit the sign and zero cases where Python, Java and SQL disagree.
+ def arithmetic(x):
+ if x is not None:
+ return x // 3
+
+ def modulo(x):
+ if x is not None:
+ return x % 3
+
+ def promoted(x):
+ if x is not None:
+ return x / 4
+
+ rows = [(-7,), (-1,), (0,), (7,), (8,)]
+ df = self.spark.createDataFrame(rows, "a bigint")
+ for func, return_type in (
+ (arithmetic, LongType()),
+ (modulo, LongType()),
+ (promoted, DoubleType()),
+ ):
+ with self.subTest(func=func.__name__):
+ with self.sql_conf(_TRANSPILE_OFF):
+ plain = UserDefinedFunction(func, return_type)
+ self.assertEqual([], plain.transpiled)
+ expected = [r[0] for r in
df.select(plain(col("a"))).collect()]
+ with self.sql_conf(_JAVA_ONLY):
+ lowered = UserDefinedFunction(func, return_type)
+ self.assertTrue(lowered.transpiled)
+ actual = [r[0] for r in
df.select(lowered(col("a"))).collect()]
+ self.assertEqual(expected, actual)
+
+ def test_python_floor_and_mod_signs(self):
+ # Pinned values, not just agreement: -7 // 3 is -3 and -7 % 3 is 2 in
Python, where
+ # Java's own operators give -2 and -1.
+ def floor_div(x):
+ if x is not None:
+ return x // 3
+
+ def modulo(x):
+ if x is not None:
+ return x % 3
+
+ df = self.spark.createDataFrame([(-7,)], "a bigint")
+ with self.sql_conf(_JAVA_ONLY):
+ self.assertEqual(
+ -3, df.select(UserDefinedFunction(floor_div,
LongType())(col("a"))).first()[0]
+ )
+ self.assertEqual(
+ 2, df.select(UserDefinedFunction(modulo,
LongType())(col("a"))).first()[0]
+ )
+
+ def test_null_propagates_like_the_catalyst_target(self):
+ # An unguarded body over a NULL gives NULL on both transpiled targets,
where
+ # interpreted Python raises TypeError. Documented, and the same on
both, so which
+ # backend fired is not observable from the result.
+ def unguarded(x):
+ return x + 1
+
+ df = self.spark.createDataFrame([(None,), (1,)], "a bigint")
+ with self.sql_conf(_JAVA_ONLY):
+ udf = UserDefinedFunction(unguarded, LongType())
+ self.assertTrue(udf.transpiled)
+ self.assertEqual([None, 2], [r[0] for r in
df.select(udf(col("a"))).collect()])
+
+ def test_equality_over_null_is_null_safe_like_python(self):
+ # Python's `==` is not three-valued: `None == None` is True and `None
== 1` is False, never
+ # None. Propagating NULL instead made `x != 1` return NULL over a NULL
column where Python
+ # returns True, and `if x != 1` take the wrong branch. Three
statements, so Catalyst
+ # declines and the java option is what runs.
+ def not_one(x):
+ y = 1
+ if x != 1:
+ y = 10
+ return y
+
+ def both_none(a, b):
+ same = a == b
+ if same:
+ return 1
+ return 0
+
+ df = self.spark.createDataFrame([(None,)], "a bigint")
+ pair = self.spark.createDataFrame([(None, None)], "a bigint, b bigint")
+ with self.sql_conf(_TRANSPILE_OFF):
+ expected_ne = df.select(UserDefinedFunction(not_one,
LongType())(col("a"))).first()[0]
+ expected_eq = pair.select(
+ UserDefinedFunction(both_none, LongType())(col("a"), col("b"))
+ ).first()[0]
+ with self.sql_conf(_JAVA_ONLY):
+ udf_ne = UserDefinedFunction(not_one, LongType())
+ self.assertTrue(udf_ne.transpiled)
+ self.assertEqual(expected_ne,
df.select(udf_ne(col("a"))).first()[0])
+ udf_eq = UserDefinedFunction(both_none, LongType())
+ self.assertTrue(udf_eq.transpiled)
+ self.assertEqual(expected_eq, pair.select(udf_eq(col("a"),
col("b"))).first()[0])
+ # Pinned, not just agreed: `None != 1` is True so the branch is taken,
and
+ # `None == None` is True.
+ self.assertEqual(10, expected_ne)
+ self.assertEqual(1, expected_eq)
+
+ def test_a_bare_none_local_declines_with_a_python_level_message(self):
+ # `y = None` is ordinary Python. Declining is fine; the message has to
name the construct
+ # rather than leak the internal "no Java type for category 'none'".
+ def maybe(x):
+ y = None
+ if x is not None:
+ y = x
+ return y
+
+ with self.sql_conf(_JAVA_ONLY):
+ import warnings as _w
+
+ with _w.catch_warnings(record=True) as caught:
+ _w.simplefilter("always")
+ udf = UserDefinedFunction(maybe, LongType())
+ self.assertEqual([], udf.transpiled)
+ messages = " ".join(str(w.message) for w in caught)
+ self.assertIn("bare None", messages)
+ self.assertNotIn("no Java type for category", messages)
+ self.assertNotIn("no ABI for category", messages)
+
+ def test_both_eval_paths_agree(self):
+ # `eval` and `doGenCode` come off one source string; this is what says
so from the
+ # outside. Codegen off exercises the per-JVM compile in the
interpreted path.
+ def clamp(x):
+ doubled = x * 2
+ if doubled > 10:
+ return 10
+ return doubled + 1
+
+ df = self.spark.createDataFrame([(1,), (3,), (9,)], "a bigint")
+ results = []
+ for factory_mode in ("CODEGEN_ONLY", "NO_CODEGEN"):
+ with self.sql_conf(dict(_JAVA_ONLY,
**{"spark.sql.codegen.factoryMode": factory_mode})):
+ udf = UserDefinedFunction(clamp, LongType())
+ results.append([r[0] for r in
df.select(udf(col("a"))).collect()])
+ self.assertEqual(results[0], results[1])
+ self.assertEqual([3, 7, 10], results[0])
+
+ def test_a_literal_argument_works(self):
+ # `foldable` is deliberately not overridden, so ConstantFolding does
not fire on this node
+ # -- the interpreted path exists for NO_CODEGEN, not for folding. What
this pins is that a
+ # literal argument still produces the right answer.
+ def plus_one(x):
+ return x + 1
+
+ with self.sql_conf(_JAVA_ONLY):
+ udf = UserDefinedFunction(plus_one, LongType())
+ result = self.spark.range(1).select(udf(lit(41)).alias("v"))
+ self.assertEqual(42, result.first()[0])
+
+ def test_float_mod_is_exact_not_just_correctly_signed(self):
+ # The bug this replaced got the sign right and the value wrong for
almost every inexact
+ # pair, returning 0.0 for `5.5 % 1.1`. Compared against interpreted
Python rather than a
+ # hand-written constant.
+ def remainder(x):
+ if x is not None:
+ return x % 1.1
+
+ rows = [(5.5,), (100.0,), (0.7,), (-5.5,), (1e16,)]
+ df = self.spark.createDataFrame(rows, "a double")
+ with self.sql_conf(_TRANSPILE_OFF):
+ expected = [
+ r[0]
+ for r in df.select(UserDefinedFunction(remainder,
DoubleType())(col("a"))).collect()
+ ]
+ with self.sql_conf(_JAVA_ONLY):
+ udf = UserDefinedFunction(remainder, DoubleType())
+ self.assertTrue(udf.transpiled)
+ actual = [r[0] for r in df.select(udf(col("a"))).collect()]
Review Comment:
Fixed in 8d3c694b486: each of the six fractional- and string-input
end-to-end tests you listed now asserts `TranspiledJavaUDF` is in the optimized
plan before comparing results.
---
<sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of
@holdenk.</sub>
<!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk
-->
##########
python/pyspark/sql/transpile_java.py:
##########
@@ -0,0 +1,793 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""
+The ``java`` UDF transpilation target: Python UDF to generated Java source.
+
+Opt in after ``catalyst``::
+
+ spark.conf.set("spark.sql.experimental.optimizer.pyTranspilers",
"catalyst,java")
+
+Tried left to right; first surviving option wins. ``catalyst`` first is the
+recommendation: a Catalyst lowering is ordinary expressions the optimizer can
+push, prune and fold, while a generated body is opaque. This target buys reach,
+not speed relative to Catalyst -- speed relative to a Python worker.
+
+A Catalyst option is an expression, so it refuses more than one top-level
+statement. A Java method has statements, so this target lowers locals, several
+statements, early returns, and ``/`` / ``//``.
+
+Each argument is a method parameter, so a body that reads it N times still
+evaluates it once (the thing SPARK-58626 is about for Catalyst). The flip side:
+unread arguments are still evaluated, matching the interpreted UDF and not a
+Catalyst lowering.
+
+Arithmetic propagates null (``None + 1`` is NULL, same as Catalyst). Ordering
+raises on null (same as Catalyst). ``NaN`` uses raw IEEE, which is CPython's
+and not Spark's normalised ``NaN == NaN``.
+
+``"numeric"`` is split into ``"integral"`` (Long) and ``"fractional"``
+(Double). Annotate parameters to keep the option count down.
+
+Overflow, ``//`` / ``%`` signs, and every other Python/Java/ANSI fight live in
+``TranspiledJavaUDFHelpers``.
+
+What falls back (``UnsupportedOperationException`` -> ordinary fallback):
+
+* ``and`` / ``or`` -- a helper call cannot short-circuit
+ (``b != 0 and a // b > 1``). Catalyst's ``And`` can, so ``catalyst,java``
+ keeps them.
+* ``== None`` / ``!= None`` -- use ``is None`` / ``is not None``.
+* ``None is x`` / ``None is not x`` -- reverse it to ``x is None``.
+* ``not`` over anything but a real boolean.
+* An annotated local whose annotation disagrees with its value.
+* Loops, ``try``/``except``, string methods, bitwise ops, and any type
+ outside integral/fractional/str/bool/bytes.
+"""
+
+import ast
+import itertools
+from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Tuple
+
+from pyspark.errors import UnsupportedOperationException
+from pyspark.sql.column import Column
+from pyspark.sql.functions import col
+from pyspark.sql.transpile import AbstractTranspiler, _is_definitely_boolean,
_positional_args
+from pyspark.sql.types import (
+ BinaryType,
+ BooleanType,
+ DataType,
+ DecimalType,
+ DoubleType,
+ FractionalType,
+ IntegralType,
+ LongType,
+ StringType,
+)
+
+if TYPE_CHECKING:
+ from pyspark.sql._typing import DataTypeOrString
+
+# One table: Catalyst type and Java type are the same ABI decision. Split
tables let a
+# new category pass the entry-point check and fail later inside the lowering.
+_CATEGORY_ABI: Dict[str, Tuple[DataType, str]] = {
+ "integral": (LongType(), "Long"),
+ "fractional": (DoubleType(), "Double"),
+ "string": (StringType(), "UTF8String"),
+ "bool": (BooleanType(), "Boolean"),
+ "binary": (BinaryType(), "byte[]"),
+}
+
+# FQCN: this is off by default, so the helpers stay off codegen's
default-import list.
+_HELPERS = "org.apache.spark.sql.catalyst.expressions.TranspiledJavaUDFHelpers"
+
+# Per-category operator helper names. Keyed by (ast op class name, category).
+_BINARY_HELPERS: Dict[Tuple[str, str], str] = {
+ ("Add", "integral"): "addLong",
+ ("Add", "fractional"): "addDouble",
+ ("Add", "string"): "concat",
+ ("Sub", "integral"): "subtractLong",
+ ("Sub", "fractional"): "subtractDouble",
+ ("Mult", "integral"): "multiplyLong",
+ ("Mult", "fractional"): "multiplyDouble",
+ ("FloorDiv", "integral"): "floorDivideLong",
+ ("FloorDiv", "fractional"): "floorDivideDouble",
+ ("Mod", "integral"): "modLong",
+ ("Mod", "fractional"): "modDouble",
+ # Python's `/` on two ints is a float, so this one changes category (see
`_lower_binop`).
+ ("Div", "integral"): "divideLong",
+ ("Div", "fractional"): "divideDouble",
+}
+
+_ORDER_OPS = {ast.Lt: "Lt", ast.LtE: "LtE", ast.Gt: "Gt", ast.GtE: "GtE"}
+
+_COMPARE_HELPERS: Dict[Tuple[str, str], str] = {
+ ("Eq", "integral"): "equalsLong",
+ ("Eq", "fractional"): "equalsDouble",
+ ("Eq", "string"): "equalsString",
+ ("Eq", "bool"): "equalsBoolean",
+ ("Lt", "integral"): "lessThanLong",
+ ("Lt", "fractional"): "lessThanDouble",
+ ("Lt", "string"): "lessThanString",
+ ("LtE", "integral"): "lessThanOrEqualLong",
+ ("LtE", "fractional"): "lessThanOrEqualDouble",
+ ("LtE", "string"): "lessThanOrEqualString",
+ ("Gt", "integral"): "greaterThanLong",
+ ("Gt", "fractional"): "greaterThanDouble",
+ ("Gt", "string"): "greaterThanString",
+ ("GtE", "integral"): "greaterThanOrEqualLong",
+ ("GtE", "fractional"): "greaterThanOrEqualDouble",
+ ("GtE", "string"): "greaterThanOrEqualString",
+}
+
+# Mixed integral / fractional comparison. CPython compares an int and a float
exactly, so the
+# long is NOT widened to double the way the arithmetic `_coerce` does:
`9007199254740993 ==
+# 9007199254740992.0` is False in Python but True after `toDouble`. Direction
matters -- Java
+# evaluates arguments left to right, so the operand that raises has to raise
first -- which is why
+# there is a helper per direction rather than one with the operands swapped.
+_MIXED_COMPARE_HELPERS: Dict[Tuple[str, str, str], str] = {
+ ("Eq", "integral", "fractional"): "equalsLongDouble",
+ ("Eq", "fractional", "integral"): "equalsDoubleLong",
+ ("Lt", "integral", "fractional"): "lessThanLongDouble",
+ ("Lt", "fractional", "integral"): "lessThanDoubleLong",
+ ("LtE", "integral", "fractional"): "lessThanOrEqualLongDouble",
+ ("LtE", "fractional", "integral"): "lessThanOrEqualDoubleLong",
+ ("Gt", "integral", "fractional"): "greaterThanLongDouble",
+ ("Gt", "fractional", "integral"): "greaterThanDoubleLong",
+ ("GtE", "integral", "fractional"): "greaterThanOrEqualLongDouble",
+ ("GtE", "fractional", "integral"): "greaterThanOrEqualDoubleLong",
+}
+
+
+class _JavaValue(NamedTuple):
+ """A lowered Java expression and the category it produces. Boxed, so
``null``
+ is both SQL NULL and Python ``None``."""
+
+ code: str
+ category: str
+
+
+def _java_string_literal(value: str) -> str:
+ """A Java ``UTF8String`` literal. Non-ASCII is ``\\uXXXX`` so the generated
+ source stays ASCII regardless of how the compiler decodes it."""
+ out = []
+ for ch in value:
+ if ch == "\\":
+ out.append("\\\\")
+ elif ch == '"':
+ out.append('\\"')
+ elif ch == "\n":
+ out.append("\\n")
+ elif ch == "\r":
+ out.append("\\r")
+ elif ch == "\t":
+ out.append("\\t")
+ elif " " <= ch <= "~":
+ out.append(ch)
+ else:
+ # Java source is UTF-16, so a character outside the BMP needs both
of its
+ # surrogates written out rather than one escape.
+ try:
+ encoded = ch.encode("utf-16-be")
+ except UnicodeEncodeError:
+ # A lone surrogate is legal in a Python str but has no UTF-16
encoding, so it
+ # cannot be written as a Java escape. Decline like every other
unsupported
+ # construct rather than surfacing a codec error as the reason.
+ raise UnsupportedOperationException(
+ "a string literal containing an unpaired surrogate is not
lowered by the "
+ "java transpiler"
+ )
+ for i in range(0, len(encoded), 2):
+ out.append(f"\\u{encoded[i] << 8 | encoded[i + 1]:04x}")
+ return f'UTF8String.fromString("{"".join(out)}")'
+
+
+def _definitely_returns(body: List[ast.stmt]) -> bool:
+ """Whether every path through ``body`` hits a ``return``.
+
+ Java rejects an unreachable statement outright, so the trailing ``return
null;`` that
+ stands for Python falling off the end of a function can only be emitted
when the body
+ might actually reach it. Verified: a `return` after an if/else whose
branches both
+ return does not compile.
+ """
+ for stmt in body:
+ match stmt:
+ case ast.Return():
+ return True
+ case ast.If(body=if_body, orelse=if_orelse):
+ # An `if` with no `else` always has a path that falls through.
+ if if_orelse and _definitely_returns(if_body) and
_definitely_returns(if_orelse):
+ return True
+ case _:
+ pass
+ return False
+
+
+class JavaTranspiler(AbstractTranspiler):
+ """Transpiles a Python UDF into Java source. See the module docstring."""
+
+ variety = "java"
+
+ def __init__(self) -> None:
+ self._param_categories: Dict[int, str] = {}
+ self._params: List[str] = []
+ self._arg_names: List[str] = []
+ self._locals: Dict[str, str] = {}
+ # Held, not computed: sanitising to Java's character set is not
injective
+ # (``cafe`` + acute and ``caf_`` both become ``caf_``), and two locals
+ # sharing storage would be a silently wrong answer.
+ self._local_java_names: Dict[str, str] = {}
+ self._cast_columns: Dict[Tuple[int, str], Any] = {}
+
+ def _bind(self, params: List[str], param_categories: dict) -> None:
+ self._param_categories = dict(param_categories)
+ self._params = list(params)
+ self._arg_names = [f"_udf_arg_{i}" for i in range(len(params))]
+ self._locals = {}
+ self._local_java_names = {}
+
+ #
---------------------------------------------------------------------------------
+ # Input-type variants
+ #
---------------------------------------------------------------------------------
+
+ def _param_category_combos(
+ self, function_ast: ast.FunctionDef, public_params: List[str]
+ ) -> List[dict]:
+ """Like the Catalyst target's, but ``"numeric"`` split into
integral/fractional.
+
+ Cap is two untyped parameters, not three: 3**n options, and pruning
keeps at
+ most one.
+ """
+ n = len(public_params)
+ if n == 0:
+ return [{}]
+ all_args = _positional_args(function_ast)
+ public_args = all_args[len(all_args) - n :]
+ candidates: List[List[str]] = []
+ untyped = 0
+ for arg in public_args:
+ pinned = _java_annotation_category(arg.annotation)
+ if pinned is None:
+ candidates.append(["integral", "fractional", "string"])
+ untyped += 1
+ else:
+ candidates.append([pinned])
+ if untyped > 2:
+ return [
+ {i: c[0] if len(c) == 1 else fill for i, c in
enumerate(candidates)}
+ for fill in ("integral", "fractional", "string")
+ ]
+ return [{i: choice[i] for i in range(n)} for choice in
itertools.product(*candidates)]
+
+ #
---------------------------------------------------------------------------------
+ # Entry point
+ #
---------------------------------------------------------------------------------
+
+ def _transpile_from_ast(
+ self,
+ src: Optional[str],
+ ast_info: ast.AST,
+ function_ast: ast.FunctionDef,
+ params: List[str],
+ returnType: "DataTypeOrString",
+ param_categories: Optional[dict] = None,
+ ) -> Optional[Column]:
+ if src == "" or ast_info is None:
+ return None
+ self._bind(params, param_categories or {})
+
+ if not isinstance(returnType, DataType):
+ # ``_transpile_func`` parses a string return type before we are
called.
+ raise UnsupportedOperationException("the java transpiler needs a
resolved return type")
+ return_category = _return_category(returnType)
+
+ for index in range(len(params)):
+ if self._param_categories.get(index) not in _CATEGORY_ABI:
+ raise UnsupportedOperationException(
+ f"parameter {params[index]!r} has category "
+ f"{self._param_categories.get(index)!r}, which the java
transpiler "
+ "does not lower"
+ )
+
+ statements = self._lower_body(function_ast.body, return_category)
+ body = "\n".join(statements)
+ return self._build_column(
+ name=function_ast.name,
+ body=body,
+ arg_names=self._arg_names,
+ params=params,
+ return_type=_catalyst_type(return_category),
+ declared_return_type=returnType,
+ )
+
+ #
---------------------------------------------------------------------------------
+ # Statements
+ #
---------------------------------------------------------------------------------
+
+ def _lower_body(self, body: List[ast.stmt], return_category: str) ->
List[str]:
+ """Lower a function body to Java statements, ending with a return on
every path."""
+ statements = self._lower_statements(body, return_category)
+ # Java rejects an unreachable statement (JLS 14.21), so only emit the
+ # fall-off-the-end ``return null`` when a path can actually reach it.
+ if not _definitely_returns(body):
+ statements.append(f"return (({_java_type(return_category)})
null);")
+ return statements
+
+ def _lower_statements(self, body: List[ast.stmt], return_category: str) ->
List[str]:
+ out: List[str] = []
+ for stmt in body:
+ out.extend(self._lower_statement(stmt, return_category))
+ if _definitely_returns([stmt]):
+ break
+ return out
+
+ def _lower_statement(self, stmt: ast.stmt, return_category: str) ->
List[str]:
+ match stmt:
+ case ast.Expr(value=ast.Constant(value=str())) | ast.Pass():
+ return []
+ case ast.Return(value=value):
+ if value is None:
+ return ["return null;"]
+ lowered = self._lower_expr(value)
+ return [f"return {self._coerce(lowered,
return_category).code};"]
+ case ast.Assign(targets=targets, value=value):
+ if len(targets) != 1 or not isinstance(targets[0], ast.Name):
+ raise UnsupportedOperationException(
+ "only assignment to a single plain name is lowered by
the java transpiler"
+ )
+ return self._assign_lowered(targets[0].id,
self._lower_expr(value))
+ case ast.AnnAssign(target=ast.Name(id=target), value=value,
annotation=annotation):
+ if value is None:
+ raise UnsupportedOperationException(
+ "a bare annotation with no value is not lowered"
+ )
+ lowered = self._lower_expr(value)
+ pinned = _java_annotation_category(annotation)
+ if pinned is not None and pinned != lowered.category:
+ # An annotation is not a cast. Converting ``y: float = x``
over a
+ # bigint would lose precision past 2**53, with no fallback
left.
+ raise UnsupportedOperationException(
+ f"the annotation on local {target!r} says {pinned} but
the value is "
+ f"{lowered.category}; a Python annotation does not
convert the value, so "
+ "the java transpiler declines rather than inserting a
conversion"
+ )
+ return self._assign_lowered(target, lowered)
+ case ast.If(test=test, body=if_body, orelse=if_orelse):
+ condition = self._lower_expr(test)
+ if condition.category != "bool":
+ raise UnsupportedOperationException(
+ "an `if` condition must be statically boolean; Python
truthiness "
+ "over numbers, strings and None is not lowered by the
java "
+ "transpiler"
+ )
+ out = [f"if ({_HELPERS}.isTrue({condition.code})) {{"]
+ # A Java local dies with its block; Python's would still be
bound after
+ # the `if`. Restore the outer set so a name first assigned in
a branch
+ # is unknown afterwards. Fail closed: declining costs a
lowering.
+ outer_locals = dict(self._locals)
+ out.extend(_indent(self._lower_statements(if_body,
return_category)))
+ self._locals = dict(outer_locals)
+ if if_orelse:
+ out.append("} else {")
+ out.extend(_indent(self._lower_statements(if_orelse,
return_category)))
+ self._locals = dict(outer_locals)
+ out.append("}")
+ return out
+ case _:
+ raise UnsupportedOperationException(
+ f"{type(stmt).__name__} statements are not lowered by the
java transpiler"
+ )
+
+ def _assign_lowered(self, target: str, lowered: _JavaValue) -> List[str]:
+ if target in self._params:
+ raise UnsupportedOperationException(
+ f"assigning to the parameter {target!r} is not lowered"
+ )
+ if lowered.category == "none":
+ # Ordinary Python, but a bare null has no Java type to declare.
+ raise UnsupportedOperationException(
+ f"assigning a bare None to the local {target!r} is not
lowered: the local has no "
+ "type to declare, since None carries no category"
+ )
+ if target in self._locals and self._locals[target] != lowered.category:
+ raise UnsupportedOperationException(
+ f"local {target!r} is assigned both a {self._locals[target]}
and a "
+ f"{lowered.category} value, which the java transpiler does not
lower"
+ )
+ declaration = "" if target in self._locals else
f"{_java_type(lowered.category)} "
+ self._locals[target] = lowered.category
+ return [f"{declaration}{self._java_local(target)} = {lowered.code};"]
+
+ #
---------------------------------------------------------------------------------
+ # Expressions
+ #
---------------------------------------------------------------------------------
+
+ def _lower_expr(self, node: ast.expr) -> _JavaValue:
+ match node:
+ case ast.Constant(value=None):
+ return _JavaValue("null", "none")
+ case ast.Constant(value=bool() as value):
+ # Before int: `bool` is a subclass of `int`.
+ return _JavaValue("Boolean.valueOf(" + ("true" if value else
"false") + ")", "bool")
+ case ast.Constant(value=int() as value):
+ if not (-(2**63) <= value < 2**63):
+ raise UnsupportedOperationException(
+ f"the integer literal {value} does not fit in a Java
long, which is "
+ "what the java transpiler lowers Python ints to"
+ )
+ return _JavaValue(f"Long.valueOf({value}L)", "integral")
+ case ast.Constant(value=float() as value):
+ if value != value or value in (float("inf"), float("-inf")):
+ raise UnsupportedOperationException("non-finite float
literals are not lowered")
+ return _JavaValue(f"Double.valueOf({value!r}d)", "fractional")
+ case ast.Constant(value=str() as value):
+ return _JavaValue(_java_string_literal(value), "string")
+ case ast.Constant(value=bytes()):
+ raise UnsupportedOperationException(
+ "bytes literals are not lowered by the java transpiler"
+ )
+ case ast.Name(id=name):
+ return self._lower_name(name)
+ case ast.UnaryOp(op=ast.Not(), operand=operand):
+ if not _is_definitely_boolean(operand):
+ raise UnsupportedOperationException(
+ "`not` is only lowered for a statically boolean
operand; Python "
+ "truthiness over other types is not reproduced"
+ )
+ lowered = self._lower_expr(operand)
+ if lowered.category != "bool":
+ # `_is_definitely_boolean` admits `None`; we have no
coalesce back
+ # to Python's `not None is True`, so require a real
boolean.
+ raise UnsupportedOperationException(
+ f"`not` on a {lowered.category} operand is not
lowered; Python's `not "
+ "None` is True where SQL's `NOT NULL` is NULL"
+ )
+ return _JavaValue(f"{_HELPERS}.not({lowered.code})", "bool")
+ case ast.UnaryOp(op=(ast.USub() | ast.UAdd()) as op,
operand=operand):
+ lowered = self._lower_expr(operand)
+ if lowered.category not in ("integral", "fractional"):
+ raise UnsupportedOperationException(
+ "unary `+`/`-` is only lowered for numbers; Python
raises TypeError "
+ f"for a {lowered.category} operand"
+ )
+ if isinstance(op, ast.UAdd):
+ return lowered
+ helper = "negateLong" if lowered.category == "integral" else
"negateDouble"
+ return _JavaValue(f"{_HELPERS}.{helper}({lowered.code})",
lowered.category)
+ case ast.BinOp(left=left, op=op, right=right):
+ return self._lower_binop(left, op, right)
+ case ast.BoolOp():
+ # TODO (SPARK-55209 follow-up): hoist the right operand behind
an `if`.
+ # A helper call cannot short-circuit, so `b != 0 and a // b >
1` would
+ # raise on the rows the guard exists to exclude. Catalyst's
`And` can,
+ # so `catalyst,java` keeps these.
+ raise UnsupportedOperationException(
+ "`and`/`or` are not lowered by the java transpiler: Python
short-circuits "
+ "them and a Java helper call would evaluate both operands,
which turns a "
+ "guard like `b != 0 and a // b > 1` into a divide-by-zero"
+ )
+ case ast.Compare(left=left, ops=ops, comparators=comparators):
+ return self._lower_compare(left, ops, comparators)
+ case ast.IfExp(test=test, body=body, orelse=orelse):
+ condition = self._lower_expr(test)
+ if condition.category != "bool":
+ raise UnsupportedOperationException(
+ "a conditional expression's test must be statically
boolean"
+ )
+ when_true = self._lower_expr(body)
+ when_false = self._lower_expr(orelse)
+ category = self._unify(when_true.category,
when_false.category, "conditional")
+ true_code = self._coerce(when_true, category).code
+ false_code = self._coerce(when_false, category).code
+ return _JavaValue(
+ f"({_HELPERS}.isTrue({condition.code}) ? {true_code} :
{false_code})",
+ category,
+ )
+ case _:
+ raise UnsupportedOperationException(
+ f"{type(node).__name__} expressions are not lowered by the
java transpiler"
+ )
+
+ def _java_local(self, name: str) -> str:
+ """The Java name for a Python local. Numbered so the mapping cannot
collide."""
+ existing = self._local_java_names.get(name)
+ if existing is not None:
+ return existing
+ cleaned = "".join(
+ ch if (ch.isalnum() and ch.isascii()) or ch == "_" else "_" for ch
in name
+ )
+ assigned = f"_udf_local_{len(self._local_java_names)}_{cleaned}"
+ self._local_java_names[name] = assigned
+ return assigned
+
+ def _lower_name(self, name: str) -> _JavaValue:
+ if name in self._locals:
+ return _JavaValue(self._java_local(name), self._locals[name])
+ if name in self._params:
+ index = self._params.index(name)
+ return _JavaValue(self._arg_names[index],
self._param_categories[index])
+ # Free variable. SPARK-55207 is the shared fix; until then neither
target reads them.
+ raise UnsupportedOperationException(
+ f"{name!r} is neither a parameter nor a local assigned in the
body, so the "
+ "java transpiler cannot lower it"
+ )
+
+ def _lower_binop(self, left: ast.expr, op: ast.operator, right: ast.expr)
-> _JavaValue:
+ op_name = type(op).__name__
+ lowered_left = self._lower_expr(left)
+ lowered_right = self._lower_expr(right)
+
+ # `str * int`: refuse a fractional count rather than truncate the way
Catalyst does.
+ if op_name == "Mult" and {lowered_left.category,
lowered_right.category} == {
+ "string",
+ "integral",
+ }:
+ text, count = (
+ (lowered_left, lowered_right)
+ if lowered_left.category == "string"
+ else (lowered_right, lowered_left)
+ )
+ return _JavaValue(f"{_HELPERS}.repeat({text.code}, {count.code})",
"string")
+
+ category = self._unify(lowered_left.category, lowered_right.category,
op_name)
+ if category == "string" and op_name != "Add":
+ raise UnsupportedOperationException(
+ f"`{op_name}` is not lowered for text (Python raises
TypeError)"
+ )
+ if category == "bool":
+ # `True + 1` is legal Python; ANSI Spark rejects it. Both targets
refuse.
+ raise UnsupportedOperationException(f"`{op_name}` is not lowered
for booleans")
+ helper = _BINARY_HELPERS.get((op_name, category))
+ if helper is None:
+ raise UnsupportedOperationException(
+ f"`{op_name}` on {category} operands is not lowered by the
java transpiler"
+ )
+ left_code = self._coerce(lowered_left, category).code
+ right_code = self._coerce(lowered_right, category).code
+ result_category = "fractional" if op_name == "Div" else category
+ return _JavaValue(f"{_HELPERS}.{helper}({left_code}, {right_code})",
result_category)
+
+ def _lower_compare(
+ self, left: ast.expr, ops: List[ast.cmpop], comparators: List[ast.expr]
+ ) -> _JavaValue:
+ if len(ops) != 1:
+ raise UnsupportedOperationException(
+ "chained comparisons are not lowered by the java transpiler"
+ )
+ op = ops[0]
+ right = comparators[0]
+
+ if isinstance(op, (ast.Is, ast.IsNot)):
+ if not isinstance(right, ast.Constant) or right.value is not None:
+ raise UnsupportedOperationException("`is` is only lowered
against None")
+ lowered = self._lower_expr(left)
+ test = "!=" if isinstance(op, ast.IsNot) else "=="
+ return _JavaValue(f"Boolean.valueOf({lowered.code} {test} null)",
"bool")
+
+ # Either side: `None == x` is as much a None comparison as `x == None`.
+ # Catalyst lowers this specially and is tried first; `is None` is the
idiom.
+ if any(
+ isinstance(operand, ast.Constant) and operand.value is None for
operand in (left, right)
+ ):
+ raise UnsupportedOperationException(
+ "`==`/`!=` against None are not lowered by the java
transpiler; use "
+ "`is None` / `is not None`"
+ )
+
+ lowered_left = self._lower_expr(left)
+ lowered_right = self._lower_expr(right)
+ left_cat, right_cat = lowered_left.category, lowered_right.category
+ op_key = "Eq" if isinstance(op, (ast.Eq, ast.NotEq)) else
_ORDER_OPS.get(type(op))
+ if op_key is None:
+ raise UnsupportedOperationException(
+ f"{type(op).__name__} comparisons are not lowered by the java
transpiler"
+ )
+
+ # Mixed integral / fractional: compare exactly rather than widening
the long to a
+ # double (see `_MIXED_COMPARE_HELPERS`). The operands stay in their
own types, so no
+ # `_coerce` runs and the operand that raises still raises first.
+ mixed = _MIXED_COMPARE_HELPERS.get((op_key, left_cat, right_cat))
+ if mixed is not None:
+ call = f"{_HELPERS}.{mixed}({lowered_left.code},
{lowered_right.code})"
+ if isinstance(op, ast.NotEq):
+ call = f"{_HELPERS}.not({call})"
+ return _JavaValue(call, "bool")
+
+ category = self._unify(left_cat, right_cat, "comparison")
+ left_code = self._coerce(lowered_left, category).code
+ right_code = self._coerce(lowered_right, category).code
+
+ # Own helper per operator, not swapped `<`: Java evaluates args left to
+ # right, so `x // 0 > x * x` would raise the multiply first.
+ if isinstance(op, (ast.Eq, ast.NotEq)):
+ helper = _COMPARE_HELPERS.get(("Eq", category))
+ if helper is None:
+ sym = "==" if isinstance(op, ast.Eq) else "!="
+ raise UnsupportedOperationException(
+ f"`{sym}` on {category} operands is not lowered"
+ )
+ call = f"{_HELPERS}.{helper}({left_code}, {right_code})"
+ if isinstance(op, ast.NotEq):
+ call = f"{_HELPERS}.not({call})"
+ return _JavaValue(call, "bool")
+ return self._ordered(category, op_key, left_code, right_code)
+
+ def _ordered(self, category: str, op_name: str, left: str, right: str) ->
_JavaValue:
+ helper = _COMPARE_HELPERS.get((op_name, category))
+ if helper is None:
+ raise UnsupportedOperationException(
+ f"ordering comparisons on {category} operands are not lowered
by the "
+ "java transpiler"
+ )
+ return _JavaValue(f"{_HELPERS}.{helper}({left}, {right})", "bool")
+
+ #
---------------------------------------------------------------------------------
+ # Categories
+ #
---------------------------------------------------------------------------------
+
+ def _unify(self, left: str, right: str, what: str) -> str:
+ """The category an operation over ``left`` and ``right`` produces.
+
+ ``none`` unifies with anything. Integral promotes to fractional.
Anything
+ else mixed is a Python ``TypeError``, so it is not lowered.
+ """
+ if left == right:
+ return left
+ if left == "none":
+ return right
+ if right == "none":
+ return left
+ if {left, right} == {"integral", "fractional"}:
+ return "fractional"
+ raise UnsupportedOperationException(
+ f"{what} mixes {left} and {right} operands, which the java
transpiler does not lower"
+ )
+
+ def _coerce(self, value: _JavaValue, category: str) -> _JavaValue:
+ """Bring ``value`` into ``category``, or refuse."""
+ if value.category == category:
+ return value
+ if value.category == "none":
+ # Keep the code. Replacing a "none" value with a bare `null`
dropped
+ # `None if a // b > 0 else None`'s divide, returning NULL where
+ # CPython raises.
+ return _JavaValue(f"(({_java_type(category)}) {value.code})",
category)
+ if value.category == "integral" and category == "fractional":
+ return _JavaValue(f"{_HELPERS}.toDouble({value.code})",
"fractional")
+ raise UnsupportedOperationException(
+ f"a {value.category} value cannot be used where a {category} one
is needed; "
+ "the java transpiler falls back rather than converting"
+ )
+
+ #
---------------------------------------------------------------------------------
+ # Handing the source to the JVM
+ #
---------------------------------------------------------------------------------
+
+ def _build_column(
+ self,
+ name: str,
+ body: str,
+ arg_names: List[str],
+ params: List[str],
+ return_type: DataType,
+ declared_return_type: DataType,
+ ) -> Column:
+ from pyspark.sql.classic.column import Column as ClassicColumn
+ from pyspark.sql.classic.column import _to_java_column
+ from pyspark.sql.utils import get_active_spark_context
+
+ sc = get_active_spark_context()
+ assert sc._jvm is not None
+
+ # Widen into the category type (int/smallint/bigint all arrive as
Long).
+ # Memoized: this runs once per option and a Column is immutable.
+ children = []
+ input_type_json = []
+ for index in range(len(params)):
+ category = self._param_categories[index]
+ target = _catalyst_type(category)
+ cached = self._cast_columns.get((index, category))
+ if cached is None:
+ cached =
_to_java_column(col(f"_udf_param_{index}").cast(target))
+ self._cast_columns[(index, category)] = cached
+ children.append(cached)
+ input_type_json.append(target.json())
+
+ jcol = getattr(
+ sc._jvm,
+ "org.apache.spark.sql.execution.python.TranspiledJavaUDFBuilder",
+ ).create(
+ name,
+ body,
+ arg_names,
+ children,
+ input_type_json,
+ return_type.json(),
+ )
+ result = ClassicColumn(jcol)
+ if return_type != declared_return_type:
Review Comment:
Fixed in 8d3c694b486: added end-to-end cases for int-, smallint- and
float-declared UDFs and an integral body under a declared double, asserting the
schema and values, plus a case where the result exceeds the int range and fails
under ANSI with CAST_OVERFLOW. Removing the cast makes these fail.
---
<sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of
@holdenk.</sub>
<!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk
-->
--
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]