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 f0de9212 [SPARK-61405][CONNECT] Draw a seed of the client for 
sample_by without one, take PySpark's strata types, and fill the columns of a 
map in fillna_value, in the Rust API as PySpark does
f0de9212 is described below

commit f0de9212557ba2493b485a79a5d4a70463daab21
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 08:43:18 2026 +0900

    [SPARK-61405][CONNECT] Draw a seed of the client for sample_by without one, 
take PySpark's strata types, and fill the columns of a map in fillna_value, in 
the Rust API as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61405](https://issues.apache.org/jira/browse/SPARK-61405): three 
fixes to the Rust API's `StatFunctions::sample_by` and 
`DataFrame::fillna_value`, to behave as PySpark's `sampleBy` and `fillna` do.
    
    - `sample_by(col, fractions, None)` sends a seed that the client draws 
(`random_seed()`, as `sample` and `random_split` already do), instead of no 
seed.
    - `sample_by` accepts a stratum only if it is a literal of a bool, an 
integer, a float or a string, the Rust kinds of PySpark's `float`, `int` and 
`str` keys. A stratum of another type, or one that is not a literal, is 
`DISALLOWED_TYPE_FOR_CONTAINER` with PySpark's `allowed_types` of `float, int, 
str`, and with the Python name of its type as `item_type` (for example `date`, 
`datetime`, `Decimal`, `bytes`, `NoneType`, `Column`).
    - `fillna_value(Value::Map(..), subset)` fills the columns of the map's 
keys with its values, as PySpark's `fillna` of a dict does, and ignores 
`subset` as PySpark does. It returns PySpark's errors:
      - a key that is not a string: `NOT_EXPECTED_TYPE` for `key type of dict`;
      - a value of another type: `NOT_EXPECTED_TYPE` for `value type of dict`;
      - an empty map: `CANNOT_BE_EMPTY`.
    
      The Python names of the value types move from `check_fill_value` into a 
`python_type_name` function that both errors use.
    
    ### Why are the changes needed?
    
    - Without a seed, the server draws one (`Utils.random.nextLong`) each time 
it plans the relation. So one DataFrame of `sample_by(.., None)` returned 
different rows in different actions: `count()` changed from call to call and 
disagreed with `collect()`, and a self-join paired two different samples.
      - Over `range(0, 200, 1, 2)` with strata `id % 2` at 0.5 each, on a local 
Spark 4.3.0 server, three `count()`s gave `[108, 101, 101]` and `collect()` 
gave 109 rows.
      - PySpark draws the seed on the client: `seed = seed if seed is not None 
else random.randint(0, sys.maxsize)`.
      - The drop-in always passed a seed, so it was not affected.
    - The server reads a stratum by its Catalyst internal value, and Spark's 
`sampleBy` looks it up by the external value of the column. So a date, 
timestamp, decimal or binary stratum matched no row, and the sample was empty 
without an error (0 of 1 row at fraction 1.0 for each of them). PySpark takes 
only `float`, `int` and `str` keys and raises `DISALLOWED_TYPE_FOR_CONTAINER` 
for others.
    - `fillna_value` of a map raised `[NOT_EXPECTED_TYPE] Argument `value` 
should be bool, dict, float, int or str, got dict.`, which names `dict` both as 
an accepted type and as the rejected one. PySpark's `fillna` takes a dict.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, in the Rust API:
    
    - A sample of `sample_by` without a seed returns the same rows in every 
execution. Its rows are those of a seed that the client draws, so they differ 
from before; before, they changed with each execution anyway.
    - A stratum of a type other than bool, integer, float or string is an error 
instead of an empty sample.
    - `fillna_value` of a map of string keys fills those columns.
    
    The Python client is not changed.
    
    ### How was this patch tested?
    
    - New unit tests in `crates/spark-connect/src/group.rs`, placed before 
`sample_by_rejects_a_stratum_that_is_not_a_literal_as_pyspark`:
      - `sample_by_takes_a_seed_of_the_client_without_one_as_pyspark`: the 
relation carries the given seed, and a non-negative seed of the client without 
one, which stays the same for the DataFrame.
      - `sample_by_takes_the_strata_types_of_pyspark`: the accepted literal 
kinds, and the rejected ones with their `item_type` and `allowed_types`.
    - `sample_by_rejects_a_stratum_that_is_not_a_literal_as_pyspark` now 
expects PySpark's `[float, int, str]`.
    - A new unit test in `crates/spark-connect/src/dataframe.rs`, placed after 
`fill_values_are_those_of_pyspark_and_sent_as_its_literals`: 
`a_map_fill_value_fills_its_columns_as_pyspark` checks the FillNa of a map (its 
columns and values, without the subset), and the three errors with their 
messages.
    - A new live test in `crates/spark-connect/tests/e2e_new_methods.rs`, 
placed after `stat_corr_cov_sample_by`: 
`sample_by_without_a_seed_returns_the_same_rows_in_every_execution_as_pyspark` 
checks that three `count()`s and a `collect()` of one sample without a seed 
agree, against a local Spark 4.3.0 server.
    - With master's `sample_by` and `fillna_value` put back, the four unit 
tests above fail, and the live test fails with `[108, 101, 101] and 109`. With 
the fix, all of them pass.
    - The lib tests of `sample_by`, `fill` and `stat_`; `e2e_new_methods` 
against the server (9 passed); the build of all the tests without warnings; 
`cargo fmt --all --check`. Clippy reports nothing in 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 #478 from HyukjinKwon/SPARK-61405-sample-by-seed.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/spark-connect/src/dataframe.rs         | 130 ++++++++++++++++++++----
 crates/spark-connect/src/group.rs             | 141 +++++++++++++++++++++++---
 crates/spark-connect/tests/e2e_new_methods.rs |  28 +++++
 3 files changed, 265 insertions(+), 34 deletions(-)

diff --git a/crates/spark-connect/src/dataframe.rs 
b/crates/spark-connect/src/dataframe.rs
index c7599102..45044adf 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -1871,14 +1871,46 @@ impl DataFrame {
 
     /// Fill NA values with a [`crate::row::Value`]. Mirrors 
`DataFrame.fillna(value, subset)`:
     /// the value is a bool, an integer (sent as a long), a float (sent as a 
double) or a string,
-    /// else a `NOT_EXPECTED_TYPE` error, as PySpark raises for a value of 
another type.
+    /// else a `NOT_EXPECTED_TYPE` error, as PySpark raises for a value of 
another type. A map,
+    /// as PySpark's dict, fills its columns, its string keys, with its 
values, as
+    /// [`DataFrame::fillna_map`], and `subset` is not used; a key that is not 
a string is a
+    /// `NOT_EXPECTED_TYPE` error, as PySpark raises.
     pub fn fillna_value(
         &self,
         value: crate::row::Value,
         subset: Option<Vec<&str>>,
     ) -> Result<DataFrame> {
-        check_fill_value(&value, "value", "bool, dict, float, int or str")?;
-        Ok(self.fill_with(value, subset))
+        let entries = match value {
+            Value::Map(entries) => entries,
+            value => {
+                check_fill_value(&value, "value", "bool, dict, float, int or 
str")?;
+                return Ok(self.fill_with(value, subset));
+            }
+        };
+        if entries.is_empty() {
+            return Err(SparkError::classed(
+                SparkErrorKind::ValueError,
+                "CANNOT_BE_EMPTY",
+                &[("item", "value")],
+            ));
+        }
+        let mut pairs = Vec::with_capacity(entries.len());
+        for (key, value) in entries {
+            let Value::String(column) = key else {
+                return Err(SparkError::classed(
+                    SparkErrorKind::TypeError,
+                    "NOT_EXPECTED_TYPE",
+                    &[
+                        ("arg_name", "key type of dict"),
+                        ("expected_type", "str"),
+                        ("arg_type", python_type_name(&key)),
+                    ],
+                ));
+            };
+            check_fill_value(&value, "value type of dict", "bool, float, int 
or str")?;
+            pairs.push((column, value));
+        }
+        self.fillna_map(pairs)
     }
 
     /// The NAFill of `value`, a value that PySpark's `fillna` takes, over 
`subset`.
@@ -2752,15 +2784,35 @@ fn set_observations(
 /// other value is the `NOT_EXPECTED_TYPE` error of PySpark, of `arg_name` and 
`expected_type`, with
 /// the Python name of the type that the value stands for.
 fn check_fill_value(value: &Value, arg_name: &str, expected_type: &str) -> 
Result<()> {
-    let arg_type = match value {
-        Value::Bool(_)
-        | Value::Byte(_)
-        | Value::Short(_)
-        | Value::Integer(_)
-        | Value::Long(_)
-        | Value::Float(_)
-        | Value::Double(_)
-        | Value::String(_) => return Ok(()),
+    if let Value::Bool(_)
+    | Value::Byte(_)
+    | Value::Short(_)
+    | Value::Integer(_)
+    | Value::Long(_)
+    | Value::Float(_)
+    | Value::Double(_)
+    | Value::String(_) = value
+    {
+        return Ok(());
+    }
+    Err(SparkError::classed(
+        SparkErrorKind::TypeError,
+        "NOT_EXPECTED_TYPE",
+        &[
+            ("arg_name", arg_name),
+            ("expected_type", expected_type),
+            ("arg_type", python_type_name(value)),
+        ],
+    ))
+}
+
+/// The Python name of the type of the value that `value` stands for, as 
PySpark's errors name it.
+fn python_type_name(value: &Value) -> &'static str {
+    match value {
+        Value::Bool(_) => "bool",
+        Value::Byte(_) | Value::Short(_) | Value::Integer(_) | Value::Long(_) 
=> "int",
+        Value::Float(_) | Value::Double(_) => "float",
+        Value::String(_) => "str",
         Value::Null => "NoneType",
         Value::Binary(_) => "bytes",
         Value::Date(_) => "date",
@@ -2774,16 +2826,7 @@ fn check_fill_value(value: &Value, arg_name: &str, 
expected_type: &str) -> Resul
         Value::Map(_) => "dict",
         Value::Struct(_) => "Row",
         Value::Variant { .. } => "VariantVal",
-    };
-    Err(SparkError::classed(
-        SparkErrorKind::TypeError,
-        "NOT_EXPECTED_TYPE",
-        &[
-            ("arg_name", arg_name),
-            ("expected_type", expected_type),
-            ("arg_type", arg_type),
-        ],
-    ))
+    }
 }
 
 /// A random seed of a sample without one, as PySpark's `random.randint(0, 
sys.maxsize)`: the
@@ -4870,6 +4913,49 @@ mod plan_construction_tests {
         assert_eq!(empty.get_condition().as_deref(), Some("CANNOT_BE_EMPTY"));
     }
 
+    /// As PySpark's `fillna` of a dict: a map fills its columns, its keys, 
with its values, as
+    /// `fillna_map`, and `subset` is not used; a key that is not a string, a 
value of another type
+    /// and an empty map are the errors of PySpark.
+    #[test]
+    fn a_map_fill_value_fills_its_columns_as_pyspark() {
+        let df = session().range(1).unwrap();
+        let filled = df
+            .fillna_value(
+                Value::Map(vec![
+                    (Value::String("id".into()), Value::Long(1)),
+                    (Value::String("x".into()), Value::String("a".into())),
+                ]),
+                Some(vec!["unused"]),
+            )
+            .unwrap();
+        match filled.to_relation().unwrap().rel_type {
+            Some(proto::relation::RelType::FillNa(fill)) => {
+                assert_eq!(fill.cols, vec!["id".to_string(), "x".to_string()]);
+                assert_eq!(fill.values.len(), 2);
+            }
+            other => panic!("expected a FillNa, got {other:?}"),
+        }
+        let message = |entries| {
+            df.fillna_value(Value::Map(entries), None)
+                .err()
+                .expect("an error")
+                .message()
+        };
+        assert_eq!(
+            message(vec![(Value::Long(1), Value::Long(1))]),
+            "[NOT_EXPECTED_TYPE] Argument `key type of dict` should be str, 
got int."
+        );
+        assert_eq!(
+            message(vec![(Value::String("id".into()), Value::Date(0))]),
+            "[NOT_EXPECTED_TYPE] Argument `value type of dict` should be bool, 
float, int or str, \
+             got date."
+        );
+        assert_eq!(
+            message(vec![]),
+            "[CANNOT_BE_EMPTY] At least one value must be specified."
+        );
+    }
+
     fn session() -> SparkSession {
         SparkSession::builder()
             .remote("sc://localhost:15002")
diff --git a/crates/spark-connect/src/group.rs 
b/crates/spark-connect/src/group.rs
index e914f86f..e071b952 100644
--- a/crates/spark-connect/src/group.rs
+++ b/crates/spark-connect/src/group.rs
@@ -693,29 +693,54 @@ impl StatFunctions {
     }
 
     /// Sample by values in a column, mirroring 
`DataFrameStatFunctions.sampleBy(col, fractions,
-    /// seed)`: each stratum of `fractions` is a literal, of any type, with 
its fraction. A
-    /// stratum that is not a literal, which the server cannot read, is a
+    /// seed)`: each stratum of `fractions` is a literal of a bool, an 
integer, a float or a
+    /// string, as PySpark's keys are a float, an int or a str, with its 
fraction. A stratum of
+    /// another type, which the server matches against no row, or that is not 
a literal, is a
     /// `DISALLOWED_TYPE_FOR_CONTAINER` error, as PySpark raises for a key of 
another type.
+    /// Without a seed, the client chooses one, as PySpark does, so that every 
execution of the
+    /// sample returns the same rows.
     pub fn sample_by(
         &self,
         col: impl Into<Column>,
         fractions: Vec<(Expression, f64)>,
         seed: Option<i64>,
     ) -> Result<DataFrame> {
-        if fractions.iter().any(|(stratum, _)| {
-            !matches!(
-                stratum.node(),
-                crate::expression::ExpressionNode::Literal(_)
-            )
-        }) {
+        use crate::expression::{ExpressionNode, LiteralExpression};
+        for (stratum, _) in &fractions {
+            // The Python name of the type of the value that a literal stands 
for.
+            let item_type = match stratum.node() {
+                ExpressionNode::Literal(literal) => match literal {
+                    LiteralExpression::Boolean(_)
+                    | LiteralExpression::Byte(_)
+                    | LiteralExpression::Short(_)
+                    | LiteralExpression::Integer(_)
+                    | LiteralExpression::Long(_)
+                    | LiteralExpression::Float(_)
+                    | LiteralExpression::Double(_)
+                    | LiteralExpression::String(_) => continue,
+                    LiteralExpression::Null(_) => "NoneType",
+                    LiteralExpression::Decimal { .. } => "Decimal",
+                    LiteralExpression::Binary(_) => "bytes",
+                    LiteralExpression::Date(_) => "date",
+                    LiteralExpression::Timestamp(_) | 
LiteralExpression::TimestampNtz(_) => {
+                        "datetime"
+                    }
+                    LiteralExpression::DayTimeInterval(_) => "timedelta",
+                    // Python has no type of a year-month interval: its Spark 
type names it.
+                    LiteralExpression::YearMonthInterval(_) => 
"YearMonthInterval",
+                    LiteralExpression::Time { .. } => "time",
+                    LiteralExpression::Array { .. } => "list",
+                },
+                _ => "Column",
+            };
             return Err(SparkError::classed(
                 SparkErrorKind::TypeError,
                 "DISALLOWED_TYPE_FOR_CONTAINER",
                 &[
                     ("arg_name", "fractions"),
                     ("arg_type", "dict"),
-                    ("allowed_types", "literal"),
-                    ("item_type", "Column"),
+                    ("allowed_types", "float, int, str"),
+                    ("item_type", item_type),
                 ],
             ));
         }
@@ -723,7 +748,7 @@ impl StatFunctions {
             input: Arc::clone(&self.dataframe.plan),
             col: col.into().expression().clone(),
             fractions,
-            seed,
+            seed: Some(seed.unwrap_or_else(crate::dataframe::random_seed)),
         };
         Ok(DataFrame::new(self.dataframe.session.clone(), plan))
     }
@@ -1373,6 +1398,98 @@ mod tests {
         }
     }
 
+    /// As PySpark's `sampleBy`, whose seed the client chooses when none is 
given, so that every
+    /// execution of the sample returns the same rows: the server draws one in 
each planning of a
+    /// relation without one.
+    #[test]
+    fn sample_by_takes_a_seed_of_the_client_without_one_as_pyspark() {
+        use crate::expression::LiteralExpression as L;
+        let df = session().range(10).unwrap();
+        let sampled = |seed| {
+            df.stat()
+                .sample_by("id", vec![(Expression::literal(L::Long(1)), 0.5)], 
seed)
+                .unwrap()
+        };
+        let sent_seed = |frame: DataFrame| match 
frame.to_relation().unwrap().rel_type {
+            Some(spark_connect_proto::relation::RelType::SampleBy(stat)) => 
stat.seed,
+            other => panic!("expected a StatSampleBy, got {other:?}"),
+        };
+        assert_eq!(sent_seed(sampled(Some(7))), Some(7));
+        let chosen = sent_seed(sampled(None));
+        assert!(chosen.is_some_and(|seed| seed >= 0), "{chosen:?}");
+        // The seed of a DataFrame is kept, as it is in its plan.
+        let frame = sampled(None);
+        assert_eq!(sent_seed(frame.clone()), sent_seed(frame));
+    }
+
+    /// As PySpark's `sampleBy`, whose keys are a float, an int (or a bool) or 
a str: a stratum of
+    /// another type, which the server matches against no row, is 
`DISALLOWED_TYPE_FOR_CONTAINER`,
+    /// of the Python name of its type.
+    #[test]
+    fn sample_by_takes_the_strata_types_of_pyspark() {
+        use crate::expression::LiteralExpression as L;
+        let df = session().range(10).unwrap();
+        for accepted in [
+            L::Boolean(true),
+            L::Byte(1),
+            L::Short(1),
+            L::Integer(1),
+            L::Long(1),
+            L::Float(0.5),
+            L::Double(0.5),
+            L::String("a".into()),
+        ] {
+            df.stat()
+                .sample_by(
+                    "id",
+                    vec![(Expression::literal(accepted.clone()), 0.5)],
+                    None,
+                )
+                .unwrap_or_else(|error| panic!("{accepted:?}: {error}"));
+        }
+        for (rejected, item_type) in [
+            (L::Null(DataType::Long), "NoneType"),
+            (
+                L::Decimal {
+                    value: "1.5".into(),
+                    precision: 2,
+                    scale: 1,
+                },
+                "Decimal",
+            ),
+            (L::Binary(vec![1]), "bytes"),
+            (L::Date(0), "date"),
+            (L::Timestamp(0), "datetime"),
+            (L::TimestampNtz(0), "datetime"),
+            (L::DayTimeInterval(0), "timedelta"),
+            (L::YearMonthInterval(0), "YearMonthInterval"),
+        ] {
+            let error = df
+                .stat()
+                .sample_by(
+                    "id",
+                    vec![(Expression::literal(rejected.clone()), 0.5)],
+                    None,
+                )
+                .err()
+                .unwrap_or_else(|| panic!("{rejected:?} must be rejected"));
+            assert_eq!(error.kind, SparkErrorKind::TypeError, "{rejected:?}");
+            assert_eq!(
+                error.get_condition().as_deref(),
+                Some("DISALLOWED_TYPE_FOR_CONTAINER")
+            );
+            assert_eq!(
+                error.params.get("item_type").map(String::as_str),
+                Some(item_type),
+                "{rejected:?}"
+            );
+            assert_eq!(
+                error.params.get("allowed_types").map(String::as_str),
+                Some("float, int, str")
+            );
+        }
+    }
+
     /// As PySpark's `sampleBy` rejects a key that is not a float, an int or a 
str: a stratum
     /// that is not a literal, which the server cannot read, is 
`DISALLOWED_TYPE_FOR_CONTAINER`.
     #[test]
@@ -1392,7 +1509,7 @@ mod tests {
         assert_eq!(
             error.message(),
             "[DISALLOWED_TYPE_FOR_CONTAINER] Argument `fractions`(type: dict) 
should only contain \
-             a type in [literal], got Column"
+             a type in [float, int, str], got Column"
         );
     }
 }
diff --git a/crates/spark-connect/tests/e2e_new_methods.rs 
b/crates/spark-connect/tests/e2e_new_methods.rs
index d2c9d187..f61d9ce5 100644
--- a/crates/spark-connect/tests/e2e_new_methods.rs
+++ b/crates/spark-connect/tests/e2e_new_methods.rs
@@ -126,6 +126,34 @@ fn stat_corr_cov_sample_by() {
     assert!(sampled.len() <= 5);
 }
 
+/// As PySpark's `sampleBy`, whose seed the client chooses when none is given: 
every execution of
+/// a sample without a seed returns the same rows, where a server that drew a 
seed in each planning
+/// would count other rows each time.
+#[test]
+fn 
sample_by_without_a_seed_returns_the_same_rows_in_every_execution_as_pyspark() {
+    if !should_run() {
+        return;
+    }
+    let spark = session();
+    let df = spark
+        .sql("SELECT id, id % 2 AS k FROM range(0, 200, 1, 2)")
+        .expect("sql");
+    let fractions = vec![
+        (lit(0).expression().clone(), 0.5),
+        (lit(1).expression().clone(), 0.5),
+    ];
+    let sampled = df
+        .stat()
+        .sample_by("k", fractions, None)
+        .expect("sample_by");
+    let counts: Vec<i64> = (0..3).map(|_| 
sampled.count().expect("count")).collect();
+    let collected = sampled.collect().expect("collect").len() as i64;
+    assert!(
+        counts.iter().all(|&count| count == collected),
+        "{counts:?} and {collected}"
+    );
+}
+
 #[test]
 fn replace_to_with_metadata_random_split() {
     if !should_run() {


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to