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 701fb316 [SPARK-61335][CONNECT] Send the fill values of fillna_value 
and fillna_map as PySpark sends them, and reject the others, in the Rust API
701fb316 is described below

commit 701fb3168ba09f3ef834742ab1fa412a2caf01f3
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 17:37:14 2026 +0900

    [SPARK-61335][CONNECT] Send the fill values of fillna_value and fillna_map 
as PySpark sends them, and reject the others, in the Rust API
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61335](https://issues.apache.org/jira/browse/SPARK-61335): the fill 
values of `DataFrame::fillna_value` and `fillna_map` of the Rust API are sent 
as PySpark sends them, and the others are rejected.
    
    - In `crates/spark-connect/src/plan.rs`, `value_to_proto_literal` follows 
PySpark's `NAFill._convert_value`, which sends the only types the server's fill 
takes:
      - a bool as a boolean;
      - an integer (`Byte`, `Short`, `Integer`, `Long`) as a long;
      - a float as a double;
      - a string as a string.
    - A value that only a directly built plan can hold gets its own literal 
type, or an empty literal for nested values, so that the server rejects it.
    - In `crates/spark-connect/src/dataframe.rs`, `fillna_value` and 
`fillna_map` check their values as PySpark's `fillna` does:
      - any other value is `NOT_EXPECTED_TYPE`, with PySpark's `arg_name` and 
`expected_type`;
      - an empty map is `CANNOT_BE_EMPTY`;
      - so they return a `Result`, as `dropna` does.
    - `fillna`, `fillna_double`, `fillna_string` and `fillna_bool` are 
unchanged. The drop-in's `fillna`, which checks its values in Python first, 
maps the `Result`.
    - `docs/compatibility.md` notes the change in the Rust migration section.
    
    ### Why are the changes needed?
    
    A value of a type that PySpark's `fillna` does not take was sent as the 
string of its Debug text, so it silently filled string columns:
    - `Value::Null` filled them with `"Null"`, `Value::Binary` with 
`"Binary([1, 2])"`, and `List`, `Map`, `Struct` and `Time` likewise.
    - `Value::Integer(5)` and `Value::Float(1.5)` were sent as an int and a 
float. The server's fill rejects those ("Unsupported value type 
java.lang.Integer (5)."), though PySpark's `fillna(5)` and `fillna(1.5)` work.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, in the Rust API:
    - `fillna_value` and `fillna_map` return a `Result`, and reject the values 
PySpark rejects.
    - An integer or a float fill now works.
    
    ### How was this patch tested?
    
    - Unit (`plan_construction_tests`): 
`fill_values_are_those_of_pyspark_and_sent_as_its_literals`.
      - The eight accepted value types are sent as PySpark's literals, by both 
methods.
      - `Null`, `Binary`, `List` and `Date` are `NOT_EXPECTED_TYPE` with 
PySpark's parameters; an empty map is `CANNOT_BE_EMPTY`.
    - Live (`crates/spark-connect/tests/e2e_ops_breadth.rs`): 
`fill_values_are_sent_as_pyspark_sends_them`. An `Integer` and a `Float` fill 
their columns; the server rejected the integer before.
    - Checks:
      - the lib tests of both crates (719 passed);
      - the build of all tests (also `wasm-udf`, `datafusion,polars`) without 
warnings;
      - `cargo fmt --all --check`, and clippy with no diagnostics on the 
changed lines;
      - the offline Python suites (2980 passed, 8 skipped);
      - the live drop-in, Arrow and ML suites against a local Spark 4.3.0 
server (254 passed).
    
    ### 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 #465 from HyukjinKwon/s16-fillna-values.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/stat_arguments.rs       |   5 +-
 crates/spark-connect/src/dataframe.rs         | 154 ++++++++++++++++++++++++--
 crates/spark-connect/src/plan.rs              |  66 +++++------
 crates/spark-connect/tests/e2e_coverage.rs    |   2 +
 crates/spark-connect/tests/e2e_ops_breadth.rs |  40 +++++++
 docs/compatibility.md                         |   7 ++
 6 files changed, 231 insertions(+), 43 deletions(-)

diff --git a/crates/pyspark-rs/src/stat_arguments.rs 
b/crates/pyspark-rs/src/stat_arguments.rs
index 0f0a2034..8683484d 100644
--- a/crates/pyspark-rs/src/stat_arguments.rs
+++ b/crates/pyspark-rs/src/stat_arguments.rs
@@ -157,10 +157,11 @@ pub(crate) fn fillna(
         for (column, fill) in dict.iter() {
             pairs.push((column.extract()?, fill_value(&fill)?));
         }
-        return Ok(PyDataFrame::new(df.fillna_map(pairs)));
+        return Ok(PyDataFrame::new(df.fillna_map(pairs).to_pyerr()?));
     }
     Ok(PyDataFrame::new(
-        df.fillna_value(fill_value(value)?, column_refs(&columns)),
+        df.fillna_value(fill_value(value)?, column_refs(&columns))
+            .to_pyerr()?,
     ))
 }
 
diff --git a/crates/spark-connect/src/dataframe.rs 
b/crates/spark-connect/src/dataframe.rs
index 2225c2aa..762236bd 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -1823,26 +1823,38 @@ impl DataFrame {
 
     /// Fill NA values with an integer.
     pub fn fillna(&self, value: i64, subset: Option<Vec<&str>>) -> DataFrame {
-        self.fillna_value(crate::row::Value::Long(value), subset)
+        self.fill_with(crate::row::Value::Long(value), subset)
     }
 
     /// Fill NA values with a double (e.g. a fractional fill into a double 
column).
     pub fn fillna_double(&self, value: f64, subset: Option<Vec<&str>>) -> 
DataFrame {
-        self.fillna_value(crate::row::Value::Double(value), subset)
+        self.fill_with(crate::row::Value::Double(value), subset)
     }
 
     /// Fill NA values with a string.
     pub fn fillna_string(&self, value: &str, subset: Option<Vec<&str>>) -> 
DataFrame {
-        self.fillna_value(crate::row::Value::String(value.to_string()), subset)
+        self.fill_with(crate::row::Value::String(value.to_string()), subset)
     }
 
     /// Fill NA values with a boolean.
     pub fn fillna_bool(&self, value: bool, subset: Option<Vec<&str>>) -> 
DataFrame {
-        self.fillna_value(crate::row::Value::Bool(value), subset)
+        self.fill_with(crate::row::Value::Bool(value), subset)
     }
 
-    /// Fill NA values with a typed [`crate::row::Value`] 
(Long/Double/String/Bool/...).
-    pub fn fillna_value(&self, value: crate::row::Value, subset: 
Option<Vec<&str>>) -> 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.
+    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))
+    }
+
+    /// The NAFill of `value`, a value that PySpark's `fillna` takes, over 
`subset`.
+    fn fill_with(&self, value: crate::row::Value, subset: Option<Vec<&str>>) 
-> DataFrame {
         let columns = subset
             .map(|v| v.iter().map(|s| s.to_string()).collect())
             .unwrap_or_default();
@@ -1854,16 +1866,27 @@ impl DataFrame {
         DataFrame::new(self.session.clone(), plan)
     }
 
-    /// Fill NA values per column from `(column, value)` pairs.
-    /// Mirrors `df.fillna({col: value, ...})`.
-    pub fn fillna_map(&self, pairs: Vec<(String, crate::row::Value)>) -> 
DataFrame {
+    /// Fill NA values per column from `(column, value)` pairs. Mirrors
+    /// `df.fillna({col: value, ...})`: the values are as those of 
[`DataFrame::fillna_value`],
+    /// and an empty map is a `CANNOT_BE_EMPTY` error, as PySpark raises.
+    pub fn fillna_map(&self, pairs: Vec<(String, crate::row::Value)>) -> 
Result<DataFrame> {
+        if pairs.is_empty() {
+            return Err(SparkError::classed(
+                SparkErrorKind::ValueError,
+                "CANNOT_BE_EMPTY",
+                &[("item", "value")],
+            ));
+        }
+        for (_, value) in &pairs {
+            check_fill_value(value, "value type of dict", "bool, float, int or 
str")?;
+        }
         let (cols, values): (Vec<String>, Vec<crate::row::Value>) = 
pairs.into_iter().unzip();
         let plan = LogicalPlan::NAFillColumns {
             input: Arc::clone(&self.plan),
             cols,
             values,
         };
-        DataFrame::new(self.session.clone(), plan)
+        Ok(DataFrame::new(self.session.clone(), plan))
     }
 
     /// Drop NA values. Mirrors `DataFrame.dropna`: `how` is "any" (the 
default) or "all", else
@@ -2693,6 +2716,42 @@ fn set_observations(
     }
 }
 
+/// Whether `value` is a fill of PySpark's `fillna`: a bool, an integer, a 
float or a string. Any
+/// 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(()),
+        Value::Null => "NoneType",
+        Value::Binary(_) => "bytes",
+        Value::Date(_) => "date",
+        Value::Timestamp(_) | Value::TimestampNtz(_) => "datetime",
+        Value::Time(_) => "time",
+        Value::DayTimeInterval(_) => "timedelta",
+        Value::Decimal { .. } => "Decimal",
+        Value::List(_) => "list",
+        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
 /// client chooses it, so that every execution of the sample returns the same 
rows.
 pub(crate) fn random_seed() -> i64 {
@@ -4615,6 +4674,81 @@ mod plan_construction_tests {
         assert_eq!(info.operation_id.as_deref(), Some("op-1"));
     }
 
+    /// As PySpark's `fillna`: a fill is a bool, an integer (sent as a long), 
a float (sent as a
+    /// double) or a string; any other value, and an empty map, is PySpark's 
error, instead of a
+    /// fill of the text of the value.
+    #[test]
+    fn fill_values_are_those_of_pyspark_and_sent_as_its_literals() {
+        use proto::expression::literal::LiteralType;
+        let spark = session();
+        let df = spark.range(1).unwrap();
+        let sent = |frame: DataFrame| -> Vec<Option<LiteralType>> {
+            match frame.to_relation().unwrap().rel_type {
+                Some(proto::relation::RelType::FillNa(fill)) => fill
+                    .values
+                    .into_iter()
+                    .map(|literal| literal.literal_type)
+                    .collect(),
+                other => panic!("expected a FillNa, got {other:?}"),
+            }
+        };
+        for (value, literal) in [
+            (Value::Byte(1), LiteralType::Long(1)),
+            (Value::Short(2), LiteralType::Long(2)),
+            (Value::Integer(5), LiteralType::Long(5)),
+            (Value::Long(6), LiteralType::Long(6)),
+            (Value::Float(1.5), LiteralType::Double(1.5)),
+            (Value::Double(2.5), LiteralType::Double(2.5)),
+            (Value::Bool(true), LiteralType::Boolean(true)),
+            (Value::String("x".into()), LiteralType::String("x".into())),
+        ] {
+            let filled = df.fillna_value(value.clone(), None).unwrap();
+            assert_eq!(sent(filled), vec![Some(literal.clone())], "{value:?}");
+            let mapped = df.fillna_map(vec![("id".into(), value)]).unwrap();
+            assert_eq!(sent(mapped), vec![Some(literal)]);
+        }
+        let condition = |error: SparkError| {
+            (
+                error.kind,
+                error.get_condition(),
+                error.params.get("arg_name").cloned(),
+                error.params.get("arg_type").cloned(),
+            )
+        };
+        for (value, arg_type) in [
+            (Value::Null, "NoneType"),
+            (Value::Binary(vec![1, 2]), "bytes"),
+            (Value::List(vec![]), "list"),
+            (Value::Date(0), "date"),
+        ] {
+            let Err(error) = df.fillna_value(value.clone(), None) else {
+                panic!("{value:?} must be rejected");
+            };
+            assert_eq!(
+                condition(error),
+                (
+                    SparkErrorKind::TypeError,
+                    Some("NOT_EXPECTED_TYPE".to_string()),
+                    Some("value".to_string()),
+                    Some(arg_type.to_string())
+                )
+            );
+            let Err(error) = df.fillna_map(vec![("id".into(), value)]) else {
+                panic!("{arg_type} must be rejected in a map");
+            };
+            assert_eq!(
+                condition(error).2.as_deref(),
+                Some("value type of dict"),
+                "{arg_type}"
+            );
+        }
+        let Err(empty) = df.fillna_map(vec![]) else {
+            panic!("an empty map must be rejected");
+        };
+        assert_eq!(empty.kind, SparkErrorKind::ValueError);
+        assert_eq!(empty.get_condition().as_deref(), Some("CANNOT_BE_EMPTY"));
+    }
+
     fn session() -> SparkSession {
         SparkSession::builder()
             .remote("sc://localhost:15002")
diff --git a/crates/spark-connect/src/plan.rs b/crates/spark-connect/src/plan.rs
index b9e8cfed..d838bb11 100644
--- a/crates/spark-connect/src/plan.rs
+++ b/crates/spark-connect/src/plan.rs
@@ -2541,44 +2541,48 @@ pub fn na_fill(
     }
 }
 
-/// Build a proto `Literal` from a [`crate::row::Value`] (used by NAFill).
+/// The proto `Literal` of a fill of NAFill, as PySpark's 
`NAFill._convert_value` sends it: a
+/// bool as a boolean, an integer as a long, a float as a double and a string 
as a string, the
+/// only types that the server's NAFill takes. `DataFrame::fillna_value` takes 
no other value. For
+/// one that a plan built directly holds, the literal is of its own type, or 
empty for a nested
+/// value, so that the server rejects it instead of filling a string column 
with a text of it.
 fn value_to_proto_literal(v: &crate::row::Value) -> proto::expression::Literal 
{
     use crate::row::Value;
     use proto::expression::literal::LiteralType;
-    let mut lit = proto::expression::Literal::default();
-    lit.literal_type = Some(match v {
-        Value::Bool(b) => LiteralType::Boolean(*b),
-        Value::Byte(x) => LiteralType::Byte(*x as i32),
-        Value::Short(x) => LiteralType::Short(*x as i32),
-        Value::Integer(x) => LiteralType::Integer(*x),
-        Value::Long(x) => LiteralType::Long(*x),
-        Value::Float(x) => LiteralType::Float(*x),
-        Value::Double(x) => LiteralType::Double(*x),
-        Value::String(s) => LiteralType::String(s.clone()),
-        Value::Date(d) => LiteralType::Date(*d),
-        Value::Timestamp(t) => LiteralType::Timestamp(*t),
-        Value::TimestampNtz(t) => LiteralType::TimestampNtz(*t),
-        // Spark rejects interval NA fills. Preserve the type so it errors 
instead
-        // of silently filling string columns with the Value's Debug text.
-        Value::DayTimeInterval(t) => LiteralType::DayTimeInterval(*t),
+    let literal_type = match v {
+        Value::Bool(b) => Some(LiteralType::Boolean(*b)),
+        Value::Byte(x) => Some(LiteralType::Long(i64::from(*x))),
+        Value::Short(x) => Some(LiteralType::Long(i64::from(*x))),
+        Value::Integer(x) => Some(LiteralType::Long(i64::from(*x))),
+        Value::Long(x) => Some(LiteralType::Long(*x)),
+        Value::Float(x) => Some(LiteralType::Double(f64::from(*x))),
+        Value::Double(x) => Some(LiteralType::Double(*x)),
+        Value::String(s) => Some(LiteralType::String(s.clone())),
+        Value::Binary(b) => Some(LiteralType::Binary(b.clone().into())),
+        Value::Date(d) => Some(LiteralType::Date(*d)),
+        Value::Timestamp(t) => Some(LiteralType::Timestamp(*t)),
+        Value::TimestampNtz(t) => Some(LiteralType::TimestampNtz(*t)),
+        Value::DayTimeInterval(t) => Some(LiteralType::DayTimeInterval(*t)),
         Value::Decimal {
             value,
             precision,
             scale,
-        } => {
-            let mut decimal = proto::expression::literal::Decimal::default();
-            decimal.value = value.clone();
-            if let Some(p) = precision {
-                decimal.precision = Some(*p);
-            }
-            if let Some(s) = scale {
-                decimal.scale = Some(*s);
-            }
-            LiteralType::Decimal(decimal)
-        }
-        other => LiteralType::String(format!("{:?}", other)),
-    });
-    lit
+        } => Some(LiteralType::Decimal(proto::expression::literal::Decimal {
+            value: value.clone(),
+            precision: *precision,
+            scale: *scale,
+        })),
+        Value::Null
+        | Value::Time(_)
+        | Value::List(_)
+        | Value::Map(_)
+        | Value::Struct(_)
+        | Value::Variant { .. } => None,
+    };
+    proto::expression::Literal {
+        literal_type,
+        ..Default::default()
+    }
 }
 
 /// The literal of a replacement given as a string: a double for a 
numeric-looking string,
diff --git a/crates/spark-connect/tests/e2e_coverage.rs 
b/crates/spark-connect/tests/e2e_coverage.rs
index b5a8665d..0624b6ae 100644
--- a/crates/spark-connect/tests/e2e_coverage.rs
+++ b/crates/spark-connect/tests/e2e_coverage.rs
@@ -901,10 +901,12 @@ fn dataframe_extra_surface() {
     let _ = na_df.fillna_bool(false, Some(vec!["b"])).collect().unwrap();
     let _ = na_df
         .fillna_value(Value::Double(1.0), Some(vec!["d"]))
+        .unwrap()
         .collect()
         .unwrap();
     let _ = na_df
         .fillna_map(vec![("d".to_string(), Value::Double(9.0))])
+        .unwrap()
         .collect()
         .unwrap();
 
diff --git a/crates/spark-connect/tests/e2e_ops_breadth.rs 
b/crates/spark-connect/tests/e2e_ops_breadth.rs
index e6e8628b..2bd3dae3 100644
--- a/crates/spark-connect/tests/e2e_ops_breadth.rs
+++ b/crates/spark-connect/tests/e2e_ops_breadth.rs
@@ -200,6 +200,46 @@ fn aggregates_execute() {
     let _ = df.observe("obs", vec![expr(f::sum(col("v")))]).collect();
 }
 
+/// As PySpark's `fillna`, which sends an int as a long and a float as a 
double: the server's
+/// fill takes those, so an `Integer` and a `Float` fill their columns, where 
the server rejected
+/// the integer literal before; and a value PySpark does not take is an error, 
not a string fill.
+#[test]
+fn fill_values_are_sent_as_pyspark_sends_them() {
+    use spark_connect::row::Value;
+    if !should_run() {
+        return;
+    }
+    let s = session();
+    let df = s
+        .sql(
+            "SELECT CAST(NULL AS BIGINT) AS i, CAST(NULL AS DOUBLE) AS d, \
+             CAST(NULL AS STRING) AS n",
+        )
+        .unwrap();
+    let row = df
+        .fillna_value(Value::Integer(5), Some(vec!["i"]))
+        .unwrap()
+        .fillna_value(Value::Float(1.5), Some(vec!["d"]))
+        .unwrap()
+        .collect()
+        .unwrap()
+        .remove(0);
+    assert_eq!(row.get(0).and_then(|v| v.as_i64()), Some(5));
+    assert_eq!(row.get(1).and_then(|v| v.as_f64()), Some(1.5));
+    assert!(df.fillna_value(Value::Null, Some(vec!["n"])).is_err());
+    let mapped = df
+        .fillna_map(vec![
+            ("i".to_string(), Value::Short(7)),
+            ("n".to_string(), Value::String("x".to_string())),
+        ])
+        .unwrap()
+        .collect()
+        .unwrap()
+        .remove(0);
+    assert_eq!(mapped.get(0).and_then(|v| v.as_i64()), Some(7));
+    assert_eq!(mapped.get(2).and_then(|v| v.as_str()), Some("x"));
+}
+
 /// NA / stat / reshape / schema-shaping operations.
 #[test]
 fn na_reshape_execute() {
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 08e79700..f4a0b98e 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -20,6 +20,13 @@ microseconds. Downstream exhaustive matches on these public 
enums must handle
 the new variant. Rust interval map keys are stringified as raw microseconds;
 Python `timedelta` map keys are not yet supported.
 
+`DataFrame::fillna_value` and `DataFrame::fillna_map` return a `Result`, as
+`dropna` does. As PySpark's `fillna`, they take a bool, an integer, a float or 
a
+string (an integer is sent as a long, a float as a double), and reject other 
values
+with `NOT_EXPECTED_TYPE` and an empty map with `CANNOT_BE_EMPTY`. Before, such 
a
+value filled string columns with its debug text. `fillna`, `fillna_double`,
+`fillna_string` and `fillna_bool` are unchanged.
+
 The 4.3 line changes the public Rust representation of expressions and logical
 plans to share immutable nodes. This is a breaking change for code that 
directly
 constructs or matches these representations. The `Column` and `DataFrame` APIs,


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

Reply via email to