This is an automated email from the ASF dual-hosted git repository.
dongjoon-hyun pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new 24bf9678b2ef [SPARK-61275][PYTHON] Fix wrong error type for
out-of-range approxQuantile probabilities
24bf9678b2ef is described below
commit 24bf9678b2ef1f7c25e4621d3d71085ffd9d3763
Author: Alejandro Morgante <[email protected]>
AuthorDate: Wed Nov 11 09:28:56 2026 -0800
[SPARK-61275][PYTHON] Fix wrong error type for out-of-range approxQuantile
probabilities
### What changes were proposed in this pull request?
`DataFrame.approxQuantile` (classic and Connect) validated each value in
`probabilities` with a single check combining a type test and a range test: `if
not isinstance(p, (float, int)) or p < 0 or p > 1`. This PR splits that into a
proper type check followed by a range check, and fixes several bugs that review
surfaced along the way: `NaN` silently passed the range check, `bool` was
silently accepted as `0`/`1`, and the raised exception class depended on the
order of elements in the l [...]
Validation of NaN and bool values in `relativeError` is addressed
separately in #60306 (SPARK-61372).
### Why are the changes needed?
Before this change, a validly-typed but out-of-range value raised a type
error:
```
>>> df.stat.approxQuantile("a", [1.5], 0.1)
PySparkTypeError: [NOT_EXPECTED_TYPE] Argument `probabilities` should be
list[float, int], got float.
```
`1.5` *is* a float, exactly what the message says it should be -- the real
problem is the value is out of `[0, 1]`. This is the same type/value conflation
bug fixed for streaming's `awaitTermination` timeout validation in #60215,
found while auditing the codebase for the same anti-pattern elsewhere.
Review on this PR (thanks dongjoon-hyun) caught three more bugs in the same
validation:
- `NaN` passed silently, since every comparison with `NaN` is `False` (`nan
< 0 or nan > 1` is `False`), and then failed server-side with a raw
`IllegalArgumentException` instead of a proper PySpark error.
- `bool` passed silently as `0`/`1`, since `bool` is a subclass of `int`.
- Because the type and range checks were interleaved per element,
`approxQuantile("a", [1.5, "x"], 0.1)` raised a value error while
`approxQuantile("a", ["x", 1.5], 0.1)` raised a type error for the same
underlying problems, just reordered.
### Does this PR introduce _any_ user-facing change?
Yes. Before:
```
>>> df.stat.approxQuantile("a", [1.5], 0.1)
PySparkTypeError: [NOT_EXPECTED_TYPE] ... got float.
>>> df.stat.approxQuantile("a", [float("nan")], 0.1)
IllegalArgumentException # raw, unwrapped, from the server
>>> df.stat.approxQuantile("a", [True], 0.1)
# silently treated as probability 1.0
```
After:
```
>>> df.stat.approxQuantile("a", [1.5], 0.1)
PySparkValueError: [VALUE_OUT_OF_BOUNDS] Value for `probabilities` must be
between 0 and 1 (inclusive), got 1.5
>>> df.stat.approxQuantile("a", [float("nan")], 0.1)
PySparkValueError: [VALUE_OUT_OF_BOUNDS] Value for `probabilities` must be
between 0 and 1 (inclusive), got nan
>>> df.stat.approxQuantile("a", [True], 0.1)
PySparkTypeError: [NOT_EXPECTED_TYPE] Argument `probabilities` should be
list[float, int], got bool.
```
Type errors (wrong element type) still raise `NOT_EXPECTED_TYPE` as before,
and now always take priority over range errors regardless of list order.
### How was this patch tested?
Added tests to `FunctionsTestsMixin.test_approxQuantile` in
`test_functions.py` (shared by classic and Connect via
`test_parity_functions.py`) covering: a non-numeric element, an out-of-range
element (both bounds), `NaN`, `bool`, both orderings of a mixed
type/range-invalid list, and a `tuple` input. Updated the existing Connect-only
regression test in `test_connect_stat.py` that had hard-coded the old (buggy)
expectation. Verified the shared validation function directly, including a
[...]
### Was this patch authored or co-authored using generative AI tooling?
Yes. Generated-by: Claude Code (Claude Sonnet 5)
---
This contribution is my original work and I license the work to the project
under the project's open source license.
(First-time contributors here, still learning the contribution flow --
happy to adjust anything that's off.)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Closes #60248 from
AlejandroMorgante/fix-approxquantile-type-value-conflation.
Authored-by: Alejandro Morgante
<[email protected]>
Signed-off-by: Dongjoon Hyun <[email protected]>
skip-checks: true
---
python/pyspark/sql/classic/dataframe.py | 23 +----
python/pyspark/sql/connect/dataframe.py | 23 +----
python/pyspark/sql/dataframe.py | 41 ++++++++
.../pyspark/sql/tests/connect/test_connect_stat.py | 9 +-
python/pyspark/sql/tests/test_functions.py | 111 +++++++++++++++++++++
5 files changed, 161 insertions(+), 46 deletions(-)
diff --git a/python/pyspark/sql/classic/dataframe.py
b/python/pyspark/sql/classic/dataframe.py
index 6b47a23f5135..82250b61877e 100644
--- a/python/pyspark/sql/classic/dataframe.py
+++ b/python/pyspark/sql/classic/dataframe.py
@@ -60,6 +60,7 @@ from pyspark.sql.dataframe import (
from pyspark.sql.dataframe import (
DataFrameStatFunctions as ParentDataFrameStatFunctions,
)
+from pyspark.sql.dataframe import _validate_approx_quantile_probabilities
from pyspark.sql.functions import builtin as F
from pyspark.sql.merge import MergeIntoWriter
from pyspark.sql.pandas.conversion import PandasConversionMixin
@@ -1720,27 +1721,7 @@ class DataFrame(ParentDataFrame, PandasMapOpsMixin,
PandasConversionMixin):
)
col = _to_list(self._sc, cast(List["ColumnOrName"], col))
- if not isinstance(probabilities, (list, tuple)):
- raise PySparkTypeError(
- errorClass="NOT_EXPECTED_TYPE",
- messageParameters={
- "arg_name": "probabilities",
- "expected_type": "list or tuple",
- "arg_type": type(probabilities).__name__,
- },
- )
- if isinstance(probabilities, tuple):
- probabilities = list(probabilities)
- for p in probabilities:
- if not isinstance(p, (float, int)) or p < 0 or p > 1:
- raise PySparkTypeError(
- errorClass="NOT_EXPECTED_TYPE",
- messageParameters={
- "arg_name": "probabilities",
- "expected_type": "list[float, int]",
- "arg_type": type(p).__name__,
- },
- )
+ probabilities = _validate_approx_quantile_probabilities(probabilities)
probabilities = _to_list(self._sc, cast(List["ColumnOrName"],
probabilities))
if not isinstance(relativeError, (float, int)):
diff --git a/python/pyspark/sql/connect/dataframe.py
b/python/pyspark/sql/connect/dataframe.py
index 8d76ba09e6d7..ee6268862f95 100644
--- a/python/pyspark/sql/connect/dataframe.py
+++ b/python/pyspark/sql/connect/dataframe.py
@@ -86,6 +86,7 @@ from pyspark.sql.dataframe import (
from pyspark.sql.dataframe import (
DataFrameStatFunctions as ParentDataFrameStatFunctions,
)
+from pyspark.sql.dataframe import _validate_approx_quantile_probabilities
from pyspark.sql.pandas.functions import _validate_vectorized_udf # type:
ignore[attr-defined]
from pyspark.sql.pandas.types import from_arrow_schema, to_arrow_schema
from pyspark.sql.table_arg import TableArg
@@ -1775,27 +1776,7 @@ class DataFrame(ParentDataFrame):
},
)
- if not isinstance(probabilities, (list, tuple)):
- raise PySparkTypeError(
- errorClass="NOT_EXPECTED_TYPE",
- messageParameters={
- "arg_name": "probabilities",
- "expected_type": "list or tuple",
- "arg_type": type(probabilities).__name__,
- },
- )
- if isinstance(probabilities, tuple):
- probabilities = list(probabilities)
- for p in probabilities:
- if not isinstance(p, (float, int)) or p < 0 or p > 1:
- raise PySparkTypeError(
- errorClass="NOT_EXPECTED_TYPE",
- messageParameters={
- "arg_name": "probabilities",
- "expected_type": "list[float, int]",
- "arg_type": type(p).__name__,
- },
- )
+ probabilities = _validate_approx_quantile_probabilities(probabilities)
if not isinstance(relativeError, (float, int)):
raise PySparkTypeError(
diff --git a/python/pyspark/sql/dataframe.py b/python/pyspark/sql/dataframe.py
index 908bfa5a5cd1..96d67b354068 100644
--- a/python/pyspark/sql/dataframe.py
+++ b/python/pyspark/sql/dataframe.py
@@ -78,6 +78,47 @@ if TYPE_CHECKING:
__all__ = ["DataFrame", "DataFrameNaFunctions", "DataFrameStatFunctions"]
+def _validate_approx_quantile_probabilities(probabilities: Any) ->
List[Union[float, int]]:
+ """
+ Validate the ``probabilities`` argument of ``DataFrame.approxQuantile``,
shared by the
+ classic and Connect implementations so both stay in sync. Returns it as a
``list``.
+ """
+ from pyspark.errors import PySparkTypeError, PySparkValueError
+
+ if not isinstance(probabilities, (list, tuple)):
+ raise PySparkTypeError(
+ errorClass="NOT_EXPECTED_TYPE",
+ messageParameters={
+ "arg_name": "probabilities",
+ "expected_type": "list or tuple",
+ "arg_type": type(probabilities).__name__,
+ },
+ )
+ probabilities = list(probabilities)
+ for p in probabilities:
+ if isinstance(p, bool) or not isinstance(p, (float, int)):
+ raise PySparkTypeError(
+ errorClass="NOT_EXPECTED_TYPE",
+ messageParameters={
+ "arg_name": "probabilities",
+ "expected_type": "list[float, int]",
+ "arg_type": type(p).__name__,
+ },
+ )
+ for p in probabilities:
+ if not (0 <= p <= 1):
+ raise PySparkValueError(
+ errorClass="VALUE_OUT_OF_BOUNDS",
+ messageParameters={
+ "arg_name": "probabilities",
+ "lower_bound": "0",
+ "upper_bound": "1",
+ "actual": str(p),
+ },
+ )
+ return probabilities
+
+
class DataFrame:
"""A distributed collection of data grouped into named columns.
diff --git a/python/pyspark/sql/tests/connect/test_connect_stat.py
b/python/pyspark/sql/tests/connect/test_connect_stat.py
index 51d89e5051f1..66b788ec69f0 100644
--- a/python/pyspark/sql/tests/connect/test_connect_stat.py
+++ b/python/pyspark/sql/tests/connect/test_connect_stat.py
@@ -263,18 +263,19 @@ class SparkConnectStatTests(SparkConnectSQLTestCase):
"arg_type": "float",
},
)
- with self.assertRaises(PySparkTypeError) as pe:
+ with self.assertRaises(PySparkValueError) as pe:
self.connect.read.table(self.tbl_name2).stat.approxQuantile(
["col1", "col3"], [-0.1], 0.1
)
self.check_error(
exception=pe.exception,
- errorClass="NOT_EXPECTED_TYPE",
+ errorClass="VALUE_OUT_OF_BOUNDS",
messageParameters={
- "expected_type": "list[float, int]",
"arg_name": "probabilities",
- "arg_type": "float",
+ "lower_bound": "0",
+ "upper_bound": "1",
+ "actual": "-0.1",
},
)
with self.assertRaises(PySparkTypeError) as pe:
diff --git a/python/pyspark/sql/tests/test_functions.py
b/python/pyspark/sql/tests/test_functions.py
index f4fef28e10c5..260af6692170 100644
--- a/python/pyspark/sql/tests/test_functions.py
+++ b/python/pyspark/sql/tests/test_functions.py
@@ -1634,6 +1634,117 @@ class FunctionsTestsMixin:
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(PySparkTypeError) as pe:
+ df.stat.approxQuantile("a", [0.1, "0.9"], 0.1)
+
+ self.check_error(
+ exception=pe.exception,
+ errorClass="NOT_EXPECTED_TYPE",
+ messageParameters={
+ "arg_name": "probabilities",
+ "expected_type": "list[float, int]",
+ "arg_type": "str",
+ },
+ )
+
+ with self.assertRaises(PySparkValueError) as pe:
+ df.stat.approxQuantile("a", [0.1, 1.5], 0.1)
+
+ self.check_error(
+ exception=pe.exception,
+ errorClass="VALUE_OUT_OF_BOUNDS",
+ messageParameters={
+ "arg_name": "probabilities",
+ "lower_bound": "0",
+ "upper_bound": "1",
+ "actual": "1.5",
+ },
+ )
+
+ with self.assertRaises(PySparkValueError) as pe:
+ df.stat.approxQuantile("a", [0.1, -0.1], 0.1)
+
+ self.check_error(
+ exception=pe.exception,
+ errorClass="VALUE_OUT_OF_BOUNDS",
+ messageParameters={
+ "arg_name": "probabilities",
+ "lower_bound": "0",
+ "upper_bound": "1",
+ "actual": "-0.1",
+ },
+ )
+
+ with self.assertRaises(PySparkValueError) as pe:
+ df.stat.approxQuantile("a", [0.1, float("nan")], 0.1)
+
+ self.check_error(
+ exception=pe.exception,
+ errorClass="VALUE_OUT_OF_BOUNDS",
+ messageParameters={
+ "arg_name": "probabilities",
+ "lower_bound": "0",
+ "upper_bound": "1",
+ "actual": "nan",
+ },
+ )
+
+ with self.assertRaises(PySparkTypeError) as pe:
+ df.stat.approxQuantile("a", [0.1, True], 0.1)
+
+ self.check_error(
+ exception=pe.exception,
+ errorClass="NOT_EXPECTED_TYPE",
+ messageParameters={
+ "arg_name": "probabilities",
+ "expected_type": "list[float, int]",
+ "arg_type": "bool",
+ },
+ )
+
+ # A value error earlier in the list must not hide a type error later
in the list:
+ # types are validated for every element before any value is checked,
regardless
+ # of which order the bad elements appear in.
+ with self.assertRaises(PySparkTypeError) as pe:
+ df.stat.approxQuantile("a", [1.5, "0.9"], 0.1)
+
+ self.check_error(
+ exception=pe.exception,
+ errorClass="NOT_EXPECTED_TYPE",
+ messageParameters={
+ "arg_name": "probabilities",
+ "expected_type": "list[float, int]",
+ "arg_type": "str",
+ },
+ )
+
+ with self.assertRaises(PySparkTypeError) as pe:
+ df.stat.approxQuantile("a", ["0.9", 1.5], 0.1)
+
+ self.check_error(
+ exception=pe.exception,
+ errorClass="NOT_EXPECTED_TYPE",
+ messageParameters={
+ "arg_name": "probabilities",
+ "expected_type": "list[float, int]",
+ "arg_type": "str",
+ },
+ )
+
+ with self.assertRaises(PySparkValueError) as pe:
+ df.stat.approxQuantile("a", (0.1, 1.5), 0.1)
+
+ self.check_error(
+ exception=pe.exception,
+ errorClass="VALUE_OUT_OF_BOUNDS",
+ messageParameters={
+ "arg_name": "probabilities",
+ "lower_bound": "0",
+ "upper_bound": "1",
+ "actual": "1.5",
+ },
+ )
+
def test_sorting_functions_with_column(self):
self.check_sorting_functions_with_column(Column)
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]