This is an automated email from the ASF dual-hosted git repository.
HyukjinKwon pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git
The following commit(s) were added to refs/heads/master by this push:
new 14375b99 [SPARK-61394][CONNECT][PYTHON] Reject a bool or out-of-range
thresh in dropna as PySpark does, and name VariantVal in the error of a pivot
value
14375b99 is described below
commit 14375b99ddc63a47485d5db4f33bf9ec3dd09217
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 09:14:57 2026 +0900
[SPARK-61394][CONNECT][PYTHON] Reject a bool or out-of-range thresh in
dropna as PySpark does, and name VariantVal in the error of a pivot value
### What changes were proposed in this pull request?
[SPARK-61394](https://issues.apache.org/jira/browse/SPARK-61394): a
follow-up of #441 (SPARK-61320), from a review of it.
- `df.dropna(thresh=...)` and `df.na.drop(thresh=...)` of the Python client
refuse a bool `thresh` and an int outside the 32-bit range, with the errors
that PySpark's protobuf raises for them
(`crates/pyspark-rs/src/stat_arguments.rs`). The subset is checked first, as in
the reference.
- The Rust API's pivot error names a Variant value `VariantVal`, PySpark's
class, as the fill path already does (`crates/spark-connect/src/group.rs`).
- A decimal pivot value of the Rust API whose scale overflows
(`1E-2147483648`) takes the default type (10, 0), as the other invalid texts
do, instead of overflowing the scale computation (a panic in debug builds, a
wrapped scale in release).
### Why are the changes needed?
A Python bool is an int, so `df.dropna(thresh=True)` was treated as
`thresh=1` and returned rows, and `df.dropna(thresh=2**40)` raised
`OverflowError`. PySpark 4.3.0 raises:
```
df.dropna(thresh=True) # TypeError: Cannot set
spark.connect.NADrop.min_non_nulls to True: True has type <class 'bool'>, but
expected one of: (int).
df.dropna(thresh=2**40) # ValueError: Value out of range: 1099511627776
```
The drop-in now raises the same errors. PySpark raises them when the plan
is serialized (at the action), while the drop-in raises them at the `dropna`
call, as it does for its other argument errors.
### Does this PR introduce _any_ user-facing change?
Yes. A bool or out-of-range `thresh` in `dropna` and `na.drop` raises the
reference's TypeError or ValueError, instead of returning rows or raising
OverflowError. The Rust API's pivot error says `VariantVal` instead of
`Variant`.
### How was this patch tested?
- An offline test,
`test_dropna_thresh_that_the_proto_refuses_is_refused_as_pyspark`, for `dropna`
and `na.drop` with a bool, out-of-range values and the int32 bounds, the
subset-first order, and `how="all"`, with the reference's messages. It fails
without the change.
- Rust unit tests:
`a_decimal_pivot_value_whose_scale_overflows_takes_the_default_type`, and
`a_null_or_a_nested_pivot_value_is_not_expected_type` extended with the Struct
and Variant cases.
- `cargo test -p apache-spark-connect -p apache-spark-connect-core
--release --lib`, the `--no-run` builds, `cargo fmt --check`,
`scripts/audit_no_stubs.sh`, the offline drop-in suite, and the drop-in and
Rust e2e suites against a Spark 4.3.0 server.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5
This pull request and its description were written by Isaac.
Closes #484 from HyukjinKwon/SPARK-61394-dropna-thresh-pivot-names.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/stat_arguments.rs | 30 ++++++++++++++---
crates/spark-connect/src/group.rs | 58 ++++++++++++++++++++++++++++++---
python/tests/test_dropin_offline.py | 36 ++++++++++++++++++++
3 files changed, 116 insertions(+), 8 deletions(-)
diff --git a/crates/pyspark-rs/src/stat_arguments.rs
b/crates/pyspark-rs/src/stat_arguments.rs
index 8683484d..734c5115 100644
--- a/crates/pyspark-rs/src/stat_arguments.rs
+++ b/crates/pyspark-rs/src/stat_arguments.rs
@@ -2,7 +2,7 @@
//! ...), which check their arguments on the client as PySpark Connect's
DataFrame does.
use pyo3::prelude::*;
-use pyo3::types::{PyDict, PyFloat, PyInt, PyList, PyString, PyTuple};
+use pyo3::types::{PyBool, PyDict, PyFloat, PyInt, PyList, PyString, PyTuple};
use spark_connect::dataframe::DataFrame;
use spark_connect::group::StatFunctions;
@@ -101,17 +101,39 @@ pub(crate) fn dropna(
Ok(PyDataFrame::new(dataframe))
}
-/// The `thresh` and the `subset` of `dropna`, checked as PySpark's.
+/// The `thresh` and the `subset` of `dropna`, checked as PySpark's. The
`subset` is checked
+/// before the `thresh` is sent as a proto int, which [`proto_int32`] checks.
fn dropna_thresh_and_subset(
thresh: Option<&Bound<'_, PyAny>>,
subset: Option<&Bound<'_, PyAny>>,
) -> PyResult<(Option<i32>, Vec<String>)> {
let thresh = match thresh {
None => None,
- Some(thresh) if thresh.is_instance_of::<PyInt>() =>
Some(thresh.extract::<i32>()?),
+ Some(thresh) if thresh.is_instance_of::<PyInt>() => Some(thresh),
Some(thresh) => return Err(not_expected_type(thresh, "thresh", "int")),
};
- Ok((thresh, subset_columns(subset, "list, str or tuple")?))
+ let columns = subset_columns(subset, "list, str or tuple")?;
+ let thresh = thresh.map(proto_int32).transpose()?;
+ Ok((thresh, columns))
+}
+
+/// An int, the `thresh` of `dropna`, as the proto's int32. A bool, which is
an int, is refused as
+/// the proto refuses it, `TypeError`, and an int out of the range of an int32
is a `ValueError`.
+fn proto_int32(thresh: &Bound<'_, PyAny>) -> PyResult<i32> {
+ if thresh.is_instance_of::<PyBool>() {
+ return Err(pyo3::exceptions::PyTypeError::new_err(format!(
+ "Cannot set spark.connect.NADrop.min_non_nulls to {thresh}:
{thresh} has type {}, \
+ but expected one of: (int).",
+ thresh.get_type()
+ )));
+ }
+ match thresh.extract::<i32>() {
+ Ok(thresh) => Ok(thresh),
+ Err(_) => Err(pyo3::exceptions::PyValueError::new_err(format!(
+ "Value out of range: {}",
+ thresh.str()?
+ ))),
+ }
}
/// `df.fillna(value, subset)` and `df.na.fill`, as PySpark's: `value` is a
bool, an int, a
diff --git a/crates/spark-connect/src/group.rs
b/crates/spark-connect/src/group.rs
index e071b952..73e92e44 100644
--- a/crates/spark-connect/src/group.rs
+++ b/crates/spark-connect/src/group.rs
@@ -57,7 +57,7 @@ fn value_to_lit_expr(v: crate::row::Value) ->
Result<Expression> {
Value::List(_) => return Err(not_a_pivot_value("list")),
Value::Map(_) => return Err(not_a_pivot_value("dict")),
Value::Struct(_) => return Err(not_a_pivot_value("Row")),
- Value::Variant { .. } => return Err(not_a_pivot_value("Variant")),
+ Value::Variant { .. } => return Err(not_a_pivot_value("VariantVal")),
};
Ok(Expression::literal(lit))
}
@@ -82,8 +82,8 @@ const PIVOT_VALUE_TYPES: &str =
"a bool, a number, a string, bytes, a date, a timestamp, a time or an
interval";
/// The precision and scale of a decimal text, such as `"1.50"` (3 and 2) or
`"1E+3"` (1 and -3),
-/// as Java's `BigDecimal` of the text has them. Text that is not a decimal
gives `(10, 0)`, and
-/// the server rejects it.
+/// as Java's `BigDecimal` of the text has them. Text that is not a decimal,
or whose scale does
+/// not fit an int, gives `(10, 0)`, and the server rejects it.
fn decimal_type_of_text(text: &str) -> (i32, i32) {
let (mantissa, exponent) = match text.split_once(['e', 'E']) {
Some((mantissa, exponent)) => (mantissa, exponent.parse::<i32>().ok()),
@@ -100,7 +100,10 @@ fn decimal_type_of_text(text: &str) -> (i32, i32) {
}
let unscaled = digits.trim_start_matches('0');
let precision = unscaled.len().max(1) as i32;
- (precision, frac_part.len() as i32 - exponent)
+ match (frac_part.len() as i32).checked_sub(exponent) {
+ Some(scale) => (precision, scale),
+ None => (10, 0),
+ }
}
/// Grouped data for performing aggregations.
@@ -1285,6 +1288,40 @@ mod tests {
assert_eq!(literals[7], decimal("1E+3", 1, -3));
}
+ #[test]
+ fn a_decimal_pivot_value_whose_scale_overflows_takes_the_default_type() {
+ use crate::row::Value;
+ use spark_connect_proto::{expression::literal::LiteralType,
relation::RelType};
+ // The scale of each text, its fraction's digits less its exponent, is
past the greatest
+ // int, so the text is not a decimal of an int scale, and takes the
default type.
+ let values = ["1E-2147483648", "1.5E-2147483647"]
+ .into_iter()
+ .map(|value| Value::Decimal {
+ value: value.to_string(),
+ precision: None,
+ scale: None,
+ })
+ .collect();
+ let frame = session().range(1).unwrap();
+ let pivot = frame
+ .group_by(vec![] as Vec<Column>)
+ .pivot(crate::column::col("value"), Some(values))
+ .unwrap()
+ .count();
+ let Some(RelType::Aggregate(aggregate)) =
pivot.plan.to_proto().rel_type else {
+ panic!("expected Aggregate");
+ };
+ let literals = aggregate.pivot.unwrap().values;
+ assert_eq!(literals.len(), 2);
+ for literal in literals {
+ assert!(matches!(
+ literal.literal_type,
+ Some(LiteralType::Decimal(ref decimal))
+ if decimal.precision == Some(10) && decimal.scale ==
Some(0)
+ ));
+ }
+ }
+
#[test]
fn a_null_or_a_nested_pivot_value_is_not_expected_type() {
use crate::row::Value;
@@ -1293,6 +1330,19 @@ mod tests {
(Value::Null, "NoneType"),
(Value::List(vec![]), "list"),
(Value::Map(vec![]), "dict"),
+ (
+ Value::Struct(
+ crate::row::Row::new(vec!["n".into()],
vec![Value::Integer(1)]).into(),
+ ),
+ "Row",
+ ),
+ (
+ Value::Variant {
+ value: vec![0x0c, 0x01],
+ metadata: vec![0x01, 0x00, 0x00],
+ },
+ "VariantVal",
+ ),
] {
let err = frame
.group_by(vec![] as Vec<Column>)
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 8030a950..48374228 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -3662,6 +3662,42 @@ def
test_na_and_stat_functions_check_their_arguments_as_pyspark():
assert error.value.getMessageParameters() == parameters
+def test_dropna_thresh_that_the_proto_refuses_is_refused_as_pyspark():
+ # As PySpark sends `thresh` as a proto int, after it checks `how` and
`subset`: a bool, which
+ # is an int, is a TypeError, and an int out of the range of an int32 a
ValueError.
+ from pyspark.errors import PySparkTypeError
+ from pyspark.sql import DataFrame
+
+ df = _offline_session().range(1)
+ cases = (
+ (lambda: df.dropna(thresh=True), TypeError,
+ "Cannot set spark.connect.NADrop.min_non_nulls to True: True has type
<class 'bool'>, "
+ "but expected one of: (int)."),
+ (lambda: df.na.drop(thresh=False), TypeError,
+ "Cannot set spark.connect.NADrop.min_non_nulls to False: False has
type <class 'bool'>, "
+ "but expected one of: (int)."),
+ (lambda: df.dropna(thresh=True, subset=["id"]), TypeError,
+ "Cannot set spark.connect.NADrop.min_non_nulls to True: True has type
<class 'bool'>, "
+ "but expected one of: (int)."),
+ (lambda: df.dropna(thresh=2**40), ValueError, "Value out of range:
1099511627776"),
+ (lambda: df.na.drop(thresh=-(2**31) - 1), ValueError, "Value out of
range: -2147483649"),
+ (lambda: df.dropna(how="all", thresh=2**40), ValueError,
+ "Value out of range: 1099511627776"),
+ )
+ for call, error_type, message in cases:
+ with pytest.raises(error_type) as error:
+ call()
+ assert type(error.value) is error_type
+ assert str(error.value) == message
+ # The `subset` is checked before the `thresh` is sent.
+ with pytest.raises(PySparkTypeError) as error:
+ df.dropna(thresh=True, subset=1)
+ assert error.value.getCondition() == "NOT_EXPECTED_TYPE"
+ # The bounds of an int32 are those of the proto.
+ assert isinstance(df.dropna(thresh=2**31 - 1), DataFrame)
+ assert isinstance(df.na.drop(thresh=-(2**31)), DataFrame)
+
+
def test_avro_protobuf_partitioning_submodules():
# The official import paths resolve (the implementations live in
# pyspark.sql.functions and are re-exported here).
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]