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 32d21e35 [SPARK-61474][CONNECT][PYTHON] Raise PySpark's errors for the
seeds of randomSplit, sample and sampleBy that PySpark cannot send
32d21e35 is described below
commit 32d21e35361888548d06bc75501b548debae9f4d
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 09:46:25 2026 +0900
[SPARK-61474][CONNECT][PYTHON] Raise PySpark's errors for the seeds of
randomSplit, sample and sampleBy that PySpark cannot send
### What changes were proposed in this pull request?
The seeds of `randomSplit`, `sample`, `sampleBy` and `stat.sampleBy` that
PySpark cannot send now raise PySpark's errors in the Python client:
- `randomSplit` and `sample`: a seed whose `int()` is outside a long raises
`ValueError: Value out of range: <int>`, as protobuf does, instead of
`OverflowError`.
- `sampleBy` and `stat.sampleBy`: a seed that is not an int raises a bare
`AssertionError`, as PySpark's `StatSampleBy` asserts. A bool raises the
`TypeError` with which the proto refuses it, and an int out of the range of a
long raises `ValueError`. The checks of `col` and `fractions` come first, as in
PySpark.
### Why are the changes needed?
The drop-in did not match PySpark 4.3.0 for these seeds:
```python
df.randomSplit([1.0, 1.0], 2**63) # before: OverflowError: Python int too
large to convert to C long
# PySpark: ValueError: Value out of
range: 9223372036854775808
df.sampleBy("id", {0: 0.5}, 3.7) # before: TypeError: argument 'seed':
'float' object cannot be interpreted as an integer
# PySpark: AssertionError
df.sampleBy("id", {0: 0.5}, np.int64(3)) # before: accepted; PySpark:
AssertionError
df.sampleBy("id", {0: 0.5}, True) # before: accepted
# PySpark: TypeError: Cannot set
spark.connect.StatSampleBy.seed to True: True has type <class 'bool'>, but
expected one of: (int).
```
PySpark raises the `TypeError` of a bool seed and the `ValueError` of a
seed beyond a long when the plan is serialized; the drop-in raises them at the
call, as its other checks of proto fields do. This is a follow-up of
SPARK-61396 (#486).
### Does this PR introduce _any_ user-facing change?
Yes. The errors for the seeds above now match PySpark's class and message.
Valid seeds, including the bounds of a long, are unchanged.
### How was this patch tested?
A new offline test,
`test_seeds_that_pyspark_cannot_send_are_refused_as_pyspark`, which fails
without the fix and passes with it. A probe against a Spark 4.3.0 server
matched the reference client's class and message for every seed above. Also ran
the offline suite (1836 passed), the e2e sample, randomSplit, sampleBy and
dropna tests against Spark 4.3.0, the Rust library tests, the `--no-run` builds
(with and without `wasm-udf`), `cargo fmt --check`, `scripts/audit_no_stubs.sh`
and the [...]
### 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 #526 from HyukjinKwon/SPARK-61474-seeds.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/dataframe.rs | 17 +++----
crates/pyspark-rs/src/session.rs | 2 +-
crates/pyspark-rs/src/stat.rs | 27 ++++++++---
crates/pyspark-rs/src/stat_arguments.rs | 18 +++++---
python/tests/test_dropin_offline.py | 79 +++++++++++++++++++++++++++++++++
5 files changed, 122 insertions(+), 21 deletions(-)
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index c5473a34..845c0c66 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -1871,14 +1871,11 @@ impl PyDataFrame {
&self,
col: &Bound<'_, PyAny>,
fractions: &Bound<'_, PyAny>,
- seed: Option<i64>,
+ seed: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyDataFrame> {
let py = col.py();
let (col, fractions) = crate::stat::sample_by_arguments(col,
fractions)?;
- let seed = match seed {
- Some(seed) => seed,
- None => python_random_seed(py)?,
- };
+ let seed = crate::stat::sample_by_seed(py, seed)?;
Ok(PyDataFrame::new(
self.dataframe
.stat()
@@ -4501,12 +4498,12 @@ pub(crate) fn python_random_seed(py: Python<'_>) ->
PyResult<i64> {
}
/// `int(value)` of Python, as PySpark applies to a seed: a float is
truncated, a str is parsed,
-/// and a value that `int()` rejects raises its error.
+/// and a value that `int()` rejects raises its error. An int out of the range
of a long is the
+/// `ValueError` of protobuf.
pub(crate) fn python_int(py: Python<'_>, value: &Bound<'_, PyAny>) ->
PyResult<i64> {
- py.import("builtins")?
- .getattr("int")?
- .call1((value,))?
- .extract()
+ let int = py.import("builtins")?.getattr("int")?.call1((value,))?;
+ int.extract::<i64>()
+ .map_err(|_| crate::session::value_out_of_range(&int))
}
/// The collected `rows` of a result of `schema`, with configured binary
values and
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index 9232c0f9..51e5bdc8 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -4017,7 +4017,7 @@ pub(crate) fn range_arguments(
}
/// The `ValueError` of protobuf for an int out of the range of its field.
-fn value_out_of_range(int: &Bound<'_, PyAny>) -> PyErr {
+pub(crate) fn value_out_of_range(int: &Bound<'_, PyAny>) -> PyErr {
let shown = int.str().map(|text| text.to_string()).unwrap_or_default();
pyo3::exceptions::PyValueError::new_err(format!("Value out of range:
{shown}"))
}
diff --git a/crates/pyspark-rs/src/stat.rs b/crates/pyspark-rs/src/stat.rs
index 495b6368..39433527 100644
--- a/crates/pyspark-rs/src/stat.rs
+++ b/crates/pyspark-rs/src/stat.rs
@@ -5,6 +5,8 @@ use spark_connect::group::StatFunctions;
use crate::dataframe::{python_random_seed, PyDataFrame};
use crate::errors::ResultExt;
+use crate::session::value_out_of_range;
+use crate::stat_arguments::bool_not_proto_int;
/// Python wrapper for DataFrame statistical functions.
#[pyclass(
@@ -83,14 +85,11 @@ impl PyStatFunctions {
&self,
col: &Bound<'_, PyAny>,
fractions: &Bound<'_, PyAny>,
- seed: Option<i64>,
+ seed: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyDataFrame> {
let py = col.py();
let (col, fractions) = sample_by_arguments(col, fractions)?;
- let seed = match seed {
- Some(seed) => seed,
- None => python_random_seed(py)?,
- };
+ let seed = sample_by_seed(py, seed)?;
Ok(PyDataFrame::new(
self.stat.sample_by(col, fractions, Some(seed)).to_pyerr()?,
))
@@ -181,3 +180,21 @@ pub(crate) fn sample_by_arguments(
}
Ok((col, strata))
}
+
+/// The seed of `sampleBy`, drawn from Python's `random` when there is none.
As PySpark's
+/// `StatSampleBy` asserts an int, any other type is a bare `AssertionError`.
A bool, which is an
+/// int, is refused by the proto, and an int out of the range of a long is a
`ValueError`.
+pub(crate) fn sample_by_seed(py: Python<'_>, seed: Option<&Bound<'_, PyAny>>)
-> PyResult<i64> {
+ use pyo3::types::{PyBool, PyInt};
+
+ let Some(seed) = seed else {
+ return python_random_seed(py);
+ };
+ if !seed.is_instance_of::<PyInt>() {
+ return Err(pyo3::exceptions::PyAssertionError::new_err(()));
+ }
+ if seed.is_instance_of::<PyBool>() {
+ return Err(bool_not_proto_int(seed,
"spark.connect.StatSampleBy.seed"));
+ }
+ seed.extract::<i64>().map_err(|_| value_out_of_range(seed))
+}
diff --git a/crates/pyspark-rs/src/stat_arguments.rs
b/crates/pyspark-rs/src/stat_arguments.rs
index feee6081..1138e296 100644
--- a/crates/pyspark-rs/src/stat_arguments.rs
+++ b/crates/pyspark-rs/src/stat_arguments.rs
@@ -99,15 +99,23 @@ fn dropna_thresh_and_subset(
Ok((thresh, columns))
}
+/// The `TypeError` of protobuf for a bool in the int field `field`: a bool is
an int, but the
+/// proto refuses it.
+pub(crate) fn bool_not_proto_int(value: &Bound<'_, PyAny>, field: &str) ->
PyErr {
+ pyo3::exceptions::PyTypeError::new_err(format!(
+ "Cannot set {field} to {value}: {value} has type {}, but expected one
of: (int).",
+ value.get_type()
+ ))
+}
+
/// 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()
- )));
+ return Err(bool_not_proto_int(
+ thresh,
+ "spark.connect.NADrop.min_non_nulls",
+ ));
}
match thresh.extract::<i32>() {
Ok(thresh) => Ok(thresh),
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index d4768a5e..60c474e1 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -10433,6 +10433,85 @@ def
test_random_split_converts_its_seed_with_int_as_pyspark(mock_connect):
assert error.value.getCondition() == "VALUE_NOT_POSITIVE"
+def test_seeds_that_pyspark_cannot_send_are_refused_as_pyspark(mock_connect):
+ # As PySpark Connect's: randomSplit and sample take int() of the seed, and
an int out of the
+ # range of a long is the ValueError of protobuf. sampleBy's StatSampleBy
asserts an int, so
+ # a float, a str or an np.int64 is a bare AssertionError, and a bool
passes the assertion but
+ # is refused by the proto. Its checks of col and fractions come first.
+ from pyspark.errors import PySparkTypeError
+
+ spark, service = mock_connect
+ df = spark.range(10)
+
+ def split(seed):
+ return df.randomSplit([1.0, 1.0], seed)
+
+ def sample(seed):
+ return df.sample(0.5, seed)
+
+ def keyword_sample(seed):
+ return df.sample(fraction=0.5, seed=seed)
+
+ def positional_sample(seed):
+ return df.sample(False, 0.5, seed)
+
+ out_of_range = (
+ (1e30, "1000000000000000019884624838656"),
+ (2**63, "9223372036854775808"),
+ (-(2**63) - 1, "-9223372036854775809"),
+ (np.uint64(2**63), "9223372036854775808"),
+ )
+ for call in (split, sample, keyword_sample, positional_sample):
+ for seed, shown in out_of_range:
+ with pytest.raises(ValueError) as error:
+ call(seed)
+ assert type(error.value) is ValueError
+ assert str(error.value) == f"Value out of range: {shown}"
+
+ def sample_by(seed):
+ return df.sampleBy("id", {0: 0.5}, seed)
+
+ def stat_sample_by(seed):
+ return df.stat.sampleBy("id", {0: 0.5}, seed)
+
+ for call in (sample_by, stat_sample_by):
+ for seed in (3.7, np.int64(3), "3"):
+ with pytest.raises(AssertionError) as error:
+ call(seed)
+ assert type(error.value) is AssertionError
+ assert str(error.value) == ""
+ for seed in (True, False):
+ with pytest.raises(TypeError) as error:
+ call(seed)
+ assert str(error.value) == (
+ f"Cannot set spark.connect.StatSampleBy.seed to {seed}: {seed}
has type "
+ "<class 'bool'>, but expected one of: (int)."
+ )
+ for seed, shown in out_of_range[1:3]:
+ with pytest.raises(ValueError) as error:
+ call(seed)
+ assert str(error.value) == f"Value out of range: {shown}"
+ with pytest.raises(PySparkTypeError) as error:
+ df.sampleBy(1, {0: 0.5}, 3.7)
+ assert error.value.getCondition() == "NOT_EXPECTED_TYPE"
+ with pytest.raises(PySparkTypeError) as error:
+ df.sampleBy("id", [0.5], 3.7)
+ assert error.value.getCondition() == "NOT_EXPECTED_TYPE"
+
+ # The bounds of a long are valid seeds, sent as they are, by Sample.seed=5
and
+ # StatSampleBy.seed=5, of Relation.sample=12 and Relation.sample_by=107.
+ def sent_seed(dataframe, field):
+ dataframe.collect()
+ plan =
parse_message(parse_message(service.execute_requests[-1])[3][0])[1][0]
+ return parse_message(parse_message(plan)[field][0])[5][0]
+
+ assert sent_seed(df.sample(0.5, 2**63 - 1), 12) == 2**63 - 1
+ assert sent_seed(df.sampleBy("id", {0: 1.0}, 2**63 - 1), 107) == 2**63 - 1
+ assert len(df.randomSplit([1.0, 1.0], -(2**63))) == 2
+ assert df.sample(0.5, -(2**63)) is not None
+ assert df.sampleBy("id", {0: 1.0}, -(2**63)) is not None
+
+
def
test_with_metadata_and_pivot_refer_to_their_column_through_the_dataframe_as_pyspark(
mock_connect):
# As PySpark's withMetadata (self[columnName]) and pivot
(self._df[pivot_col]): the column
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]