spark-test commented on code in PR #59730:
URL: https://github.com/apache/spark/pull/59730#discussion_r4510774151
##########
python/pyspark/sql/transpile.py:
##########
@@ -132,26 +275,211 @@
from pyspark.sql import SparkSession
from pyspark.sql._typing import DataTypeOrString
-# Categories that represent numeric (non-string) scalar types.
-_NUMERIC_CATS = frozenset(("numeric", "integer", "float"))
+# Input-type categories. "numeric" spans every numeric column type that has a
+# faithful Python counterpart -- Byte/Short/Integer/Long/DoubleType, so neither
+# DecimalType nor FloatType (see the module docstring); "integral" and
+# "fractional" narrow it for the lowerings that are only exact on one kind of
+# number, and "integral32" narrows "integral" further to the widths whose
values
+# are all exactly representable as a double. The JVM side of this vocabulary
+# lives in ResolveTranspiledPythonUDFOptions.
+_INTEGRAL_CATEGORIES = frozenset({"integral", "integral32"})
+_NUMERIC_CATEGORIES = frozenset({"numeric", "fractional"}) |
_INTEGRAL_CATEGORIES
+# Categories a lowering may tighten (see ``CatalystTranspiler._narrow``), in
+# increasing narrowness, so a later entry matches strictly fewer column types
than
+# an earlier one. Requirements from different lowerings in one option are
+# conjunctive -- every one of them has to hold for the option to be exact -- so
+# when two apply to the same parameter the narrowest wins.
+#
+# Only the numeric categories spanning more than one kind of number are in
here:
+# narrowing "fractional" to an integral category would change the assumption
rather
+# than tighten it, and the non-numeric categories have nothing to narrow to.
+_NARROWING_ORDER = ("numeric", "integral", "integral32")
+_NARROWABLE_CATEGORIES = frozenset(_NARROWING_ORDER)
+# Python builtins the transpiler can lower. Only reached after the name is
proven
+# to still refer to the builtin (see ``_resolvable_builtins``).
+_SUPPORTED_BUILTINS = frozenset({"abs", "min", "max", "round"})
+# `x ** k` expands to k-1 multiplications, so cap k to keep plans small.
Raising
+# the cap buys little: past it, all but the smallest bases overflow LongType.
+_MAX_POW_EXPANSION = 8
+# An int literal past this is conservatively treated as too wide for
IntegerType,
+# so Spark would promote the expression to LongType and the int32 exactness
+# argument for `/` stops holding. (-2**31 does fit; we don't bother.)
+_INT32_MAX = 2**31 - 1
+# Shifts widen their operand to a long, so this is the count at which Python
has
+# shifted every bit out -- and the point at which Spark's masked shift stops
+# agreeing with it.
+_LONG_BITS = 64
+
+
+def _promoting_if_numeric(
+ op: str, categories: List[Optional[str]], plain: Callable[[], Column],
*cols: Column
+) -> Column:
+ """``_promoting(op, ...)`` when every operand is a number, else
``plain()``.
+
+ The gate is on *numeric* rather than *integral* deliberately, and getting
that wrong is worth
+ a note. An unannotated parameter's category is plain ``"numeric"`` -- it
could be an int
+ column or a double one, and only the JVM finds out which. Gating on
``_INTEGRAL_CATEGORIES``
+ therefore refuses promotion for exactly the common case, `udf(lambda x, y:
x + y)` over two
+ int columns, which is the shape this whole exercise is about. It has to be
the coarse
+ category here and the concrete type over there.
+
+ Nothing is lost by handing a double to the promoting operator:
``PythonNumericPromotion``
+ declines to widen a fractional type (IEEE arithmetic saturates to
infinity, which is what
+ Python does too), and aligns the operands so the replacement still
resolves.
+ """
+ if all(_is_numeric_cat(c) for c in categories):
+ return _promoting(op, *cols)
+ return plain()
+
+
+def _promoting(op: str, *cols: Column) -> Column:
+ """Emit the operand-widening version of ``op``.
+
+ Python integers have no width, so `x * 100` on a tinyint column is fine
there and
+ ARITHMETIC_OVERFLOW here -- `Multiply` keeps its operands' type. The JVM
side widens the
+ operands far enough that the worst case the *column types* allow cannot
overflow; see
+ ``PythonNumericPromotion``. It has to happen over there rather than in
this file, because
+ only the analyzer knows the concrete column widths -- we only ever see a
category, and
+ "integral" spans tinyint through bigint.
+
+ Reached through ``InternalFunction`` rather than ``call_function``: these
are registered as
+ internal expressions, so they are invisible to ``SHOW FUNCTIONS`` and to
SQL. That is the
+ right side of the line -- for a SQL user `a + b` overflowing is the
documented ANSI contract,
+ and a public registration would additionally owe an
``@ExpressionDescription`` and a row in
+ ``sql-expression-schema.md``, for a function nobody should call by name.
+ """
+ return
InternalFunction._invoke_internal_function_over_columns(f"python_promoting_{op}",
*cols)
-def _is_numeric_cat(cat: str) -> bool:
- """True for any numeric sub-category (``"numeric"``, ``"integer"``,
``"float"``)."""
- return cat in _NUMERIC_CATS
+def _raise_on_null_operand(op_repr: str, result: Column, *cols: Column) ->
Column:
+ """``result``, but raising where CPython gets a ``None`` operand.
+ Spark's arithmetic propagates NULL (``x + 1`` on NULL is NULL) where Python
+ raises ``TypeError`` (``None + 1``), and a row that should have failed
+ coming back silently missing is worse than any wrong answer, so every
+ lowered operator guards the way the comparisons and ``min`` / ``max`` do:
+ NULL in, ``raise_error`` out. A caller that already proved non-null (``if x
+ is not None: return x + 1``) takes the otherwise branch and never trips it.
+ """
+ err = lit(
+ f"Python UDF transpiler: cannot apply `{op_repr}` to NULL; "
+ "Python would raise TypeError here. Add an `is not None` guard or "
+ "filter NULLs upstream."
+ )
+ any_null = cols[0].isNull()
Review Comment:
**Blocking (P1):** This guard reads each operand twice, once in `isNull`
here and once inside `result`. `when` and `isNull` keep references to the
operand's existing ColumnNode, and ColumnNodeToExpressionConverter turns each
reference into its own Catalyst subtree with no memoization, inside
`UserDefinedPythonFunction.builder` on every call. When an operand is itself a
guarded lowering, every level doubles it. With transpilation and ANSI on,
`udf(lambda a1, ..., a20: a1 + ... + a20, LongType())` puts 2^18 copies of `a1
+ a2` into one option, and four rounds of `(h * 31 + v) % P` put about 160,000
copies of `a`, since `_python_mod` also reads its dividend five times. On the
base branch `+ - *` were unguarded and `%` read its dividend once, so both
options were linear in the body.
Every analyzer and optimizer pass walks the expanded options, so analysis
can stall or run the driver out of memory. CaseWhen subexpression elimination
cannot share the copy in the test with the copy in the else value, so per-row
work multiplies as well. Even one level costs something: because the guard
reads the parameter a second time, ConvertToCatalyst owes a compound argument a
single evaluation, so `plus_one(v * 2)` in an aggregate, a join condition or a
command now keeps the Python UDF where the base branch transpiled it.
**Recommended change:** Raise on a NULL operand with a single read of each
operand, and move the lowerings that need an operand more than once into
internal JVM expressions that evaluate each child once.
**Why this works:** Some lowerings are NULL exactly when an operand is NULL
under ANSI: +, -, *, /, unary minus and plus, ~, abs, round, the bitwise
operators, repeat and string concatenation. For these, replace the CASE WHEN
guard with `coalesce(op(a, b), raise_error(...))`, which references each
operand once and raises for exactly the same rows. Keep an explicit null test
only where the result can be non-NULL for a NULL input (least and greatest for
min and max, and the literal result of `x ** 0`), applied to the operand once.
Implement Python's %, //, constant-exponent ** and the two shifts as internal
binary expressions registered beside the existing promoting expressions. Their
sign, floor, widening and count corrections then read each child once inside
the expression, instead of re-referencing operand Columns. Update the
divergence ledger's evaluation-count entry to match.
**Scope:** Rework operand references in the Python lowerings and add
internal JVM expressions for the corrections that need an operand more than
once.
**Compatibility:** Results and raises for every input the current lowering
handles stay the same; only the expression shape and the evaluation count
change.
**Risks:** The new internal expressions re-implement Python's %, //, ** and
shift semantics on the JVM and must match the current lowering exactly across
signs, zero divisors, width boundaries, shift counts past the width, NaN and
infinities. When one operand is NULL and the other raises, the reported error
can differ from today's; the divergence ledger already accepts differences in
which exception is raised.
**Constraints:** Transpilation stays ANSI-only, and the coalesce form relies
on ANSI arithmetic raising on overflow and divide-by-zero rather than returning
NULL. A clamp inside a lowering, such as the string-repeat count, must keep a
NULL operand NULL, or the coalesce form stops raising for it.
**Exclusions:**
- Comparison and len lowerings keep their current NULL guards, because their
boolean or integer results rarely feed another guarded operator and so do not
compound in practice.
**Success:** Option expression size grows linearly with the UDF body for
nested +, -, *, /, %, //, ** and shift chains. Each parameter is read once per
occurrence in the body, so a transpiled `x + 1` called on a compound argument
inside an aggregate or a join condition runs natively again, as on the base
branch. A NULL operand still raises for every lowered operator, matching
CPython's TypeError. Results for non-NULL inputs are unchanged.
**Verification:**
- **Regression:** A left-associated sum over twenty untyped parameters, a
chain of true divisions and a four-round `(h * 31 + v) % P` body produce
options whose expression size grows linearly with the body, analyze promptly,
and return CPython's results natively.
- **Regression:** A transpiled `x + 1` called with a compound argument
inside an aggregate expression and inside a join condition executes with no
Python UDF in the executed plan.
- **Behavior:** Every lowered operator raises the transpiler's NULL error
for a NULL operand in either position, rather than returning NULL.
- **Compatibility:** The new internal expressions reproduce CPython's %, //,
** and shift results across signs, zero divisors, width boundaries, shift
counts past the width, NaN and infinities, matching the current differential
coverage.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveTranspiledPythonUDFOptions.scala:
##########
@@ -117,3 +177,91 @@ object ResolveTranspiledPythonUDFOptions extends
Rule[LogicalPlan] {
}
}
}
+
+/**
+ * Drops any transpiled option that analysis left unresolved, so the call
falls back to interpreted
+ * Python instead of failing the query.
+ *
+ * An option is a child of [[TranspiledPythonUDF]], so one that is still
unresolved when analysis
+ * finishes reaches `CheckAnalysis`, which reports on an expression the user
never wrote. For the
+ * common shape that is a type-check failure: an option of `cast(binary as
bigint)` is measured as
+ * [[DATATYPE_MISMATCH.CAST_WITHOUT_SUGGESTION]], "cannot cast BINARY to
BIGINT", naming a cast the
+ * transpiler invented. The honest answer is the one a category miss already
gets: run the Python.
+ *
+ * Matching categories does not rule any of this out -- the transpiler picks a
lowering per operator
+ * rather than per exact type, so `cast(binary as bigint)` matches "binary"
and never resolves.
+ *
+ * Separate from [[ResolveTranspiledPythonUDFOptions]], and in a batch after
the Resolution batch,
+ * because inside that batch `!resolved` does not mean unresolvable. Every
option starts unresolved
+ * by design: its `_udf_param_N` references carry no type until
ResolveTranspiledPythonUDFOptions
+ * reads one off each bound argument, and the node staying unresolved is what
brings the analyzer
+ * back to coerce the body. Dropping on `!resolved` from inside the batch
would throw away every
+ * option that reads a parameter and turn transpilation off without saying so.
Once the batch is at
+ * a fixed point, nothing is going to resolve one.
+ *
+ * Dropping an option resolves the UDF, but the Resolution batch has already
converged, so whatever
+ * was waiting on the UDF stays unresolved on its own: the enclosing
`UnresolvedAlias` of
+ * `SELECT udf(a)`, or a parent held by name such as the `r` of `SELECT r + 1
FROM (SELECT udf(a)
+ * AS r ...)`. `CheckAnalysis` would then report the fall-back itself as an
error, so after
+ * dropping, this rule re-runs the resolution rules that finish those parents
off -- and only on
+ * plans it changed, so queries without a dropped option never pay for this.
The re-run is a single
+ * pass of each rule in Resolution-batch order; each walks bottom-up, which
covers the parents of
+ * every dropped UDF at any nesting depth. `resolveAggregateFunctions` comes
along because
+ * `resolveReferences` wraps ORDER BY/HAVING references over an Aggregate in
`TempResolvedColumn`,
+ * and only `ResolveAggregateFunctions` marks the invalid ones `hasTried` for
the later
+ * `RemoveTempResolvedColumn` batch to turn back into an unresolved attribute
-- without it, an
+ * invalid ORDER BY in the same query as a dropped option would be unwrapped
to a resolved
+ * attribute the Aggregate never provides, and reported as
`MISSING_ATTRIBUTES` instead of the
+ * `UNRESOLVED_COLUMN` the same query gets without a UDF. The batch must
therefore run before
+ * "Remove TempResolvedColumn", so that batch can still clean up behind this
re-run. A shape
+ * needing a resolution rule not listed here fails `CheckAnalysis` as it did
before the drop rule
+ * existed, rather than analyzing wrongly.
+ *
+ * @param resolveReferences the Analyzer's `ResolveReferences`, shared with
the Resolution batch.
+ * @param resolveAliases the Analyzer's `ResolveAliases`.
+ * @param resolveAggregateFunctions the Analyzer's `ResolveAggregateFunctions`.
+ */
+class DropUnresolvedTranspiledPythonUDFOptions(
+ resolveReferences: Rule[LogicalPlan],
+ resolveAliases: Rule[LogicalPlan],
+ resolveAggregateFunctions: Rule[LogicalPlan]) extends Rule[LogicalPlan] {
+ def apply(plan: LogicalPlan): LogicalPlan = {
+ val dropped =
+ if (!plan.containsPattern(TRANSPILED_PYTHON_UDF)) {
+ plan
+ } else {
+
plan.resolveOperatorsWithPruning(_.containsPattern(TRANSPILED_PYTHON_UDF)) {
+ case op if op.containsPattern(TRANSPILED_PYTHON_UDF) =>
+
op.transformExpressionsUpWithPruning(_.containsPattern(TRANSPILED_PYTHON_UDF)) {
+ case t: TranspiledPythonUDF if t.arguments.forall(_.resolved) &&
+ (t.optionInputCategories.nonEmpty ||
!t.transpiledOptions.forall(_.resolved)) =>
+ val typed =
ResolveTranspiledPythonUDFOptions.pruneByCategoryAndTypeParameters(t)
+ val (kept, dropped) =
typed.transpiledOptions.partition(_.resolved)
+ if (dropped.nonEmpty) {
+ val first = Utils.redact(
+ SQLConf.get.stringRedactionPattern,
dropped.head.simpleString(maxFields = 100))
+ // Only claim "falls back to interpreted Python" when every
option was
+ // dropped; with survivors, ConvertToCatalyst still picks
the first kept one.
+ if (kept.isEmpty) {
+ logWarning(log"Dropping ${MDC(LogKeys.COUNT,
dropped.length)} transpiled " +
+ log"option(s) for Python UDF
${MDC(LogKeys.FUNCTION_NAME, t.name)}; " +
+ log"the call falls back to interpreted Python. First
dropped: " +
+ log"${MDC(LogKeys.EXPR, first)}")
+ } else {
+ logWarning(log"Dropping ${MDC(LogKeys.COUNT,
dropped.length)} transpiled " +
+ log"option(s) for Python UDF
${MDC(LogKeys.FUNCTION_NAME, t.name)}; " +
+ log"${MDC(LogKeys.COUNT, kept.length)} option(s) remain.
First dropped: " +
+ log"${MDC(LogKeys.EXPR, first)}")
+ }
+ }
+ typed.copy(transpiledOptions = kept)
+ }
+ }
+ }
+ if (dropped eq plan) {
+ plan
+ } else {
+ resolveAggregateFunctions(resolveAliases(resolveReferences(dropped)))
Review Comment:
**Non-blocking (P2):** This re-run finishes bare, aliased and by-name calls,
but a parent that waits on the call through any other Resolution-batch rule
stays unresolved. Those rules skip nodes whose children are unresolved, and the
transpiled call stays unresolved until its option is dropped here, after the
batch has converged. ResolveFunctions skips such nodes, and so do the ANSI
ImplicitTypeCasts and PromoteStrings rules. Column `+`, comparisons and the
`F.*` wrappers all build UnresolvedFunction nodes, and
ResolveLateralColumnAliasReference has to run directly after ResolveReferences.
So with an option that never resolves, each of these still fails
CheckAnalysis instead of falling back: `SELECT udf(b) + 1` with a bigint
result, where Add(bigint, int) is never coerced; `df.select(udf('b') + 1)`,
`F.max(udf('b'))` and `df.filter(udf('b') > 0)`; `SELECT udf(b) AS r, r + 1L AS
s`, which leaves a LateralColumnAliasReference that CheckAnalysis reports as
INTERNAL_ERROR; and `SELECT * FROM (SELECT udf(b) FROM t)`. The description's
`SELECT r + 1 FROM (SELECT udf(a) AS r ...)` is one of them whenever the UDF
returns bigint, which is why the new test uses `Literal(1L)`. The error can now
name the user's own expression rather than the cast the transpiler invented.
**Recommended change:** After dropping options, run the Resolution batch to
a fixed point on the changed plan, instead of one pass of three rules.
**Why this works:** Give the drop rule the analyzer's Resolution batch,
built from the same rule list. Only when an option was dropped, execute that
batch to a fixed point on the resulting plan, before Remove TempResolvedColumn
runs. ResolveFunctions, type coercion, ResolveLateralColumnAliasReference, star
expansion and repeated ResolveReferences and ResolveAliases passes then finish
every parent that waited on the call, in dependency order.
**Scope:** Replace the drop rule's hand-picked re-run with a fixed-point
re-execution of the Resolution batch on changed plans.
**Risks:** Analysis runs the Resolution batch once more for plans with a
dropped option, a cost paid only on that path.
**Constraints:** The re-run must happen before Remove TempResolvedColumn, so
an invalid ORDER BY in the same query still reports UNRESOLVED_COLUMN.
**Exclusions:**
- This change does not enumerate or remove the built-in transpiler shapes
that produce options which never resolve; it makes the fallback complete for
any that do.
**Success:** A query whose transpiled call has an option that never resolves
analyzes and falls back to interpreted Python when the call sits under a Column
operator, an F.* or SQL function, a comparison, an operator needing type
coercion, a lateral column alias, or a star over an unaliased call. An invalid
ORDER BY in the same query as a dropped option still fails with
UNRESOLVED_COLUMN. Plans without a dropped option are analyzed exactly as
before.
**Verification:**
- **Regression:** With an option that never resolves, `SELECT udf(b) + 1`,
`df.select(udf('b') + 1)`, `F.max(udf('b'))`, `df.filter(udf('b') > 0)`,
`SELECT udf(b) AS r, r + 1 AS s` and `SELECT * FROM (SELECT udf(b) FROM t)` all
analyze and return the interpreted UDF's results.
- **Compatibility:** An invalid ORDER BY in the same query as a dropped
option still fails with UNRESOLVED_COLUMN, and the bare, aliased and by-name
cases keep falling back.
- **Behavior:** A plan with no dropped option leaves the drop batch
unchanged and runs no additional resolution.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveTranspiledPythonUDFOptions.scala:
##########
@@ -105,10 +158,17 @@ object ResolveTranspiledPythonUDFOptions extends
Rule[LogicalPlan] {
false
} else {
categories.zip(argTypes).forall {
- case ("integer", dt) => dt.isInstanceOf[IntegralType]
- case ("float", dt) =>
- dt.isInstanceOf[FractionalType] && !dt.isInstanceOf[DecimalType]
- case ("numeric", dt) => dt.isInstanceOf[NumericType] &&
!dt.isInstanceOf[DecimalType]
+ // Allow-lists rather than "NumericType minus the exclusions": the
numeric
+ // categories admit exactly the column types with a faithful Python
+ // counterpart, and spelling that out means a numeric type added to
Spark
+ // later falls back until someone deliberately admits it, instead of
being
+ // silently swept in by an `isInstanceOf` and diverging.
+ case ("numeric", ByteType | ShortType | IntegerType | LongType |
DoubleType) => true
Review Comment:
**Non-blocking (P2):** Excluding FloatType here also drops float bodies the
base branch lowered exactly, through its `numeric` and `float` categories.
There, `-x`, `x > 0`, `x > 0.5`, `if x:`, `x if x is not None else 0.0`, `x +
4` and `x * 2.0` on a float column ran natively and matched CPython for
non-NULL, non-NaN values, because ANSI coercion widens a float paired with an
integral or double operand to double, which is what CPython computes. Only
arithmetic between two float operands stays in float32, which is the divergence
the description and the module docstring describe. Now every UDF over a float
column runs as interpreted Python; the module docstring itself calls this a
throughput cost.
One catch for a narrower exclusion: `python_promoting_add`, `_subtract` and
`_multiply` bypass coercion, and `PythonNumericPromotion.widestOf` aligns an
integral operand with a FloatType one in FloatType, so admitting `x + 4` as the
code stands would round to 24 bits.
**Recommended change:** Admit FloatType columns, through a dedicated
category label, for options whose lowering is exact on a float32 value, and
make the promoting arithmetic align an integral operand with a FloatType one in
double, as ANSI coercion does.
**Why this works:** Under ANSI, implicit casts widen a FloatType value
paired with an integral or double operand to double, which is exact and matches
CPython's double arithmetic and comparisons; only an operator whose two
operands are both FloatType stays in float32 and rounds to 24 bits. Report a
numeric category that also matches FloatType for bodies in which no +, -, * or
% takes two operands that can both evaluate to a FloatType value, and add that
label to the allow-list in ResolveTranspiledPythonUDFOptions. Comparisons,
negation, abs, conditional branching, pass-through, truthiness and arithmetic
against an integral or double operand then lower natively for FloatType
columns. In PythonNumericPromotion, make the operand alignment return
DoubleType for an integral-and-FloatType pair, so `python_promoting_add`,
`python_promoting_subtract` and `python_promoting_multiply` evaluate `x + 4` on
a float column in double, as a plain ANSI Add would; today `widestOf` aligns
that pair i
n FloatType.
**Scope:** Carry per-body float32 exactness as a category label that admits
FloatType, and align an integral and a float operand in double.
**Risks:** The per-body rule has to treat every operand that can evaluate to
a FloatType value as one, including a parameter's negation or abs and a branch
that yields one; missing one admits float32 arithmetic and a wrong result. The
alignment change applies to every integral-and-FloatType pair the promoting
expressions see, which only a category that admits FloatType makes reachable.
Until the exact int-versus-float comparison lands, a float column compared with
a bigint beyond 2^53 rounds the bigint side, as it did on the base branch.
**Exclusions:**
- Arithmetic between two FloatType operands stays interpreted, because
making it exact needs double-precision evaluation that the current lowerings do
not provide.
**Success:** `-x`, `x if x is not None else 0.0`, `if x:`, `x > 0`, `x >
0.5`, `x + 4` and `x * 2.0` over a FloatType column run natively with CPython's
results. `x + y`, `x * y` and `x % y` over two FloatType columns still fall
back to interpreted Python.
**Verification:**
- **Regression:** Negation, conditional pass-through, truthiness,
comparisons against an int literal, an int column and a double literal, and
arithmetic against an int literal or a double operand over a FloatType column
execute natively and match CPython, including for NULL, NaN and infinite values.
- **Behavior:** Arithmetic between two FloatType columns still runs as
interpreted Python with CPython's results.
- **Compatibility:** A promoting add, subtract or multiply over a float and
an int operand resolves to double arithmetic, as plain ANSI coercion does,
while integral-only and double pairs align as today.
##########
python/pyspark/sql/transpile.py:
##########
@@ -1138,46 +2233,90 @@ def _annotation_category(annotation: Optional[ast.AST])
-> Optional[str]:
if name == "str":
return "string"
if name == "int":
- return "integer"
+ return "integral" if refined else "numeric"
if name == "float":
- return "float"
+ return "fractional" if refined else "numeric"
if name == "bool":
return "bool"
if name == "bytes":
return "binary"
return None
+def _body_needs_numeric_refinement(function_ast: ast.FunctionDef) -> bool:
+ """True when the body uses an operator whose exact lowering depends on the
+ *kind* of number, so the numeric variant has to split into integral and
+ fractional ones.
+
+ Every other body keeps the single ``"numeric"`` variant it always emitted,
+ which is what makes the split free for existing UDFs -- no extra plan
options
+ and no change in which columns match. Comparisons are refined too, so an
+ integral comparison can omit the NaN guard.
+ """
+ refined_ops = (
+ ast.Div,
+ ast.FloorDiv,
+ ast.Pow,
+ ast.BitAnd,
+ ast.BitOr,
+ ast.BitXor,
+ ast.LShift,
+ ast.RShift,
+ ast.Invert,
+ )
+ comparison_ops = (ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE)
+ for node in ast.walk(function_ast):
+ if isinstance(node, (ast.BinOp, ast.AugAssign)) and
isinstance(node.op, refined_ops):
+ return True
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, refined_ops):
+ return True
+ if isinstance(node, ast.Compare) and any(isinstance(op,
comparison_ops) for op in node.ops):
+ return True
+ # `min`/`max`/`round` are integral-only; `abs` works on either kind
and so
+ # needs no split.
+ if (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id in ("min", "max", "round")
+ ):
+ return True
+ return False
+
+
def _param_category_combos(function_ast: ast.FunctionDef, public_params:
List[str]) -> List[dict]:
"""Per-variant maps ``{public_param_index -> category}``.
- A typed param (``def f(a: str, b: int)``) is pinned to its category
- (``"integer"``/``"float"``/``"string"``/``"bool"``/``"binary"``); an
- untyped param is tried as ``"integer"``, ``"float"``, and ``"string"``
- separately so the JVM can select the variant that matches the bound column
- type and apply the right NaN semantics. To cap plan growth, when more than
- three params are untyped we collapse the untyped ones to one variant per
- base category (encourage typing inputs to keep the matrix small) while
+ A typed param (``def f(a: str, b: int)``) is pinned to its category; an
+ untyped param is tried as every category its operators could need. To cap
plan
+ growth we collapse the untyped ones to a single uniform variant per
category
+ once too many are untyped (type your inputs to keep the matrix small),
while
keeping every typed param pinned.
+
+ Bodies needing the integral/fractional split try three categories per
untyped
+ param instead of two, so the collapse kicks in one param sooner to keep
3**n
+ in check.
"""
+ refined = _body_needs_numeric_refinement(function_ast)
+ kinds = ["integral", "fractional", "string"] if refined else ["numeric",
"string"]
+ max_untyped = 2 if refined else 3
Review Comment:
**Non-blocking (P2):** With `max_untyped = 2` for refined bodies, and any
comparison making a body refined, three untyped parameters now collapse to
all-integral, all-fractional and all-string variants. `udf(lambda a, b, c: a +
b > c, BooleanType())` on (int, double, int) and `udf(lambda s, n, m: s * n if
n > m else s, StringType())` on (string, int, int) match none of them and run
as interpreted Python, while the base branch emitted all 27 combinations and
lowered both natively. Comparisons are refined only so integral pairs can skip
the NaN guard, which doesn't need a smaller cap. Keeping the cap at three for
refined bodies restores that coverage at the plan size the base branch already
had.
**Verification:**
- **Regression:** `a + b > c` over int, double and int columns, and `s * n
if n > m else s` over string, int and int columns, run natively with CPython's
results.
- **Inspection:** A refined body with three untyped parameters emits the
full product of integral, fractional and string variants, and one with four
untyped parameters emits uniform variants.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/pythonNumericPromotion.scala:
##########
@@ -0,0 +1,414 @@
+/*
+ * 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.sql.internal.SQLConf
+import org.apache.spark.sql.types.{ByteType, DataType, DoubleType, FloatType,
IntegerType, LongType, ShortType}
+
+/**
+ * Widening rules that give transpiled Python UDF arithmetic Python's overflow
behaviour.
+ *
+ * A Python `int` has no width -- it is a digit array that grows per value, so
`x * 100` on a
+ * tinyint column returns 12700 and thinks nothing of it. Catalyst picks one
type per column
+ * before it sees any data, and `Multiply` keeps its operands' type, so the
same expression
+ * raises ARITHMETIC_OVERFLOW under ANSI. The interpreted Python UDF path does
not have this
+ * problem, because it converts each row's result to the UDF's declared return
type
+ * individually -- input widths never enter into it.
+ *
+ * We cannot reproduce "per value" with a static type, but we do not need to.
Python needs
+ * unbounded integers because a Python int is unbounded; a Spark column is 8,
16, 32 or 64 bits,
+ * and that bound propagates through the expression. So the worst case over
every row the column
+ * could possibly hold is computable from the input types alone, with no data:
+ *
+ * tinyint + tinyint -> 256 -> ShortType
+ * abs(smallint) -> 32768 -> IntegerType
+ * int32 + int32 -> 2**32 -> LongType
+ * int32 * int32 -> 2**62 -> LongType
+ * int64 + int64 -> 2**64 -> nothing fits; left alone (see
narrowestFor)
+ *
+ * Widening the *operands* to that type is what makes the difference; widening
the result does
+ * not, and is what the lowerings did before. `a + b` on two int columns
already reported
+ * LongType, because the transpiler casts to the declared return type at the
end -- but the
+ * addition happened in IntegerType and overflowed long before that cast was
reached.
+ *
+ * Two deliberate limits:
+ *
+ * - `LongType` is the ceiling, so anything whose worst case needs more than
64 bits is left
+ * alone and raises on overflow exactly as it did before this rule existed
-- no worse, and
+ * never a wrong answer. `narrowestFor` explains why decimal is not an
option here. In practice
+ * this means bigint operands: every narrower width promotes cleanly.
+ * - Only integral inputs are promoted. Doubles need nothing: they saturate
to infinity, which
+ * is what Python does too, so there is no overflow to avoid.
+ *
+ * Note what this deliberately does NOT do. Once the result reaches the UDF's
declared return
+ * type, `EvaluatePython.makeFromJava` narrows it with
`.toByte`/`.toShort`/`.toInt` -- two's
+ * complement truncation, so an interpreted UDF declared `-> ByteType` turns
500 into -12 without
+ * a word. Matching the interpreted path there would mean reproducing silent
data corruption, so
+ * the transpiled path keeps raising instead. Promotion is about not failing
on an intermediate
+ * that Python would have carried; it is not licence to invent a wrong answer.
+ */
+object PythonNumericPromotion {
+
+ /** Spark's numeric precedence, for `widestOf`. A val, not a local --
`widestOf` is hot. */
+ private val rank: Seq[DataType] =
+ Seq(ByteType, ShortType, IntegerType, LongType, FloatType, DoubleType)
+
+ /**
+ * The largest magnitude a value of `dt` can have, or None if `dt` is not an
integral type we
+ * promote. Note these are magnitudes, not maxima -- two's complement
reaches one further in
+ * the negative direction, and `abs(Byte.MinValue)` is the case that cares.
+ */
+ private def magnitude(dt: DataType): Option[BigInt] = dt match {
+ case ByteType => Some(BigInt(1) << 7)
+ case ShortType => Some(BigInt(1) << 15)
+ case IntegerType => Some(BigInt(1) << 31)
+ case LongType => Some(BigInt(1) << 63)
+ // Decimal is refused outright rather than half-supported. Ranking it by
precision looked
+ // honest but was worse than declining: a decimal(18,0) pair promoted to
bigint, silently
+ // losing the decimal type, while decimal(19,0) and any non-zero scale
fell through to an
+ // unaligned replacement and INTERNAL_ERROR. Returning None sends every
decimal to `plain`,
+ // which keeps its type. (A decimal column cannot reach a transpiled UDF
anyway --
+ // ResolveTranspiledPythonUDFOptions excludes it from every numeric
category -- so this only
+ // matters for a direct SQL call.)
+ case _ => None
+ }
+
+ /**
+ * The narrowest integral type that holds every value up to `m` in
magnitude, or None when
+ * nothing does.
+ *
+ * `LongType` is the ceiling, and that is a limitation of how this is built
rather than of
+ * Spark. `DecimalType(38, 0)` would reach further and would cover a single
bigint multiply
+ * exactly, 2**126 being 38 digits. An earlier version of this comment
claimed a decimal
+ * replacement could not resolve because `DecimalPrecision` coercion is what
caps a product's
+ * precision at 38; that is wrong. `Multiply` caps it itself, in
`resultDecimalType`, and
+ * `Multiply(cast(a, decimal(38,0)), cast(b, decimal(38,0)))` resolves
standalone. What actually
+ * failed was `Add(decimal, int_literal)`, because the hand-rolled alignment
in `widestOf` does
+ * not rank DecimalType -- a gap in this file, not in Catalyst.
+ *
+ * Ranking decimal here would then have to reproduce Spark's decimal type
coercion by hand,
+ * which is the wrong trade. The right shape is to widen in an analyzer rule
instead of inside
+ * the expression: `ResolveTranspiledPythonUDFOptions` already runs in the
Resolution batch
+ * alongside `typeCoercionRules`, so a rewrite there is coerced on the next
fixed-point
+ * iteration and needs none of `plain`, `widestOf`, or a lazily-computed
replacement. Until
+ * then `x * y` on two bigints raises on overflow exactly as it did before
promotion existed.
+ */
+ private def narrowestFor(m: BigInt): Option[DataType] = {
+ if (m <= Byte.MaxValue) Some(ByteType)
+ else if (m <= Short.MaxValue) Some(ShortType)
+ else if (m <= Int.MaxValue) Some(IntegerType)
+ else if (m <= Long.MaxValue) Some(LongType)
+ else None
+ }
+
+ /**
+ * The type to evaluate `worst`-bounded arithmetic in, given the operand
types. Returns None
+ * when nothing needs to change: a non-integral operand, or a worst case too
wide for any
+ * Catalyst type, both of which leave the operator alone.
+ */
+ private def promote(inputs: Seq[DataType], worst: Seq[BigInt] => BigInt):
Option[DataType] = {
+ val magnitudes = inputs.map(magnitude)
+ if (magnitudes.exists(_.isEmpty)) {
+ None
+ } else {
+ // Whatever comes back is always strictly wider than every input, so
there is nothing to
+ // filter out: `narrowestFor(m)` answers T only when m <= T.MaxValue,
which is one below
+ // `magnitude(T)`, and `worst` is at least the widest input's magnitude
for all three
+ // functions below. `PythonNumericPromotionSuite` pins that down.
+ narrowestFor(worst(magnitudes.map(_.get)))
+ }
+ }
+
+ /** Promotion target for `a + b` / `a - b`: the operands' magnitudes can
only add. */
+ def forAddition(left: DataType, right: DataType): Option[DataType] =
+ promote(Seq(left, right), ms => ms(0) + ms(1))
+
+ /** Promotion target for `a * b`: the magnitudes multiply. */
+ def forMultiplication(left: DataType, right: DataType): Option[DataType] =
+ promote(Seq(left, right), ms => ms(0) * ms(1))
+
+ /**
+ * Promotion target for `abs(a)` and unary minus. Both need exactly one more
value than the
+ * type holds, because two's complement has no positive counterpart for the
minimum -- which
+ * is why `abs(x)` on a smallint holding -32768 raises where Python answers
32768.
+ */
+ def forNegation(child: DataType): Option[DataType] = promote(Seq(child), ms
=> ms(0))
+
+ /**
+ * The operator over its operands as given -- what we report before the
children resolve and a
+ * width can be chosen. The one thing it must do is align the operand types:
a replacement never
+ * goes through type coercion (`InheritAnalysisRules` is what normally
arranges that, and we
+ * cannot use it, since building ours needs the children's types), so an
unaligned `Add(bigint,
+ * int)` does not resolve and CheckAnalysis reports INTERNAL_ERROR -- a
broken query rather than
+ * a fallback. `x + 1` on a bigint column is enough to reach it, the literal
being an int.
+ */
+ def plain(
+ left: Expression,
+ right: Expression,
+ context: NumericEvalContext,
+ op: (Expression, Expression) => Expression): Expression = {
+ // Align the operand types ourselves rather than emitting `Add(bigint,
int)` and hoping. A
+ // replacement has to be resolvable *as written*: `InheritAnalysisRules`
is what normally
+ // hands a replacement to type coercion, and we cannot use it (building
ours needs the
+ // children's types, which are not known in the constructor). So an
unaligned replacement
+ // never gets coerced and CheckAnalysis rejects it with INTERNAL_ERROR --
which is a broken
+ // query, not a fallback. `x + 1` on a bigint column is enough to hit it,
since the literal
+ // is an int.
+ //
+ // Widest-of-two is the whole rule here, and it is safe because these
operators are only
+ // emitted for numeric operands (see `_promoting_if_numeric` on the Python
side), and it is
+ // Spark's own numeric precedence, so it agrees with what coercion would
have done. Note the
+ // gate really is *numeric* and not *integral*: an unannotated parameter's
category is plain
+ // "numeric", so an integral-only gate would refuse the commonest body of
all.
+ // Read each operand's type once: `dataType` on a RuntimeReplaceable child
builds its
+ // replacement to answer, so asking twice does the work twice.
+ val (lt, rt) = (left.dataType, right.dataType)
+ widestOf(lt, rt) match {
+ case Some(t) if lt != t || rt != t => op(cast(left, t, context),
cast(right, t, context))
+ case _ => op(left, right)
+ }
+ }
+
+ /**
+ * A widening cast carrying the caller's eval mode rather than reading the
ambient conf.
+ *
+ * Behaviour is the same either way -- every cast we emit widens (tinyint to
smallint and so on),
+ * so there is no value to overflow and nothing for ANSI to raise about.
What it buys is a stable
+ * canonical form: `Cast`'s `evalMode` defaults from `SQLConf.get`, and
because our replacement is
+ * built lazily, two identical nodes forced under different conf would
otherwise disagree and
+ * stop sharing.
+ */
+ private def cast(child: Expression, target: DataType, context:
NumericEvalContext): Expression =
+ Cast(child, target, None, context.evalMode)
+
+ /**
+ * The wider of two numeric types, or None if either is not one we rank.
+ *
+ * This is Spark's own numeric precedence, and it covers the float types as
well as the integral
+ * ones on purpose: `plain` uses it to make a replacement resolvable, and `x
/ 2.0 + 1` needs
+ * aligning just as much as `x + 1` on a bigint does. DecimalType is absent
because a decimal
+ * column never reaches these expressions --
ResolveTranspiledPythonUDFOptions keeps it out of
+ * every numeric category -- and because we never produce one ourselves.
+ */
+ private def widestOf(left: DataType, right: DataType): Option[DataType] = {
+ (rank.indexOf(left), rank.indexOf(right)) match {
+ case (l, r) if l >= 0 && r >= 0 => Some(rank(math.max(l, r)))
+ case _ => None
+ }
+ }
+
+ /**
+ * `op(cast(left, t), cast(right, t))` for the promoted `t`, or `plain` when
nothing needs
+ * widening. Lives here so the "cast both sides, then delegate" step exists
once rather than in
+ * each operator below.
+ */
+ def widened(
+ left: Expression,
+ right: Expression,
+ target: (DataType, DataType) => Option[DataType],
+ context: NumericEvalContext,
+ op: (Expression, Expression) => Expression): Expression = {
+ target(left.dataType, right.dataType) match {
+ case Some(t) => op(cast(left, t, context), cast(right, t, context))
+ // No promotion to apply, but the operands may still disagree, and an
unaligned replacement
+ // does not resolve -- so fall through to `plain`, which aligns them.
+ case None => plain(left, right, context, op)
+ }
+ }
+
+}
+
+/**
+ * Arithmetic that evaluates at a width wide enough for Python's semantics, per
+ * [[PythonNumericPromotion]]. Only meant to be emitted by the Python UDF
transpiler, which
+ * reaches them through `call_function` the same way it reaches `div` -- hence
the registry
Review Comment:
**Nit (P3):** This says the transpiler reaches these expressions through
`call_function` the same way it reaches `div`, and warns that hand-written SQL
could quietly get a decimal back. Neither holds in this PR. FunctionRegistry
registers all five with `registerInternalExpression`, and `_promoting` in
transpile.py calls them through `InternalFunction`, so neither SQL nor
`call_function` resolves them; `narrowestFor` caps promotion at LongType, so no
decimal is produced. The same premise recurs at line 87 ('this only matters for
a direct SQL call') and in the `unpromoted` doc ('Nothing reaches the throwing
path through the SQL parser today').
See **Shared repair plan 1** in the review body.
##########
.github/workflows/build_and_test.yml:
##########
@@ -601,8 +603,18 @@ jobs:
pyspark-pandas-connect
- >-
pyspark-pandas-slow-connect
+ include:
+ # The transpile differential fuzzer needs a much larger per-test
+ # timeout than the 450s the fast pyspark-sql group shares. At 10
+ # hypothesis examples the whole file runs ~1900s on CI runners; the
+ # extra room lets us fuzz harder (20 examples, ~2900s) and still
+ # keep comfortable margin under the 3600s budget.
+ - modules: pyspark-sql-slow
Review Comment:
**Non-blocking (P2):** GitHub Actions processes `include` after `exclude`,
and an include entry that can't merge into a remaining combination without
overwriting one of its values becomes a new combination. For a pandas-only
change this job still runs, because pyspark-pandas is required, and the exclude
below removes `{java, pyspark-sql-slow}`. This entry can't merge into any other
combination, since each has a different `modules` value, so `{modules:
pyspark-sql-slow, pyspark_test_timeout: 3600, run_hypothesis_max_examples: 20}`
comes back with no `java` key. `setup-build-env` then skips the JDK install for
the empty `java-version`, so the job runs on the container's default JDK, holds
a runner, and can fail for reasons unrelated to the change. Deriving the
timeout and the example cap from `matrix.modules` in the `env` expressions,
instead of using an include, keeps the exclude effective.
**Verification:**
- **Inspection:** The expanded matrix for a pandas-only change contains no
pyspark-sql-slow combination, and every combination carries the java key.
- **Inspection:** For a run requiring PySpark tests, the pyspark-sql-slow
combination's environment resolves to a 3600-second test timeout and 20
examples.
##########
python/pyspark/sql/transpile.py:
##########
@@ -549,43 +1365,57 @@ def _lower_value_compare(
mismatch raises so this variant is dropped and the UDF falls back to
interpreted Python rather than silently diverging.
- One value-level difference from Python remains (it needs runtime
- value info, so it is documented, not guarded): Spark orders ``NaN``
- as greater than every value, whereas Python's ``NaN`` comparisons
- are all ``False``.
+ Spark orders ``NaN`` as greater than every value, whereas Python's
+ ``NaN`` comparisons are all ``False``, so a numeric variant that could
+ hold a double returns false when either operand is NaN -- see
+ ``_nan_guard``. The NULL raise comes first, matching Python, which
throws
+ TypeError on ``None > 0`` regardless of the other operand.
"""
lc = self._category(params, left_node)
rc = self._category(params, right_node)
- if lc != rc and not (_is_numeric_cat(lc) and _is_numeric_cat(rc)):
+ # Coarse comparison: Python orders ints against floats happily, so
only a
+ # cross-kind pairing (numeric vs string, ...) is the TypeError case.
+ if _coarse_category(lc) != _coarse_category(rc):
Review Comment:
**Blocking (P1):** This check compares categories coarsely, so an integral
operand against a fractional one is lowered as a plain Spark comparison. ANSI
coercion then casts the integral side to double, which rounds integers beyond
2^53, while CPython compares an int with a float exactly. The base branch
already rounded this way for bodies it lowered, such as `x > 1e16` on a bigint
column, but this PR sends new bodies into it, and they return wrong booleans
with no error, so filters and joins can keep or drop the wrong rows.
`udf(lambda x: abs(x) > 1e16, BooleanType())` on a bigint holding
10000000000000001 evaluates `cast(abs(x) as double) > 1.0E16`, which is false,
while CPython returns True. On the base branch `abs` was not lowered, so this
UDF ran as Python and was right. `x // 1 == 9007199254740992.0`, `min(x, y) >
2.0 ** 53`, `(x & m) >= 1e17` and `round(x, -1) < 1e16` behave the same way.
Operand promotion reaches it with no new operator. `udf(lambda x, y: x * y >
9007199515875288.0, BooleanType())` on two int columns holding 94906267 now
multiplies in bigint (9007199515875289), the cast rounds that to
9007199515875288.0, and the comparison is false where CPython returns True. On
the base branch that multiply ran in IntegerType and raised
ARITHMETIC_OVERFLOW. I checked each CPython result with python3.
**Recommended change:** Lower a comparison between an integral and a
fractional operand as an exact comparison that compares in double only where
that is exact, instead of letting ANSI coercion cast the integral side to
double.
**Why this works:** In `_lower_eq` and `_lower_value_compare`, when one
operand is integral and the other fractional, keep the NULL and NaN branches
and replace the coerced value comparison with three ranges of the fractional
value. While its magnitude is below 2^53, compare it with the integral value
cast to double: an integral value beyond 2^53 casts to a double beyond 2^53
with the same sign, so the ordering stays right. From there up to the bigint
range the fractional value is a whole number, so compare the integral value
with it cast to bigint, which is exact. Beyond the bigint range, including
infinities, its sign decides. An integral side the existing int32 exactness
walk already bounds can keep the plain comparison.
**Scope:** Replace the coerced int-versus-float comparison with an exact one.
**Compatibility:** Same-kind comparisons, NaN handling, NULL raising and
native execution are unchanged; only the value comparison between an integral
and a fractional operand changes.
**Risks:** The range branches must be exact at both ends of the bigint range
(-2^63 is both a bigint and a double, 2^63 is neither in range nor a bigint),
for signed zero and infinities, and in both operand orders; a one-sided error
reintroduces a wrong result. Each mixed comparison carries the extra branches,
a small constant per-row cost even where the plain comparison is already exact.
**Constraints:** The NaN branch must stay ahead of the range branches, since
NaN fails every range test.
**Success:** `abs(x) > 1e16` on a bigint holding 10000000000000001 returns
True, `x // 1 == 9007199254740992.0` with 9007199254740993 returns False, and
`x * y > 9007199515875288.0` on two int columns holding 94906267 returns True,
as in CPython. Every comparison the current lowering transpiles still runs
natively, including comparisons of bigint columns and of int32 products against
fractional operands.
**Verification:**
- **Regression:** Mixed int-versus-float comparisons over bigint values just
above 2^53, and over int32 products beyond 2^53, return CPython's results
natively. This covers equality and each ordering in both operand orders, with
and without a newly lowered operator such as abs, floor division or a bitwise
operator.
- **Behavior:** Comparisons against fractional values at and beyond the
bigint range, infinities, NaN and signed zero match CPython, and comparisons
between int32 operands and fractional operands keep running natively.
##########
python/pyspark/sql/transpile.py:
##########
@@ -891,56 +1783,210 @@ def _convert_chunk(self, params: List[str], body:
ast.AST | None) -> Column:
# (str+int, str-str, ...) raise so this variant is dropped and
# the JVM picks another option or falls back to the Python UDF.
#
- # `**` is intentionally NOT lowered: Spark's `pow` is DOUBLE
and
- # loses precision for large integers, so it would silently
return
- # wrong results. TODO (SPARK-55210): add an exact integer-power
- # lowering and re-enable it.
- #
- # Value-level divergences remain documented (need runtime value
- # info, not type): overflow raises ARITHMETIC_OVERFLOW under
ANSI
- # where Python promotes to a big int; arithmetic is not
- # NULL-guarded (`x + 1` on NULL -> NULL vs Python TypeError).
- # TODO (SPARK-55210): map overflow / divide-by-zero precisely.
+ # `//`, `**` and the bitwise operators also need *integral*
+ # operands; `/` needs a fractional or int32-exact one. The
module
+ # docstring has the reasoning and the resulting fall-backs;
+ # SPARK-55220 tracks the strictness knob for the value-level
ones.
lc = self._category(params, left)
rc = self._category(params, right)
+ both_numeric = _unify_numeric(lc, rc) is not None
+ both_integral = lc in _INTEGRAL_CATEGORIES and rc in
_INTEGRAL_CATEGORIES
left_col = self._convert_chunk(params, left)
right_col = self._convert_chunk(params, right)
match op:
case ast.Add():
if lc == rc == "string":
- return concat(left_col, right_col)
- if _is_numeric_cat(lc) and _is_numeric_cat(rc):
- return left_col.__add__(right_col)
+ # `concat` propagates NULL where Python raises
+ # TypeError on `'a' + None`, so guard rather than
+ # return a value Python never would -- the same
+ # guard every numeric lowering carries.
+ concat_null = lit(
+ "Python UDF transpiler: cannot concatenate
NULL; "
+ "Python would raise TypeError here. Add an `is
not "
+ "None` guard or filter NULLs upstream."
+ )
+ return when(
+ left_col.isNull() | right_col.isNull(),
+ raise_error(concat_null),
+ ).otherwise(concat(left_col, right_col))
+ if both_numeric:
+ return _raise_on_null_operand(
+ "+",
+ _promoting_if_numeric(
+ "add",
+ [lc, rc],
+ lambda: left_col.__add__(right_col),
+ left_col,
+ right_col,
+ ),
+ left_col,
+ right_col,
+ )
case ast.Sub():
- if _is_numeric_cat(lc) and _is_numeric_cat(rc):
- return left_col.__sub__(right_col)
+ if both_numeric:
+ return _raise_on_null_operand(
+ "-",
+ _promoting_if_numeric(
+ "subtract",
+ [lc, rc],
+ lambda: left_col.__sub__(right_col),
+ left_col,
+ right_col,
+ ),
+ left_col,
+ right_col,
+ )
case ast.Mult():
- if _is_numeric_cat(lc) and _is_numeric_cat(rc):
- return left_col.__mul__(right_col)
- if lc == "string" and rc in ("integer", "numeric"):
- return repeat(left_col, right_col.cast("int"))
- if lc in ("integer", "numeric") and rc == "string":
- return repeat(right_col, left_col.cast("int"))
+ if both_numeric:
+ return _raise_on_null_operand(
+ "*",
+ _promoting_if_numeric(
+ "multiply",
+ [lc, rc],
+ lambda: left_col.__mul__(right_col),
+ left_col,
+ right_col,
+ ),
+ left_col,
+ right_col,
+ )
+ # The repeat count has to be an int -- `"ab" * 2.5` is
a
+ # TypeError, not a truncation. A float literal shows
up as
+ # "fractional" here; for a parameter only the JVM
knows, so
+ # narrow the count and let a double column drop the
option.
+ # "integral32" not "integral": `repeat` casts the
count to
+ # int, which raises under ANSI for a bigint above
Int.MaxValue
+ # where Python returns "" (negative) or a huge string.
A
+ # bigint column therefore drops the option and falls
back.
+ if lc == "string" and _is_numeric_cat(rc) and rc !=
"fractional":
+ self._narrow(params, "integral32", right)
Review Comment:
**Non-blocking (P2):** Narrowing the count to `integral32` drops bigint
count columns, which is what `spark.createDataFrame([('ab', 3)])` infers for
Python ints and what count and sum return. On the base branch `udf(lambda s, n:
s * n, StringType())` matched them and lowered `repeat(s, cast(n as int))`,
which was correct for every count in the int range and raised past it, the
raise-where-Python-answers trade-off the transpiler accepts elsewhere. Now
these calls run as interpreted Python, and the unit tests switch `b long` to `b
int` to keep their cases native.
Narrowing to `integral` and clamping the count at zero before the cast would
keep bigint counts native and return '' for any non-positive count, as CPython
does. Use a CASE WHEN for the clamp, as `_lower_shift` does, so a NULL count
stays NULL and still raises; `greatest(n, 0)` would turn it into 0.
**Verification:**
- **Regression:** String repeat with a bigint count column, in either
operand order, runs natively and matches CPython for positive, zero, negative
and below-int-range counts, and a NULL count raises.
- **Behavior:** A fractional count column still falls back to interpreted
Python, which raises TypeError like CPython.
--
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]