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 10f2d8e6 [SPARK-61329][CONNECT] Draw a new seed for each call of the
random functions of the Rust API, as PySpark does
10f2d8e6 is described below
commit 10f2d8e68bcabd815f488c1808a02844871828c9
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 17:22:05 2026 +0900
[SPARK-61329][CONNECT] Draw a new seed for each call of the random
functions of the Rust API, as PySpark does
### What changes were proposed in this pull request?
[SPARK-61329](https://issues.apache.org/jira/browse/SPARK-61329): the
random functions of the Rust API draw a new seed for each call, as PySpark does.
- `rand`, `randn`, `uuid`, `shuffle`, `uniform`, `randstr` and
`count_min_sketch` (`crates/spark-connect/src/functions.rs`) send a new
non-negative seed for each call, the core's `random_seed()` (as PySpark's
`random.randint(0, sys.maxsize)`), instead of a fixed literal.
- `_with_seed` variants take an explicit seed, as the Scala client's
overloads: `rand_with_seed(i64)` and `randn_with_seed(i64)`, and
`uuid_with_seed`, `shuffle_with_seed`, `uniform_with_seed`, `randstr_with_seed`
and `count_min_sketch_with_seed` with a `Column`.
- `random` and `random_with_seed` are added, PySpark's alias of `rand`.
- `docs/compatibility.md` notes the change in the Rust migration section.
### Why are the changes needed?
Each of these functions sent the same constant seed in every call, query,
session and process. So `uuid()` returned the same UUIDs in every run, so
surrogate keys collided across appends. `select(rand(), rand())` gave two equal
columns, and `orderBy(rand())`, `filter(rand() < p)` and `shuffle` picked the
same rows every time. PySpark 4.3.0 (`pyspark.sql.connect.functions.builtin`)
and the Scala client draw a new seed per call. The Python drop-in was not
affected: its functions draw fr [...]
### Does this PR introduce _any_ user-facing change?
Yes, in the Rust API. A random function without a seed now gives different
values in each call and run, as PySpark does; an expression keeps its seed, so
every execution of a DataFrame gives the same values. The `_with_seed`
variants, `random` and `random_with_seed` are new.
### How was this patch tested?
- Unit tests in `functions.rs`:
- `random_functions_draw_a_new_seed_for_each_call_as_pyspark`: the eight
functions, four calls each, give distinct non-negative seeds. It fails without
the change.
- `random_functions_with_a_seed_send_it_as_pyspark`: the seed of each
`_with_seed` variant is sent as given, and `random_with_seed` is
`rand_with_seed`.
- Live (`crates/spark-connect/tests/e2e_functions.rs`, in both CI e2e
lists): `random_functions_draw_a_seed_for_each_call_as_pyspark`.
- Two `uuid()` columns and two `rand()` columns differ, and the `uuid()`
of two queries differ.
- A DataFrame gives the same values in two executions, and
`rand_with_seed`/`shuffle_with_seed` repeat for a seed.
- It fails without the change.
- The golden plan test (`functions_golden.rs`, which zeroes these seeds)
and `functions_coverage.rs` pass.
- Checks:
- lib tests of both crates;
- the build of all tests, also with `wasm-udf` and `datafusion,polars`,
with no warnings;
- `cargo fmt --all --check`;
- clippy, no diagnostics on the changed lines.
### 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 #459 from HyukjinKwon/s16-rust-random-seeds.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/spark-connect/src/dataframe.rs | 2 +-
crates/spark-connect/src/functions.rs | 197 +++++++++++++++++++++++++---
crates/spark-connect/tests/e2e_functions.rs | 40 ++++++
docs/compatibility.md | 7 +
4 files changed, 226 insertions(+), 20 deletions(-)
diff --git a/crates/spark-connect/src/dataframe.rs
b/crates/spark-connect/src/dataframe.rs
index c536aff7..f5bd14cb 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -2634,7 +2634,7 @@ fn set_observations(
/// A random seed of a sample without one, as PySpark's `random.randint(0,
sys.maxsize)`: the
/// client chooses it, so that every execution of the sample returns the same
rows.
-fn random_seed() -> i64 {
+pub(crate) fn random_seed() -> i64 {
(uuid::Uuid::new_v4().as_u128() >> 65) as i64
}
diff --git a/crates/spark-connect/src/functions.rs
b/crates/spark-connect/src/functions.rs
index e13f50b5..18323a26 100644
--- a/crates/spark-connect/src/functions.rs
+++ b/crates/spark-connect/src/functions.rs
@@ -47,6 +47,14 @@ fn lit_long(v: i64) -> Expression {
Expression::literal(LiteralExpression::long(v))
}
+/// The seed of a random function called without one: a new one for each call,
as PySpark's
+/// `random.randint(0, sys.maxsize)` and the Scala client's `random.nextLong`
draw it, so that
+/// two calls give different values and a call differs from one run to the
next. Within a
+/// plan, the expression keeps its seed, so every execution of the plan gives
the same values.
+fn random_seed_literal() -> Expression {
+ lit_long(crate::dataframe::random_seed())
+}
+
/// A boolean-literal argument expression.
fn lit_bool(b: bool) -> Expression {
Expression::literal(LiteralExpression::boolean(b))
@@ -401,14 +409,34 @@ pub fn pi() -> Column {
func("pi", vec![])
}
-/// Mirrors `pyspark.sql.functions.rand`.
+/// Mirrors `pyspark.sql.functions.rand` without a seed: a new random seed for
each call.
pub fn rand() -> Column {
- func("rand", vec![lit_long(2371029763967735218)])
+ func("rand", vec![random_seed_literal()])
}
-/// Mirrors `pyspark.sql.functions.randn`.
+/// Mirrors `pyspark.sql.functions.rand(seed)`.
+pub fn rand_with_seed(seed: i64) -> Column {
+ func("rand", vec![lit_long(seed)])
+}
+
+/// Mirrors `pyspark.sql.functions.random`, an alias of `rand`: a new random
seed for each call.
+pub fn random() -> Column {
+ rand()
+}
+
+/// Mirrors `pyspark.sql.functions.random(seed)`, an alias of `rand(seed)`.
+pub fn random_with_seed(seed: i64) -> Column {
+ rand_with_seed(seed)
+}
+
+/// Mirrors `pyspark.sql.functions.randn` without a seed: a new random seed
for each call.
pub fn randn() -> Column {
- func("randn", vec![lit_long(2561831801369089374)])
+ func("randn", vec![random_seed_literal()])
+}
+
+/// Mirrors `pyspark.sql.functions.randn(seed)`.
+pub fn randn_with_seed(seed: i64) -> Column {
+ func("randn", vec![lit_long(seed)])
}
/// Mirrors `pyspark.sql.functions.rank`.
@@ -1338,11 +1366,19 @@ pub fn raise_error(col1: Column) -> Column {
func("raise_error", vec![col1.expression().clone()])
}
-/// Mirrors `pyspark.sql.functions.randstr`.
+/// Mirrors `pyspark.sql.functions.randstr` without a seed: a new random seed
for each call.
pub fn randstr(col1: Column) -> Column {
func(
"randstr",
- vec![col1.expression().clone(), lit_long(1000462829105445681)],
+ vec![col1.expression().clone(), random_seed_literal()],
+ )
+}
+
+/// Mirrors `pyspark.sql.functions.randstr(length, seed)`.
+pub fn randstr_with_seed(col1: Column, seed: Column) -> Column {
+ func(
+ "randstr",
+ vec![col1.expression().clone(), seed.expression().clone()],
)
}
@@ -1435,11 +1471,19 @@ pub fn sha1(col1: Column) -> Column {
func("sha1", vec![col1.expression().clone()])
}
-/// Mirrors `pyspark.sql.functions.shuffle`.
+/// Mirrors `pyspark.sql.functions.shuffle` without a seed: a new random seed
for each call.
pub fn shuffle(col1: Column) -> Column {
func(
"shuffle",
- vec![col1.expression().clone(), lit_long(1810822539051918711)],
+ vec![col1.expression().clone(), random_seed_literal()],
+ )
+}
+
+/// Mirrors `pyspark.sql.functions.shuffle(col, seed)`.
+pub fn shuffle_with_seed(col1: Column, seed: Column) -> Column {
+ func(
+ "shuffle",
+ vec![col1.expression().clone(), seed.expression().clone()],
)
}
@@ -2861,14 +2905,26 @@ pub fn try_to_number(col1: Column, col2: Column) ->
Column {
)
}
-/// Mirrors `pyspark.sql.functions.uniform`.
+/// Mirrors `pyspark.sql.functions.uniform` without a seed: a new random seed
for each call.
pub fn uniform(col1: Column, col2: Column) -> Column {
func(
"uniform",
vec![
col1.expression().clone(),
col2.expression().clone(),
- lit_long(1779860837174053365),
+ random_seed_literal(),
+ ],
+ )
+}
+
+/// Mirrors `pyspark.sql.functions.uniform(min, max, seed)`.
+pub fn uniform_with_seed(col1: Column, col2: Column, seed: Column) -> Column {
+ func(
+ "uniform",
+ vec![
+ col1.expression().clone(),
+ col2.expression().clone(),
+ seed.expression().clone(),
],
)
}
@@ -2992,7 +3048,8 @@ pub fn convert_timezone(col1: Column, col2: Column, col3:
Column) -> Column {
)
}
-/// Mirrors `pyspark.sql.functions.count_min_sketch`.
+/// Mirrors `pyspark.sql.functions.count_min_sketch` without a seed: a new
random seed for each
+/// call.
pub fn count_min_sketch(col1: Column, col2: Column, col3: Column) -> Column {
func(
"count_min_sketch",
@@ -3000,7 +3057,25 @@ pub fn count_min_sketch(col1: Column, col2: Column,
col3: Column) -> Column {
col1.expression().clone(),
col2.expression().clone(),
col3.expression().clone(),
- lit_long(9151685696388386553),
+ random_seed_literal(),
+ ],
+ )
+}
+
+/// Mirrors `pyspark.sql.functions.count_min_sketch(col, eps, confidence,
seed)`.
+pub fn count_min_sketch_with_seed(
+ col1: Column,
+ col2: Column,
+ col3: Column,
+ seed: Column,
+) -> Column {
+ func(
+ "count_min_sketch",
+ vec![
+ col1.expression().clone(),
+ col2.expression().clone(),
+ col3.expression().clone(),
+ seed.expression().clone(),
],
)
}
@@ -4194,14 +4269,16 @@ pub fn unix_nanos(col: Column) -> Column {
func("unix_nanos", vec![col.expression().clone()])
}
-/// Mirrors `pyspark.sql.functions.uuid`.
-///
-/// The reference client seeds the expression with a (random) `long` argument
so
-/// the result is stable per query plan; we emit a fixed seed literal, matching
-/// the `rand`/`randn` builders. The seed is treated as run-to-run noise by the
-/// golden test (see `RANDOM_SEED_FUNCS`).
+/// Mirrors `pyspark.sql.functions.uuid` without a seed: a new random seed for
each call, so
+/// that two calls, and two runs, give different UUIDs. Within a plan, the
expression keeps its
+/// seed, so every execution of the plan gives the same UUIDs, as in PySpark.
pub fn uuid() -> Column {
- func("uuid", vec![lit_long(1214072022411175128)])
+ func("uuid", vec![random_seed_literal()])
+}
+
+/// Mirrors `pyspark.sql.functions.uuid(seed)`.
+pub fn uuid_with_seed(seed: Column) -> Column {
+ func("uuid", vec![seed.expression().clone()])
}
/// Mirrors `pyspark.sql.functions.variant_array_append`.
@@ -4568,6 +4645,88 @@ mod tests {
}
}
+ /// The last argument of the function of `column`, which is the seed of a
random function.
+ fn seed_argument(column: Column) -> spark_connect_proto::Expression {
+ use spark_connect_proto::expression::ExprType;
+ match column.to_proto().expr_type {
+ Some(ExprType::UnresolvedFunction(function)) => {
+ function.arguments.last().cloned().expect("a seed argument")
+ }
+ other => panic!("expected a function, got {other:?}"),
+ }
+ }
+
+ /// The long literal of a seed argument.
+ fn long_seed(column: Column) -> i64 {
+ use spark_connect_proto::expression::literal::LiteralType;
+ use spark_connect_proto::expression::ExprType;
+ match seed_argument(column).expr_type {
+ Some(ExprType::Literal(literal)) => match literal.literal_type {
+ Some(LiteralType::Long(seed)) => seed,
+ other => panic!("expected a long seed, got {other:?}"),
+ },
+ other => panic!("expected a literal seed, got {other:?}"),
+ }
+ }
+
+ /// As PySpark's `random.randint(0, sys.maxsize)`: a random function
without a seed draws a
+ /// new, non-negative one for each call, so that two calls and two runs
differ.
+ #[test]
+ fn random_functions_draw_a_new_seed_for_each_call_as_pyspark() {
+ type Call = fn() -> Column;
+ let calls: Vec<(&str, Call)> = vec![
+ ("rand", rand),
+ ("random", random),
+ ("randn", randn),
+ ("uuid", uuid),
+ ("randstr", || randstr(crate::column::lit(5))),
+ ("shuffle", || shuffle(col("a"))),
+ ("uniform", || {
+ uniform(crate::column::lit(0), crate::column::lit(10))
+ }),
+ ("count_min_sketch", || {
+ count_min_sketch(
+ col("a"),
+ crate::column::lit_double(0.5),
+ crate::column::lit_double(0.5),
+ )
+ }),
+ ];
+ for (name, call) in calls {
+ let seeds: Vec<i64> = (0..4).map(|_| long_seed(call())).collect();
+ assert!(seeds.iter().all(|seed| *seed >= 0), "{name}: {seeds:?}");
+ let mut distinct = seeds.clone();
+ distinct.sort_unstable();
+ distinct.dedup();
+ assert_eq!(distinct.len(), seeds.len(), "{name}: {seeds:?}");
+ }
+ }
+
+ /// As PySpark's `rand(seed)` and the others with a seed: the seed is sent
as given.
+ #[test]
+ fn random_functions_with_a_seed_send_it_as_pyspark() {
+ assert_eq!(long_seed(rand_with_seed(42)), 42);
+ assert_eq!(long_seed(random_with_seed(-7)), -7);
+ assert_eq!(long_seed(randn_with_seed(3)), 3);
+ let seed = crate::column::lit(11);
+ for column in [
+ uuid_with_seed(seed.clone()),
+ randstr_with_seed(crate::column::lit(5), seed.clone()),
+ shuffle_with_seed(col("a"), seed.clone()),
+ uniform_with_seed(crate::column::lit(0), crate::column::lit(10),
seed.clone()),
+ count_min_sketch_with_seed(
+ col("a"),
+ crate::column::lit_double(0.5),
+ crate::column::lit_double(0.5),
+ seed.clone(),
+ ),
+ ] {
+ assert_eq!(seed_argument(column), seed.to_proto());
+ }
+ // The aliases are the same function as PySpark's `random = rand`.
+ assert_eq!(rand_with_seed(1).to_proto(),
random_with_seed(1).to_proto());
+ }
+
#[test]
fn test_interval_builders_serialize() {
let make_dt = make_dt_interval();
diff --git a/crates/spark-connect/tests/e2e_functions.rs
b/crates/spark-connect/tests/e2e_functions.rs
index 441479cf..60fb81cc 100644
--- a/crates/spark-connect/tests/e2e_functions.rs
+++ b/crates/spark-connect/tests/e2e_functions.rs
@@ -114,6 +114,46 @@ fn aggregate_functions() {
assert_eq!(row.get_by_name("c").and_then(|v| v.as_i64()), Some(3));
}
+/// As PySpark, whose random functions draw a seed for each call: two `uuid()`
and two `rand()`
+/// columns differ, as do the `uuid()` of two queries, while a DataFrame keeps
its seeds across
+/// executions and a given seed gives the same values in every query.
+#[test]
+fn random_functions_draw_a_seed_for_each_call_as_pyspark() {
+ if !should_run() {
+ return;
+ }
+ let s = session();
+ let df = s.range(3).unwrap();
+ let values = |frame: &DataFrame| -> Vec<String> {
+ frame
+ .collect()
+ .unwrap()
+ .iter()
+ .map(|row| format!("{:?}", (row.get(0), row.get(1))))
+ .collect()
+ };
+ let uuids = df.select(vec![f::uuid(), f::uuid()]);
+ for row in uuids.collect().unwrap() {
+ assert_ne!(row.get(0), row.get(1));
+ }
+ assert_eq!(values(&uuids), values(&uuids));
+ let one = df.select(vec![f::uuid(), lit(0)]);
+ let other = df.select(vec![f::uuid(), lit(0)]);
+ assert_ne!(values(&one), values(&other));
+ for row in df.select(vec![f::rand(), f::rand()]).collect().unwrap() {
+ assert_ne!(row.get(0), row.get(1));
+ }
+ let seeded = |seed: i64| df.select(vec![f::rand_with_seed(seed),
f::randn_with_seed(seed)]);
+ assert_eq!(values(&seeded(7)), values(&seeded(7)));
+ assert_ne!(values(&seeded(7)), values(&seeded(8)));
+ let shuffled = |seed: i64| {
+ s.sql("SELECT sequence(1, 50) AS a")
+ .unwrap()
+ .select(vec![f::shuffle_with_seed(col("a"), lit(seed)), lit(0)])
+ };
+ assert_eq!(values(&shuffled(3)), values(&shuffled(3)));
+}
+
#[test]
fn optional_arg_function_variants() {
if !should_run() {
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 6a2804aa..08e79700 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -58,6 +58,13 @@ helpers accept `impl Into<Arc<LogicalPlan>>`, so they accept
either an owned
`LogicalPlan` or an existing `Arc<LogicalPlan>`. Serialization still produces
the
same protobuf tree; sharing does not deduplicate repeated relations on the
wire.
+The random functions `rand`, `randn`, `uuid`, `shuffle`, `uniform`, `randstr`
and
+`count_min_sketch` draw a new seed for each call, as PySpark and the Scala
client do.
+Before, each sent the same fixed seed, so two `uuid()` columns, or the
`uuid()` of
+two runs, were equal. For reproducible values, use the `_with_seed` variants
+(`rand_with_seed(42)`, `uuid_with_seed(lit(42))`, ...). `random` and
+`random_with_seed` are added as the aliases of `rand` that PySpark has.
+
## Native LogisticRegression
The native `spark_connect::ml::LogisticRegression` fits Spark's JVM
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]