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 62e11ad5 [SPARK-61288][CONNECT][PYTHON] Draw the seeds of sample, 
randomSplit and sampleBy from Python's random in the Python client, as PySpark 
does
62e11ad5 is described below

commit 62e11ad554029f7992d994277a676650dfad3664
Author: Timothy Meehan <[email protected]>
AuthorDate: Tue Nov 10 10:29:24 2026 +0900

    [SPARK-61288][CONNECT][PYTHON] Draw the seeds of sample, randomSplit and 
sampleBy from Python's random in the Python client, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    The Python client (`crates/pyspark-rs`) now draws the seed of 
`DataFrame.sample`, `DataFrame.randomSplit`, `DataFrame.sampleBy` and 
`DataFrameStatFunctions.sampleBy` from Python's `random` when the caller gives 
none, as PySpark 4.3.0's Spark Connect client does:
    
    - `python_random_seed` in `crates/pyspark-rs/src/dataframe.rs` calls 
`random.randint(0, sys.maxsize)`, the same call PySpark makes.
    - `sample` draws in the branches that PySpark's `_preapare_args_for_sample` 
draws in, after the arguments are matched, so a call that raises draws nothing.
    - `randomSplit` draws after the negative-weight check and before the sum 
check, as PySpark does, so a sum that is not positive uses one draw and a 
negative weight uses none.
    - `sampleBy` (both entry points) draws after `sample_by_arguments` 
validates its arguments.
    
    An explicit seed is sent as given and draws nothing. The core's Rust API 
default seed in `crates/spark-connect` is unchanged.
    
    ### Why are the changes needed?
    
    Without a seed, the Python client took a UUID-based seed for `sample` and 
`randomSplit`, and sent none for `sampleBy`. So `random.seed(...)` had no 
effect on their rows, and two processes returned different rows for the same 
seed. PySpark 4.3.0 returns the same rows, and this change makes the drop-in do 
the same.
    
    Repro against an OSS Spark 4.3.0 Connect server on loopback, 
`random.seed(42)` before each call, run in two processes each:
    
    - Before: `sample(0.5)` gave `[2, 3, 8, 10, ...]` and then `[1, 2, 3, 4, 
...]`; `randomSplit` and `sampleBy` differed between processes too.
    - After: `sample`, `randomSplit` and `sampleBy` give the same rows in both 
processes, and the same rows as the reference client: `[1, 2, 5, 7, 11, 12, 14, 
15, 17, 19, 26, 29, 34, 35, 38]` for `sample` and for `sampleBy`, and the same 
two splits for `randomSplit`.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, in the Python client only. Without a seed, `sample`, `randomSplit` and 
`sampleBy` now return the same rows for the same `random.seed(...)`, as PySpark 
does, instead of different rows in each process. The rows of a call with an 
explicit seed are unchanged. The Rust API is unchanged.
    
    ### How was this patch tested?
    
    - Offline, `python/tests/test_dropin_offline.py`: 
`test_sample_split_and_sample_by_draw_their_seed_from_python_random_as_pyspark`.
 After `random.seed(42)`, the seed of each call in a fixed order equals the 
draw of `random.randint(0, sys.maxsize)` in that order. It also checks that an 
explicit seed draws nothing, that a `randomSplit` whose sum is not positive 
uses one draw, and that a negative weight uses none. The expected draws come 
from Python's `random` in the test. It fails on the [...]
    - Live, `python/tests/test_dropin_e2e.py`: 
`test_sample_split_and_sample_by_without_a_seed_follow_python_random_as_pyspark`.
 It runs the same script in two new interpreters and checks that both give the 
rows of the reference client. It fails on the previous code.
    - Reference check: the same call sequence on PySpark 4.3.0 gives the same 
seeds that the offline test expects, and the same rows as the e2e test.
    - `cargo test -p apache-spark-connect --release --lib`: 528 passed.
    - `cargo test -p apache-spark-connect --release --no-run` and `--features 
wasm-udf --no-run`: compile.
    - `cargo fmt --all --check`: passes.
    - `cargo clippy --workspace --all-targets --release --message-format 
short`: fails with pre-existing diagnostics in files this change does not 
touch; none are on lines changed here.
    - Offline Python (`test_dropin_offline.py`, `test_ml_offline.py`, 
`test_arrow_handoff.py`): 2928 passed, 8 skipped.
    - Live Python (`test_arrow_e2e.py`, `test_dropin_e2e.py`, 
`test_ml_e2e.py`): 237 passed, 1 skipped.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5 and Claude Haiku 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #449 from tdcmeehan/SPARK-61288-seeds-from-python-random.
    
    Lead-authored-by: Timothy Meehan <[email protected]>
    Co-authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/dataframe.rs  | 44 ++++++++++++++++++++++++++++-------
 crates/pyspark-rs/src/stat.rs       | 13 +++++++++--
 python/tests/test_dropin_e2e.py     | 46 +++++++++++++++++++++++++++++++++++++
 python/tests/test_dropin_offline.py | 34 +++++++++++++++++++++++++++
 4 files changed, 127 insertions(+), 10 deletions(-)

diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index e7532f8e..18797457 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -1821,7 +1821,8 @@ impl PyDataFrame {
         crate::stat_arguments::cov(py, &self.dataframe.stat(), col1, col2)
     }
 
-    /// Stratified sample without replacement per key.
+    /// Stratified sample without replacement per key. Without a seed, the 
client draws one
+    /// from Python's `random`, as PySpark Connect's `sampleBy` does.
     #[pyo3(name = "sampleBy", signature = (col, fractions, seed=None))]
     fn sample_by(
         &self,
@@ -1829,10 +1830,17 @@ impl PyDataFrame {
         fractions: &Bound<'_, PyAny>,
         seed: Option<i64>,
     ) -> PyResult<PyDataFrame> {
+        let py = col.py();
         let (col, fractions) = crate::stat::sample_by_arguments(col, 
fractions)?;
-        Ok(PyDataFrame::new(
-            self.dataframe.stat().sample_by(col, fractions, seed),
-        ))
+        let seed = match seed {
+            Some(seed) => seed,
+            None => python_random_seed(py)?,
+        };
+        Ok(PyDataFrame::new(self.dataframe.stat().sample_by(
+            col,
+            fractions,
+            Some(seed),
+        )))
     }
 
     /// Replace values, as PySpark's `DataFrame.replace`: `to_replace` is a 
{old: new} dict, or
@@ -1920,6 +1928,11 @@ impl PyDataFrame {
                 return Err(not_positive("weights", &weight)?);
             }
         }
+        // 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)?,
+        };
         let total = py.import("builtins")?.call_method1("sum", (weights,))?;
         if total.le(0)? {
             return Err(not_positive("sum(weights)", &total)?);
@@ -1927,7 +1940,7 @@ impl PyDataFrame {
         let weights: Vec<f64> = weights.extract()?;
         Ok(self
             .dataframe
-            .random_split(weights, seed)
+            .random_split(weights, Some(seed))
             .to_pyerr()?
             .into_iter()
             .map(PyDataFrame::new)
@@ -2521,9 +2534,15 @@ impl PyDataFrame {
                 ));
             }
         };
-        Ok(PyDataFrame::new(
-            self.dataframe.sample_opt(frac, replace, seed),
-        ))
+        let seed = match seed {
+            Some(seed) => seed,
+            None => python_random_seed(py)?,
+        };
+        Ok(PyDataFrame::new(self.dataframe.sample_opt(
+            frac,
+            replace,
+            Some(seed),
+        )))
     }
 
     /// Check if the DataFrame is empty.
@@ -4355,6 +4374,15 @@ fn read_binary_as_bytes(py: Python<'_>, dataframe: 
&DataFrame) -> PyResult<bool>
     Ok(value.is_some_and(|value| value.eq_ignore_ascii_case("true")))
 }
 
+/// The seed of a sample without one, drawn from Python's `random` as PySpark's
+/// `random.randint(0, sys.maxsize)`, so that `random.seed` makes the rows 
repeat.
+pub(crate) fn python_random_seed(py: Python<'_>) -> PyResult<i64> {
+    let max_size = py.import("sys")?.getattr("maxsize")?;
+    py.import("random")?
+        .call_method1("randint", (0, max_size))?
+        .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/crates/pyspark-rs/src/stat.rs b/crates/pyspark-rs/src/stat.rs
index d95f58da..d64f555c 100644
--- a/crates/pyspark-rs/src/stat.rs
+++ b/crates/pyspark-rs/src/stat.rs
@@ -3,7 +3,7 @@
 use pyo3::prelude::*;
 use spark_connect::group::StatFunctions;
 
-use crate::dataframe::PyDataFrame;
+use crate::dataframe::{python_random_seed, PyDataFrame};
 
 /// Python wrapper for DataFrame statistical functions.
 #[pyclass(
@@ -84,8 +84,17 @@ impl PyStatFunctions {
         fractions: &Bound<'_, PyAny>,
         seed: Option<i64>,
     ) -> PyResult<PyDataFrame> {
+        let py = col.py();
         let (col, fractions) = sample_by_arguments(col, fractions)?;
-        Ok(PyDataFrame::new(self.stat.sample_by(col, fractions, seed)))
+        let seed = match seed {
+            Some(seed) => seed,
+            None => python_random_seed(py)?,
+        };
+        Ok(PyDataFrame::new(self.stat.sample_by(
+            col,
+            fractions,
+            Some(seed),
+        )))
     }
 
     /// Approximate quantiles of a column, or of each of a list or tuple of 
columns, at the
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 7a5f3b97..b882bdad 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -4064,6 +4064,52 @@ 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_sample_split_and_sample_by_without_a_seed_follow_python_random_as_pyspark(
+        session, tmp_path):
+    # As PySpark's: without a seed, sample, randomSplit and sampleBy draw one 
from Python's
+    # random, so random.seed(42) gives the same rows in every process. The 
rows are those of
+    # the reference client for the same seed. The rows of a sample depend on 
the partitions,
+    # so the ranges have 4 of their own rather than the server's default 
parallelism.
+    import json
+    import subprocess
+    import sys
+
+    script = tmp_path / "seeded_rows.py"
+    script.write_text(
+        "import json, os, random\n"
+        "from pyspark.sql import SparkSession\n"
+        "spark = 
SparkSession.builder.remote(os.environ['SPARK_REMOTE']).getOrCreate()\n"
+        "df = spark.range(0, 40, 1, 4)\n"
+        "def ids(frame):\n"
+        "    return sorted(row.id for row in frame.collect())\n"
+        "random.seed(42)\n"
+        "sample = ids(df.sample(0.5))\n"
+        "random.seed(42)\n"
+        "splits = [ids(part) for part in df.randomSplit([0.5, 0.5])]\n"
+        "stratified = spark.range(0, 40, 1, 4).selectExpr('id', 'id % 3 AS 
k')\n"
+        "random.seed(42)\n"
+        "by = ids(stratified.sampleBy('k', {0: 0.5, 1: 0.5, 2: 0.5}))\n"
+        "print(json.dumps([sample, *splits, by]))\n"
+        "spark.stop()\n")
+
+    def rows():
+        result = subprocess.run(
+            [sys.executable, str(script)], env=os.environ, 
capture_output=True, text=True,
+            timeout=300)
+        assert result.returncode == 0, result.stderr
+        return json.loads(result.stdout.splitlines()[-1])
+
+    expected = [
+        [1, 2, 3, 8, 9, 10, 12, 13, 14, 16, 17, 19, 20, 21, 23, 25, 26, 32, 
36, 37],
+        [1, 2, 3, 8, 9, 10, 12, 13, 14, 16, 17, 19, 20, 21, 23, 25, 26, 32, 
36, 37],
+        [0, 4, 5, 6, 7, 11, 15, 18, 22, 24, 27, 28, 29, 30, 31, 33, 34, 35, 
38, 39],
+        [1, 2, 3, 8, 9, 10, 12, 13, 14, 16, 17, 19, 20, 21, 23, 25, 26, 32, 
36, 37],
+    ]
+    # Verified against the reference client 4.3.0 on the same server, with the 
same seeding.
+    assert rows() == expected
+    assert rows() == expected
+
+
 
 
 def 
test_persist_cache_and_unpersist_return_the_dataframe_itself_as_pyspark(session):
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index eba47053..a27fed72 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -8847,6 +8847,40 @@ def 
test_sample_sort_group_by_and_drop_take_their_arguments_as_pyspark(mock_conn
         assert error.value.getMessageParameters() == parameters
 
 
+def 
test_sample_split_and_sample_by_draw_their_seed_from_python_random_as_pyspark(mock_connect):
+    # As PySpark Connect's: without a seed, sample, randomSplit and sampleBy 
draw one with
+    # random.randint(0, sys.maxsize), so random.seed makes their rows repeat 
across processes.
+    # An explicit seed is sent as given and draws nothing. A sum of weights 
that is not
+    # positive raises after the draw, a negative weight before it.
+    import random
+    import sys
+
+    from pyspark.errors import PySparkValueError
+
+    spark, service = mock_connect
+    df = spark.range(10)
+
+    def seed_of(dataframe, field):
+        # Relation.sample=12 or Relation.sample_by=107, whose seed is 
StatSampleBy.seed=5.
+        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]
+
+    random.seed(42)
+    draws = [random.randint(0, sys.maxsize) for _ in range(5)]
+    random.seed(42)
+    assert seed_of(df.sample(0.5, 7), 12) == 7
+    assert seed_of(df.sample(0.5), 12) == draws[0]
+    assert [seed_of(split, 12) for split in df.randomSplit([1.0, 2.0])] == 
[draws[1]] * 2
+    with pytest.raises(PySparkValueError):
+        df.randomSplit([0.0, 0.0])
+    with pytest.raises(PySparkValueError):
+        df.randomSplit([-1.0, 2.0])
+    assert seed_of(df.sampleBy("id", {0: 1.0}), 107) == draws[3]
+    assert seed_of(df.sample(fraction=0.5), 12) == draws[4]
+    assert seed_of(df.stat.sampleBy("id", {0: 1.0}, 7), 107) == 7
+
+
 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