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


##########
python/pyspark/sql/tests/test_functions.py:
##########
@@ -1634,6 +1634,28 @@ def test_approxQuantile(self):
         self.assertRaises(TypeError, lambda: df.stat.approxQuantile(("a", 
123), [0.1, 0.9], 0.1))
         self.assertRaises(TypeError, lambda: df.stat.approxQuantile(["a", 
123], [0.1, 0.9], 0.1))
 
+        with self.assertRaises(PySparkValueError) as pe:
+            df.stat.approxQuantile("a", [0.1, 0.5, 0.9], float("nan"))
+
+        self.check_error(
+            exception=pe.exception,
+            errorClass="NEGATIVE_VALUE",
+            messageParameters={"arg_name": "relativeError", "arg_value": 
"nan"},
+        )
+
+        with self.assertRaises(PySparkTypeError) as pe:
+            df.stat.approxQuantile("a", [0.1, 0.5, 0.9], True)

Review Comment:
   **[1] Could the tests also cover `False` and a plain int?**
   
   The new cases cover `NaN` and `True`. `False` takes the same `bool` branch, 
but it used to be accepted as an exact-quantile request (`False == 0`), so it 
is the case most likely to exist in user code. A plain int such as `0` is the 
valid path that the helper must keep accepting and return as `0.0`, and I could 
not find a test that passes an int `relativeError` today. Could you add 
`approxQuantile("a", [0.5], False)` (expecting `NOT_EXPECTED_TYPE`) and a 
successful `approxQuantile("a", [0.5], 0)`?



##########
python/pyspark/sql/dataframe.py:
##########
@@ -78,6 +79,31 @@
 __all__ = ["DataFrame", "DataFrameNaFunctions", "DataFrameStatFunctions"]
 
 
+def validate_approx_quantile_relative_error(relativeError: Any) -> float:
+    """
+    Validate the ``relativeError`` argument of ``DataFrame.approxQuantile``, 
shared by the
+    classic and Connect implementations so both stay in sync. Returns it as a 
``float``.
+    """
+    if isinstance(relativeError, bool) or not isinstance(relativeError, 
(float, int)):
+        raise PySparkTypeError(
+            errorClass="NOT_EXPECTED_TYPE",
+            messageParameters={
+                "expected_type": "float or int",
+                "arg_name": "relativeError",
+                "arg_type": type(relativeError).__name__,
+            },
+        )
+    if not relativeError >= 0:
+        raise PySparkValueError(
+            errorClass="NEGATIVE_VALUE",
+            messageParameters={
+                "arg_name": "relativeError",
+                "arg_value": str(relativeError),
+            },
+        )
+    return float(relativeError)

Review Comment:
   **[3] Minor: a huge int still escapes as a raw `OverflowError`.**
   
   This predates the PR, but the check now lives in one new helper. An int such 
as `10**400` passes both checks and then fails here with `OverflowError: int 
too large to convert to float` instead of a PySpark error. The type check at 
L87 is also uneven for numpy scalars: `np.float64` passes because it subclasses 
`float`, while `np.int64` is rejected with `NOT_EXPECTED_TYPE`. Could the 
helper turn the `OverflowError` into a `PySparkValueError`, and is rejecting 
`np.int64` intended?



##########
python/pyspark/sql/dataframe.py:
##########
@@ -78,6 +79,31 @@
 __all__ = ["DataFrame", "DataFrameNaFunctions", "DataFrameStatFunctions"]
 
 
+def validate_approx_quantile_relative_error(relativeError: Any) -> float:

Review Comment:
   **[5] Nit: could the helper name start with an underscore?**
   
   `pyspark.sql.dataframe` is a public API module, so 
`validate_approx_quantile_relative_error` shows up next to `DataFrame` in IDE 
completion and `dir()`, and `from pyspark.sql.dataframe import 
validate_approx_quantile_relative_error` works, even though it is not in 
`__all__`. Internal helpers that other modules import usually start with an 
underscore, such as `_parse_datatype_json_string` and 
`_validate_vectorized_udf`, which `classic/dataframe.py` and 
`connect/dataframe.py` already import. Could it be 
`_validate_approx_quantile_relative_error`? The same applies to 
`validate_approx_quantile_probabilities` in #60248.



##########
python/pyspark/sql/dataframe.py:
##########
@@ -35,6 +35,7 @@
 
 from pyspark import _NoValue
 from pyspark._globals import _NoValueType
+from pyspark.errors import PySparkTypeError, PySparkValueError

Review Comment:
   **[7] Nit: the module-level import makes two local imports redundant.**
   
   This file has imported `pyspark.errors` only inside functions so far, e.g. 
`from pyspark.errors import PySparkTypeError` in `_preapare_args_for_sample` 
(L2200) and `from pyspark.errors import PySparkIndexError, PySparkTypeError, 
PySparkValueError` in `_preapare_cols_for_sort` (L3329). With this module-level 
import, those two now re-import names that are already global. Could the helper 
import them locally like the rest of the file? #60248 adds the same line.



##########
python/pyspark/sql/classic/dataframe.py:
##########
@@ -1743,24 +1748,7 @@ def approxQuantile(
                 )
         probabilities = _to_list(self._sc, cast(List["ColumnOrName"], 
probabilities))
 
-        if not isinstance(relativeError, (float, int)):
-            raise PySparkTypeError(
-                errorClass="NOT_EXPECTED_TYPE",
-                messageParameters={
-                    "expected_type": "float or int",
-                    "arg_name": "relativeError",
-                    "arg_type": type(relativeError).__name__,
-                },
-            )
-        if relativeError < 0:
-            raise PySparkValueError(
-                errorClass="NEGATIVE_VALUE",
-                messageParameters={
-                    "arg_name": "relativeError",
-                    "arg_value": str(relativeError),
-                },
-            )
-        relativeError = float(relativeError)
+        relativeError = validate_approx_quantile_relative_error(relativeError)

Review Comment:
   **[4] Nit: `col` and `probabilities` reach the JVM before `relativeError` is 
checked.**
   
   This order predates the PR. L1726 and L1749 convert `col` and 
`probabilities` to JVM lists through `_to_list` (`PythonUtils.toList` via py4j) 
before this line validates `relativeError`, so an invalid `relativeError` costs 
two py4j calls that are thrown away. Could the two `_to_list` calls move down 
next to `self._jdf.stat().approxQuantile(...)`, so all three arguments are 
validated first, in the same order as the Connect side?



##########
python/pyspark/sql/classic/dataframe.py:
##########
@@ -73,7 +74,11 @@
     _first_timestamp_nanos_map_key_type,
     _parse_datatype_json_string,
 )
-from pyspark.sql.utils import get_active_spark_context, to_java_array, 
to_scala_map
+from pyspark.sql.utils import (
+    get_active_spark_context,
+    to_java_array,
+    to_scala_map,
+)

Review Comment:
   **[6] Nit: this import is only rewrapped.**
   
   No name is added to the `pyspark.sql.utils` import. The rewrap looks left 
over from the first commit, which imported the helper from `pyspark.sql.utils` 
before 91b2507 moved it. Could we keep the original line, so the diff stays 
small? #60248 has the same rewrap.
   ```suggestion
   from pyspark.sql.utils import get_active_spark_context, to_java_array, 
to_scala_map
   ```



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