HyukjinKwon commented on code in PR #60541:
URL: https://github.com/apache/spark/pull/60541#discussion_r4581846885
##########
python/pyspark/sql/tests/test_udf_in_higher_order_function.py:
##########
@@ -1072,6 +1072,42 @@ def plus_one_arrow_iter(it: Iterator[pa.Array]) ->
Iterator[pa.Array]:
[([2, 3, 4],), ([],), (None,), ([11, 21],), ([6],)],
)
+ def test_scalar_arrow_udf_result_cast_is_safe(self):
+ # A lifted Arrow UDF casts its result to the declared type safely, as
the same UDF does
+ # outside a lambda, whatever
spark.sql.execution.pandas.convertToArrowArraySafely says
+ # (that setting applies to pandas UDFs only). A value that does not
fit the declared type
Review Comment:
Fixed in 4567b8f. The test comment and the `_to_flat_batch` docstring now
say the setting applies to pandas UDFs and Arrow-optimized Python UDFs, not to
Arrow UDFs. The docstring also names `ArrowElementwiseUDFHandler`, which keeps
following it at `_elementwise.py:296`, as `ArrowBatchedUDFArrowHandler` does at
`_arrow.py:960`.
##########
python/pyspark/sql/tests/test_udf_in_higher_order_function.py:
##########
@@ -1072,6 +1072,42 @@ def plus_one_arrow_iter(it: Iterator[pa.Array]) ->
Iterator[pa.Array]:
[([2, 3, 4],), ([],), (None,), ([11, 21],), ([6],)],
)
+ def test_scalar_arrow_udf_result_cast_is_safe(self):
+ # A lifted Arrow UDF casts its result to the declared type safely, as
the same UDF does
+ # outside a lambda, whatever
spark.sql.execution.pandas.convertToArrowArraySafely says
+ # (that setting applies to pandas UDFs only). A value that does not
fit the declared type
+ # raises instead of silently overflowing.
+ from typing import Iterator
+
+ import pyarrow as pa
+
+ from pyspark.errors import PythonException
+ from pyspark.sql.functions import arrow_udf
+
+ df = self.spark.createDataFrame([([1, 2],)], "values array<long>")
+
+ @arrow_udf(IntegerType())
+ def add_max_int(a: pa.Array) -> pa.Array:
+ return pa.compute.add(a, 2147483647)
+
+ @arrow_udf(IntegerType())
+ def add_max_int_iter(it: Iterator[pa.Array]) -> Iterator[pa.Array]:
+ for a in it:
+ yield pa.compute.add(a, 2147483647)
+
+ for safecheck in [False, True]:
Review Comment:
Added both in 4567b8f.
- `test_scalar_pandas_udf_result_cast_follows_setting` runs the scalar and
scalar iterator pandas UDFs inside and outside a lambda. With the setting off,
both overflow to the same values. With it on, both raise the same conversion
error. It fails if `_PandasElementwiseUDFHandler._to_flat_batch` hard-codes
`safecheck=True` (checked locally).
- `test_scalar_arrow_udf_result_cast_is_safe` now has a truncating case,
`add_half` (`1.5` for an int return). With the setting off, it raises inside
and outside a lambda. Without the fix, the lifted call does not raise.
##########
python/pyspark/eval_handlers/_elementwise.py:
##########
@@ -320,13 +320,19 @@ def _to_flat_batch(
self, output: Any, return_type: DataType, output_schema: pa.Schema
) -> pa.RecordBatch:
"""Convert one UDF result over flat elements to a one-column batch,
one row per element:
- coerce it to the UTC-typed ``output_schema``."""
+ coerce it to the UTC-typed ``output_schema``.
+
+ The cast is always safe, as in the base ``SQL_SCALAR_ARROW_UDF`` and
+ ``SQL_SCALAR_ARROW_ITER_UDF`` paths, so a result that does not fit the
declared type
+ raises instead of overflowing or truncating. ``runner_conf.safecheck``
+ (``spark.sql.execution.pandas.convertToArrowArraySafely``) applies to
the pandas flavor
+ only."""
import pyarrow as pa
return ArrowBatchTransformer.enforce_schema(
pa.RecordBatch.from_arrays([output], names=output_schema.names),
output_schema,
- safecheck=self._runner_conf.safecheck,
+ safecheck=True,
Review Comment:
Added `test_result_cast_is_safe` to `ArrowScalarElementwiseUDFHandlerTests`
and `ArrowScalarIterElementwiseUDFHandlerTests` in 4567b8f. Each UDF returns
`pc.add(x, 2**31 - 1)` for an `IntegerType` return, with
`convertToArrowArraySafely` set to false in the runner conf, and expects
`RESULT_COLUMN_TYPES_MISMATCH`. Both fail with the old
`safecheck=self._runner_conf.safecheck`.
##########
python/pyspark/sql/tests/test_udf_in_higher_order_function.py:
##########
@@ -1072,6 +1072,42 @@ def plus_one_arrow_iter(it: Iterator[pa.Array]) ->
Iterator[pa.Array]:
[([2, 3, 4],), ([],), (None,), ([11, 21],), ([6],)],
)
+ def test_scalar_arrow_udf_result_cast_is_safe(self):
+ # A lifted Arrow UDF casts its result to the declared type safely, as
the same UDF does
+ # outside a lambda, whatever
spark.sql.execution.pandas.convertToArrowArraySafely says
+ # (that setting applies to pandas UDFs only). A value that does not
fit the declared type
+ # raises instead of silently overflowing.
+ from typing import Iterator
+
+ import pyarrow as pa
+
+ from pyspark.errors import PythonException
+ from pyspark.sql.functions import arrow_udf
+
+ df = self.spark.createDataFrame([([1, 2],)], "values array<long>")
+
+ @arrow_udf(IntegerType())
+ def add_max_int(a: pa.Array) -> pa.Array:
+ return pa.compute.add(a, 2147483647)
+
+ @arrow_udf(IntegerType())
+ def add_max_int_iter(it: Iterator[pa.Array]) -> Iterator[pa.Array]:
+ for a in it:
+ yield pa.compute.add(a, 2147483647)
+
+ for safecheck in [False, True]:
+ with
self.sql_conf({"spark.sql.execution.pandas.convertToArrowArraySafely":
safecheck}):
+ for f in [add_max_int, add_max_int_iter]:
+ with self.subTest(safecheck=safecheck, udf=f.__name__):
+ with self.assertRaisesRegex(
+ PythonException, "RESULT_COLUMN_TYPES_MISMATCH"
+ ):
+ df.select(f(df.values[0])).collect()
Review Comment:
Done in 4567b8f. The outside-lambda query now runs once per UDF, with the
setting off, and the lifted query still runs under both values. With the new
truncating case that is 8 failing queries: 6 with the setting off and 2 with it
on.
##########
python/pyspark/eval_handlers/_elementwise.py:
##########
@@ -320,13 +320,19 @@ def _to_flat_batch(
self, output: Any, return_type: DataType, output_schema: pa.Schema
) -> pa.RecordBatch:
"""Convert one UDF result over flat elements to a one-column batch,
one row per element:
- coerce it to the UTC-typed ``output_schema``."""
+ coerce it to the UTC-typed ``output_schema``.
+
+ The cast is always safe, as in the base ``SQL_SCALAR_ARROW_UDF`` and
+ ``SQL_SCALAR_ARROW_ITER_UDF`` paths, so a result that does not fit the
declared type
+ raises instead of overflowing or truncating. ``runner_conf.safecheck``
+ (``spark.sql.execution.pandas.convertToArrowArraySafely``) applies to
the pandas flavor
+ only."""
import pyarrow as pa
return ArrowBatchTransformer.enforce_schema(
Review Comment:
Agreed, I'll do it as a separate follow-up and keep this PR to the behavior
fix. The helper would hold the result coercion that the base and lifted Arrow
handlers share (output schema, `arrow_cast`, `safecheck=True`), e.g. on
`ArrowBatchTransformer`.
--
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]