dongjoon-hyun commented on code in PR #60541:
URL: https://github.com/apache/spark/pull/60541#discussion_r4581740443


##########
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:
   **[2] Minor: could the test also pin the pandas flavor and a truncating 
cast?** It covers only the Arrow flavor, so nothing checks that a lifted pandas 
UDF (`SQL_SCALAR_PANDAS_ELEMENTWISE_UDF`, 
`SQL_SCALAR_PANDAS_ITER_ELEMENTWISE_UDF`) still follows 
`convertToArrowArraySafely=false`, as the new docstring in `_elementwise.py` 
says. If a later change also hard-coded `safecheck=True` in 
`_PandasElementwiseUDFHandler._to_flat_batch`, this suite would still pass, 
while a lifted pandas UDF would then raise where the same UDF outside a lambda 
silently casts. The PR description also mentions truncation, but only the 
overflow case is covered. Could we add a pandas UDF case that checks the lifted 
result matches the same UDF outside a lambda under both values, and an Arrow 
case that truncates, e.g. a float result such as `1.5` for an int return type?



##########
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:
   **[3] Minor: could the always-safe cast get a handler-level test too?** 
`test_elementwise_eval_type_handlers.py` is outside this diff, so I left this 
here. It already has `test_coerces_result_to_return_type` for both Arrow 
flavors (L336 and L533 there), but those widen int32 to int64, so the safe flag 
does not matter. `RunnerConf.safecheck` is false when the key is absent 
(`worker_util.py:484`), and `_handler` passes only the session time zone by 
default, so a UDF returning `pc.add(x, 2**31 - 1)` with an `IntegerType` return 
type would reproduce the original bug without a SparkSession. Could we add such 
a case next to `test_coerces_result_to_return_type`?



##########
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:
   **[1] Minor: `convertToArrowArraySafely` does not apply to pandas UDFs 
only.** It still drives the fallback cast of Arrow-optimized Python UDFs, both 
outside a lambda (`ArrowBatchedUDFArrowHandler`, `_arrow.py:960`) and lifted 
out of one (`ArrowElementwiseUDFHandler`, `_elementwise.py:296`). A reader who 
takes this comment at face value could hard-code `safe=True` at 
`_elementwise.py:296` too, and then a lifted `@udf(useArrow=True)` would raise 
where the same UDF outside a lambda silently casts, the kind of divergence this 
PR fixes. Could it say something like "(that setting applies to pandas UDFs and 
Arrow-optimized Python UDFs, not to Arrow UDFs)"?



##########
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:
   **[5] Minor: a shared helper for the result coercion, maybe in a 
follow-up?** The Arrow flavor here repeats the result coercion of 
`ArrowScalarUDFHandler` and `ArrowScalarIterUDFHandler`: its own output schema, 
and its own `enforce_schema` call with its own `safecheck` choice. That copy is 
how `runner_conf.safecheck` came in with SPARK-58695 and was carried over by 
SPARK-60235, and a later change to the base coercion (`arrow_cast`, 
`safecheck`, large types) would have to be repeated here by hand. Could the 
base and the lifted handlers share one helper, e.g. on `ArrowBatchTransformer`, 
so they stay in parity by construction? A follow-up is fine.



##########
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:
   **[4] Nit: the outside-lambda query does not need to run under both 
values.** The base `SQL_SCALAR_ARROW_UDF` and `SQL_SCALAR_ARROW_ITER_UDF` paths 
always cast safely (`ArrowScalarUDFHandler` takes the default `safecheck=True` 
of `enforce_schema`, and `ArrowScalarIterUDFHandler` passes it at 
`_arrow.py:766`), so this line repeats the same check under `true` and `false`. 
Each of these queries fails a task and goes through the error conversion, in 
the classic and the Connect parity runs. Could it be checked once, under 
`false` where the parity matters, so the test runs 6 failing queries instead of 
8?



-- 
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]

Reply via email to