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 fba24c02 [SPARK-61396][CONNECT][PYTHON] Accept a float or str seed in 
randomSplit of the Python client, as PySpark does
fba24c02 is described below

commit fba24c0222783fe0297fc396d0d73e7a8965f73f
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 09:13:46 2026 +0900

    [SPARK-61396][CONNECT][PYTHON] Accept a float or str seed in randomSplit of 
the Python client, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61396](https://issues.apache.org/jira/browse/SPARK-61396): a 
follow-up of #449 (SPARK-61288), from a review of it. `DataFrame.randomSplit` 
of the Python client converts a given seed with `int()`, as PySpark's does, 
after the check of the weights, as the reference's plan does. A float seed is 
truncated, a str is parsed, and a value that `int()` rejects raises its error. 
`sample` shares the same conversion (one `python_int` helper). `sampleBy` and 
`stat.sampleBy` are unchanged: P [...]
    
    ### Why are the changes needed?
    
    ```python
    df.randomSplit([1.0, 1.0], 1.5)
    # before: TypeError: argument 'seed': 'float' object cannot be interpreted 
as an integer
    # after:  the splits of seed 1, as PySpark 4.3.0 gives them
    df.randomSplit([1.0, 1.0], "3")      # the splits of seed 3, as PySpark
    df.randomSplit([1.0, 1.0], "3.5")    # ValueError: invalid literal for 
int() with base 10, as PySpark
    ```
    
    `sample(0.5, 1.5)` already worked in both clients.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. `randomSplit` accepts a float or str seed, as PySpark does. Int seeds 
are unchanged.
    
    ### How was this patch tested?
    
    - An offline test, 
`test_random_split_converts_its_seed_with_int_as_pyspark`: the Sample relations 
for `1.5` and `"1"` equal those for `1`, `"3.5"` raises `ValueError`, and a bad 
sum with a bad seed raises `VALUE_NOT_POSITIVE` first.
    - An e2e test against a Spark 4.3.0 server: the splits of `3.7` and `"3"` 
equal those of `3`.
    - Both fail without the change. `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` and the drop-in suites pass.
    
    ### 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 #486 from HyukjinKwon/SPARK-61396-randomsplit-float-seed.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/dataframe.rs  | 27 +++++++++++++++++----------
 python/tests/test_dropin_e2e.py     | 15 +++++++++++++++
 python/tests/test_dropin_offline.py | 26 ++++++++++++++++++++++++++
 3 files changed, 58 insertions(+), 10 deletions(-)

diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index 87ffa1e6..d062fec6 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -1985,12 +1985,13 @@ impl PyDataFrame {
 
     /// Randomly split into multiple DataFrames by the given weights.
     /// As PySpark's: `VALUE_NOT_POSITIVE` for a negative weight and for 
weights of a sum that is
-    /// not positive, of their `str`; without a seed, the client chooses one 
of every split.
+    /// not positive, of their `str`; without a seed, the client chooses one 
of every split; a
+    /// seed goes through `int()`, so a float or a str is accepted.
     #[pyo3(name = "randomSplit", signature = (weights, seed=None))]
     fn random_split(
         &self,
         weights: &Bound<'_, PyAny>,
-        seed: Option<i64>,
+        seed: Option<&Bound<'_, PyAny>>,
     ) -> PyResult<Vec<PyDataFrame>> {
         let py = weights.py();
         let not_positive = |arg_name: &str, value: &Bound<'_, PyAny>| -> 
PyResult<PyErr> {
@@ -2014,13 +2015,15 @@ impl PyDataFrame {
         }
         // Drawn before the sum is checked, as PySpark does, so that a failing 
sum uses one too.
         let seed = match seed {
-            Some(seed) => seed,
-            None => python_random_seed(py)?,
+            Some(seed) => seed.clone(),
+            None => python_random_seed(py)?.into_pyobject(py)?.into_any(),
         };
         let total = py.import("builtins")?.call_method1("sum", (weights,))?;
         if total.le(0)? {
             return Err(not_positive("sum(weights)", &total)?);
         }
+        // Converted once the sum is checked, as PySpark's plans do with 
int(seed).
+        let seed = python_int(py, &seed)?;
         let weights: Vec<f64> = weights.extract()?;
         Ok(self
             .dataframe
@@ -2605,12 +2608,7 @@ impl PyDataFrame {
         seed: Option<&Bound<'_, PyAny>>,
     ) -> PyResult<PyDataFrame> {
         use pyo3::types::{PyBool, PyFloat};
-        let int = |value: &Bound<'_, PyAny>| -> PyResult<i64> {
-            py.import("builtins")?
-                .getattr("int")?
-                .call1((value,))?
-                .extract()
-        };
+        let int = |value: &Bound<'_, PyAny>| python_int(py, value);
         let (replace, frac, seed) = match (withReplacement, fraction) {
             (Some(w), Some(f)) if w.is_instance_of::<PyBool>() && 
f.is_instance_of::<PyFloat>() => {
                 (w.extract()?, f.extract()?, seed.map(int).transpose()?)
@@ -4531,6 +4529,15 @@ pub(crate) fn python_random_seed(py: Python<'_>) -> 
PyResult<i64> {
         .extract()
 }
 
+/// `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.
+pub(crate) fn python_int(py: Python<'_>, value: &Bound<'_, PyAny>) -> 
PyResult<i64> {
+    py.import("builtins")?
+        .getattr("int")?
+        .call1((value,))?
+        .extract()
+}
+
 /// The collected `rows` of a result of `schema`, with configured binary 
values and
 /// user-defined values materialized before constructing the tuples returned 
to Python.
 /// Reads the binary setting after execution, including with only an Arrow 
schema.
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 728310ad..11ba614a 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -4424,6 +4424,21 @@ def 
test_samples_and_splits_take_a_seed_of_the_client_as_pyspark(session):
     assert df.withMetadata("id", metadata).schema["id"].metadata == metadata
 
 
+def 
test_random_split_seed_of_a_float_or_str_is_converted_with_int_as_pyspark(session):
+    # As PySpark's randomSplit: the seed goes through int(), so a float seed 
splits as its
+    # truncation and a str seed as its int, and a str that int() rejects 
raises its ValueError.
+    df = session.range(0, 2000, 1, 8)
+
+    def ids(part):
+        return sorted(row.id for row in part.collect())
+
+    expected = [ids(part) for part in df.randomSplit([0.5, 0.5], 3)]
+    assert [ids(part) for part in df.randomSplit([0.5, 0.5], 3.7)] == expected
+    assert [ids(part) for part in df.randomSplit([0.5, 0.5], "3")] == expected
+    with pytest.raises(ValueError, match="invalid literal for int"):
+        df.randomSplit([0.5, 0.5], "3.5")
+
+
 def 
test_answers_that_pyspark_keeps_are_asked_once_per_dataframe_as_pyspark(session):
     # As PySpark's isStreaming (a cached_property), semanticHash, isEmpty and 
inputFiles
     # (functools.cache): a DataFrame keeps the server's first answer, so a 
redefined view or a
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 91cbd3c3..8030a950 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -9885,6 +9885,32 @@ def 
test_sample_split_and_sample_by_draw_their_seed_from_python_random_as_pyspar
     assert seed_of(df.stat.sampleBy("id", {0: 1.0}, 7), 107) == 7
 
 
+def test_random_split_converts_its_seed_with_int_as_pyspark(mock_connect):
+    # As PySpark Connect's randomSplit: the seed goes through int() in each 
Sample, so a float
+    # is truncated and a str is parsed, and the splits are those of the int 
seed. A str that
+    # int() rejects raises its ValueError, after the weights are checked.
+    from pyspark.errors import PySparkValueError
+
+    spark, service = mock_connect
+    df = spark.range(10)
+
+    def sample_of(dataframe):
+        # The Sample relation (field 12) of the plan of the last request.
+        dataframe.collect()
+        plan = 
parse_message(parse_message(service.execute_requests[-1])[3][0])[1][0]
+        return parse_message(plan)[12][0]
+
+    expected = [sample_of(split) for split in df.randomSplit([1.0, 1.0], 1)]
+    assert [sample_of(split) for split in df.randomSplit([1.0, 1.0], 1.5)] == 
expected
+    assert [sample_of(split) for split in df.randomSplit([1.0, 1.0], "1")] == 
expected
+    assert [parse_message(sample)[5][0] for sample in expected] == [1, 1]
+    with pytest.raises(ValueError, match="invalid literal for int"):
+        df.randomSplit([1.0, 1.0], "3.5")
+    with pytest.raises(PySparkValueError) as error:
+        df.randomSplit([0.0, 0.0], "3.5")
+    assert error.value.getCondition() == "VALUE_NOT_POSITIVE"
+
+
 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]

Reply via email to