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 627c63ee [SPARK-61391][CONNECT][PYTHON] Send an explicit None param as 
a null literal, and raise CANNOT_INFER_ARRAY_ELEMENT_TYPE for an empty list 
param, in the native ML classes of the Python client as PySpark does
627c63ee is described below

commit 627c63ee7442b41226a54937466d6f4ba8735455
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 09:24:38 2026 +0900

    [SPARK-61391][CONNECT][PYTHON] Send an explicit None param as a null 
literal, and raise CANNOT_INFER_ARRAY_ELEMENT_TYPE for an empty list param, in 
the native ML classes of the Python client as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61391](https://issues.apache.org/jira/browse/SPARK-61391): a 
follow-up of #467 (SPARK-61358), #446 (SPARK-61324) and #475 (SPARK-61386), 
from a review of #467 and #446, for the native `pyspark.ml.connect` classes of 
the Python client:
    
    - An explicit `None` param is sent as a null literal, as PySpark's 
`Params._set` stores it and `serialize_ml_params` sends it. The new 
`Params::set_param_null` sets it, used where #475's conversion returned 
`Converted::Clear` (now `Converted::Null`). Params that are not given stay 
unsent, as in #475, and the Rust API's `clear_param` stays for Rust callers.
    - A list param that is empty (`VectorAssembler(inputCols=[])`, 
`RandomForestClassifier.setThresholds([])`, `Pipeline(stages=[])`, and the 
other list params) raises `PySparkTypeError [CANNOT_INFER_ARRAY_ELEMENT_TYPE]` 
when the params are sent, at fit, transform or evaluate, before any request, as 
PySpark raises it when it serializes them. Constructors and setters still 
accept `[]`, as PySpark's do.
    - A string array param is sent with the `UTF8_BINARY` collation, as 
PySpark's literal of a list of strings is (it was empty).
    - The test of #475 that expected `None` to leave a param unset, and the 
`None` sentence of `docs/compatibility.md`, are updated.
    
    ### Why are the changes needed?
    
    - `RandomForestClassifier(bootstrap=None)` fit a forest with the default 
`bootstrap=True` in the drop-in, while PySpark sends a null that the server 
fits as `bootstrap=False`, so the forests differ. With `seed=None`, 
`weightCol=None`, `impurity=None`, `leafCol=None` or `featuresCol=None`, 
PySpark's fit fails on the server (`NullPointerException`), while the drop-in 
fit silently with the default.
    - `VectorAssembler(inputCols=[], outputCol="f").transform(df)` gave each 
row an empty vector, and `setThresholds([])` failed on the server with 
"thresholds has length 0", where PySpark raises 
`CANNOT_INFER_ARRAY_ELEMENT_TYPE` before sending anything.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. An explicit `None` param is sent as PySpark sends it, so the server 
gives the same result or error, and an empty list param raises 
`CANNOT_INFER_ARRAY_ELEMENT_TYPE` at fit, transform or evaluate, as in PySpark.
    
    ### How was this patch tested?
    
    - Offline tests in `python/tests/test_ml_offline.py`: the null literal of 
`bootstrap=None`, an unset param not sent, the empty-list error at fit and 
transform with no request sent, and the `UTF8_BINARY` array literal of a 
non-empty list. #475's None test is updated.
    - An e2e test in `python/tests/test_ml_e2e.py` against a Spark 4.3.0 
server: `bootstrap=None` gives the same probabilities as `bootstrap=False`, and 
`seed=None` fails with the server's `NullPointerException`, as in PySpark.
    - Rust unit tests for the null and empty-array params and the string array 
collation.
    - `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 ML and drop-in offline suites.
    
    ### 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 #487 from HyukjinKwon/SPARK-61391-ml-null-and-empty-params.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/ml.rs     | 25 ++++++++++----
 crates/spark-connect/src/ml.rs  | 72 ++++++++++++++++++++++++++++++++++++++++-
 docs/compatibility.md           |  7 ++--
 python/tests/test_ml_e2e.py     | 20 ++++++++++++
 python/tests/test_ml_offline.py | 54 +++++++++++++++++++++++++++----
 5 files changed, 162 insertions(+), 16 deletions(-)

diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index a65dafce..e4ef1002 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -62,9 +62,9 @@ static TYPE_CONVERTERS: pyo3::sync::PyOnceLock<Py<PyType>> = 
pyo3::sync::PyOnceL
 
 /// The value of a param, as PySpark's `Params._set` converts it.
 enum Converted {
-    /// None, which leaves the param unset, so that the server uses its 
default. PySpark sends a
-    /// null, which the server rejects (a NullPointerException for a number).
-    Clear,
+    /// None, which PySpark sends as a null literal: the server rejects a null 
number (a
+    /// NullPointerException), and reads a null bootstrap as false.
+    Null,
     Int(i64),
     /// An int beyond a long, which PySpark's `LiteralExpression` cannot send.
     Unsendable,
@@ -79,7 +79,7 @@ enum Converted {
 /// TypeError of `Params._set` for a value that it cannot convert.
 fn convert(name: &str, kind: Kind, value: &Bound<'_, PyAny>) -> 
PyResult<Converted> {
     if value.is_none() {
-        return Ok(Converted::Clear);
+        return Ok(Converted::Null);
     }
     let py = value.py();
     let converters = TYPE_CONVERTERS.import(py, "pyspark.ml.param", 
"TypeConverters")?;
@@ -114,6 +114,7 @@ trait Native {
     fn params_mut(&mut self) -> &mut Params;
     /// The params whose value PySpark cannot send: a fit, transform or 
evaluate raises PySpark's
     /// error of its serialization of the params, before any request.
+    fn params(&self) -> &Params;
     fn unsendable(&self) -> &[&'static str];
     fn unsendable_mut(&mut self) -> &mut Vec<&'static str>;
 }
@@ -128,6 +129,9 @@ macro_rules! native {
             fn params_mut(&mut self) -> &mut Params {
                 self.inner.params_mut()
             }
+            fn params(&self) -> &Params {
+                self.inner.params()
+            }
             fn unsendable(&self) -> &[&'static str] {
                 &self.unsendable
             }
@@ -143,7 +147,7 @@ fn apply<T: Native>(target: &mut T, name: &'static str, 
value: Converted) {
     target.unsendable_mut().retain(|unsent| *unsent != name);
     let params = std::mem::take(target.params_mut());
     let params = match value {
-        Converted::Clear => params.clear_param(name),
+        Converted::Null => params.set_param_null(name),
         Converted::Unsendable => {
             target.unsendable_mut().push(name);
             params.clear_param(name)
@@ -231,12 +235,21 @@ fn init_params<T: Native>(
 /// The core object of `slf`, cloned under a short borrow, so that a setter 
that another
 /// thread calls while a fit, transform or evaluate waits for the server does 
not fail. As
 /// PySpark's serialization of the params, it first raises `VALUE_NOT_BETWEEN` 
of an int
-/// that PySpark cannot send.
+/// that PySpark cannot send, and `CANNOT_INFER_ARRAY_ELEMENT_TYPE` of a list 
param without
+/// elements, whose element type PySpark cannot infer.
 fn snapshot<T: Native + PyClass>(slf: &Bound<'_, T>) -> PyResult<T::Core> {
     let this = slf.try_borrow()?;
     if !this.unsendable().is_empty() {
         return Err(crate::functions::value_not_between(slf.py()));
     }
+    if this.params().has_empty_array() {
+        return Err(crate::column::raise_pyspark(
+            slf.py(),
+            "PySparkTypeError",
+            "CANNOT_INFER_ARRAY_ELEMENT_TYPE",
+            &[],
+        ));
+    }
     Ok(this.inner().clone())
 }
 
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index c66efc70..ef76e446 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -85,7 +85,7 @@ impl Params {
             .collect();
         let literal = LiteralExpression::Array {
             element_type: Box::new(DataType::String {
-                collation: String::new(),
+                collation: "UTF8_BINARY".to_string(),
             }),
             elements,
         }
@@ -161,6 +161,40 @@ impl Params {
         self
     }
 
+    /// Set a parameter to a null, as PySpark sends a None value of a param it 
was given.
+    pub fn set_param_null(mut self, name: &str) -> Self {
+        let literal = proto::expression::Literal {
+            literal_type: Some(proto::expression::literal::LiteralType::Null(
+                DataType::Null.to_proto(),
+            )),
+            ..Default::default()
+        };
+        self.params.insert(
+            name.to_string(),
+            proto::Expression {
+                expr_type: Some(proto::expression::ExprType::Literal(literal)),
+                ..Default::default()
+            },
+        );
+        self
+    }
+
+    /// Whether a parameter is an array without elements. PySpark cannot infer 
the element type
+    /// of such an array, so it cannot send the params that hold one.
+    pub fn has_empty_array(&self) -> bool {
+        self.params.values().any(|expr| {
+            matches!(
+                &expr.expr_type,
+                Some(proto::expression::ExprType::Literal(lit))
+                    if matches!(
+                        &lit.literal_type,
+                        
Some(proto::expression::literal::LiteralType::Array(array))
+                            if array.elements.is_empty()
+                    )
+            )
+        })
+    }
+
     /// Get a parameter value.
     pub fn get_param(&self, name: &str) -> Option<&proto::Expression> {
         self.params.get(name)
@@ -2891,6 +2925,42 @@ mod tests {
         assert!(params.get_param("outputCol").is_some());
     }
 
+    #[test]
+    fn test_params_null_and_empty_arrays() {
+        let params = Params::new()
+            .set_param_null("weightCol")
+            .set_param_string_array("inputCols", &["a".to_string()]);
+        let null = params.to_proto();
+        assert!(matches!(
+            null.params["weightCol"].literal_type,
+            Some(proto::expression::literal::LiteralType::Null(_))
+        ));
+        assert!(!params.has_empty_array());
+
+        let empty = Params::new().set_param_string_array("inputCols", 
Vec::<String>::new());
+        assert!(empty.has_empty_array());
+        let empty = Params::new().set_param_double_array("thresholds", []);
+        assert!(empty.has_empty_array());
+        assert!(!Params::new().set_param_null("x").has_empty_array());
+    }
+
+    #[test]
+    #[allow(deprecated)]
+    fn test_string_array_param_has_the_default_collation() {
+        // As PySpark infers the type of a list of strings: a string of the 
UTF8_BINARY collation.
+        let params = Params::new().set_param_string_array("inputCols", 
&["a".to_string()]);
+        let literal = params.to_proto().params["inputCols"].clone();
+        let Some(proto::expression::literal::LiteralType::Array(array)) = 
literal.literal_type
+        else {
+            panic!("expected an array literal");
+        };
+        let element_type = array.element_type.expect("element type");
+        let Some(proto::data_type::Kind::String(string)) = element_type.kind 
else {
+            panic!("expected a string element type");
+        };
+        assert_eq!(string.collation, "UTF8_BINARY");
+    }
+
     #[test]
     fn test_ml_operator_creation() {
         let op = MlOperator::new(
diff --git a/docs/compatibility.md b/docs/compatibility.md
index fcef5ab7..e60f1bc8 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -172,8 +172,11 @@ PySpark (an integral float for an int param, for example), 
and a value that the
 converter rejects raises its `TypeError`. A fit, transform or evaluate sends 
only the
 params that the constructor or a setter set, so the server applies its 
defaults to
 the others, as with PySpark. An int beyond a long raises PySpark's
-`VALUE_NOT_BETWEEN` at the next fit. `None` leaves a param unset, so the 
server's
-default applies; PySpark sends a null, which the server rejects.
+`VALUE_NOT_BETWEEN` at the next fit. `None` is sent as a null literal, as 
PySpark sends
+it: the server reads a null `bootstrap` as false and rejects the other nulls. 
A param that is
+not given is not sent, so the server's default applies. A list param without 
elements is
+accepted by its constructor and setters, and a fit, transform or evaluate 
raises PySpark's
+`CANNOT_INFER_ARRAY_ELEMENT_TYPE` for it, as PySpark's serialization does.
 
 ## Native RandomForestClassifier
 
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 3d3f2651..c47b3fff 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -55,6 +55,26 @@ def _labeled(session):
     return session.createDataFrame(rows, ["id", "label", "features"])
 
 
+def test_ml_connect_random_forest_null_bootstrap_fits_as_pyspark(session):
+    # As PySpark, a None param is sent as a null: the server reads a null 
bootstrap as false, so
+    # the forest of bootstrap=None is the forest of bootstrap=False, and a 
null seed fails.
+    from pyspark.ml.connect.classification import RandomForestClassifier
+
+    df = _labeled(session)
+
+    def probabilities(estimator):
+        return [
+            row.probability.toArray().tolist()
+            for row in estimator.fit(df).transform(df).orderBy("id").collect()
+        ]
+
+    assert probabilities(RandomForestClassifier(bootstrap=None, numTrees=5, 
seed=42)) == (
+        probabilities(RandomForestClassifier(bootstrap=False, numTrees=5, 
seed=42))
+    )
+    with pytest.raises(Exception, match="NullPointerException"):
+        RandomForestClassifier(numTrees=5, seed=None).fit(df)
+
+
 def test_ml_connect_scalers_fit_and_transform_as_pyspark(session):
     # pyspark.ml.connect's StandardScaler, MaxAbsScaler and StringIndexer: the 
server fits each one
     # and caches the model, and the transform of the model gives the values of 
PySpark 4.3.0.
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index 0f8a3327..dc2c9e8e 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -484,9 +484,8 @@ def 
test_ml_connect_constructors_send_only_the_params_they_are_given_as_pyspark(
 def test_ml_connect_unsendable_ints_none_and_uids_as_pyspark(ml_mock):
     # As PySpark: an int beyond a long is taken by the constructor and the 
setter, and the
     # next fit raises the VALUE_NOT_BETWEEN of PySpark's serialization of the 
params, before
-    # any request, until the param is set again. None leaves a param unset, 
where PySpark
-    # sends a null that the server rejects (a NullPointerException for a 
number). The uid of
-    # every native class is the name of its class and 12 hex digits, as 
PySpark's.
+    # any request, until the param is set again. None is sent as a null, as 
PySpark sends it.
+    # The uid of every native class is the name of its class and 12 hex 
digits, as PySpark's.
     import re
 
     import pyspark.ml.connect as connect
@@ -511,8 +510,9 @@ def 
test_ml_connect_unsendable_ints_none_and_uids_as_pyspark(ml_mock):
     estimator = connect.KMeans(seed=2**64)
     assert estimator.setSeed(5) is estimator
     assert _native_sent(spark, service, estimator, models) == {"seed": 
("integer", 5)}
-    assert _native_sent(spark, service, connect.KMeans(seed=2**64, 
k=2).setSeed(None),
-                        models) == {"k": ("integer", 2)}
+    sent = _native_sent(spark, service, connect.KMeans(seed=2**64, 
k=2).setSeed(None), models)
+    assert sent.keys() == {"k", "seed"} and sent["k"] == ("integer", 2)
+    assert sent["seed"][0] == "null"
 
     for name, params in _NATIVE_PARAMS.items():
         cls = getattr(connect, name)
@@ -522,9 +522,11 @@ def 
test_ml_connect_unsendable_ints_none_and_uids_as_pyspark(ml_mock):
             obj = cls()
             assert getattr(obj, setter)(value) is obj
             assert getattr(obj, setter)(None) is obj
-            assert _native_sent(spark, service, obj, models) == {}, (name, 
param)
+            assert _native_sent(spark, service, obj, models).keys() == 
{param}, (name, param)
+            assert _native_sent(spark, service, obj, models)[param][0] == 
"null", (name, param)
             if param != "thresholds":
-                assert _native_sent(spark, service, cls(**{param: None}), 
models) == {}
+                sent = _native_sent(spark, service, cls(**{param: None}), 
models)
+                assert sent.keys() == {param} and sent[param][0] == "null", 
(name, param)
         operator, _ = _native_request(spark, service, cls(), models)
         assert re.fullmatch(name + "_[0-9a-f]{12}", operator.uid), operator.uid
 
@@ -2243,3 +2245,41 @@ def 
test_session_hooks_raise_their_errors_as_pyspark(_ml_mock_server):
         assert service.execute_requests == []
     finally:
         spark.stop()
+
+
+def 
test_ml_none_params_send_null_and_empty_lists_raise_at_the_command_as_pyspark(ml_mock):
+    # As PySpark's Params._set: None is stored and sent as a null literal, and 
a param that is
+    # not given is not sent. A list without elements is accepted by the 
constructor and the
+    # setters, and PySpark raises CANNOT_INFER_ARRAY_ELEMENT_TYPE when its 
serialization sends
+    # the params of a fit, transform or evaluate, before any request.
+    import pyspark.ml.connect as connect
+    from pyspark.ml.connect.pipeline import Pipeline
+
+    spark, service = ml_mock
+    df = spark.range(1)
+    models = []
+
+    sent = _native_sent(spark, service, 
connect.RandomForestClassifier(bootstrap=None), models)
+    assert sent.keys() == {"bootstrap"} and sent["bootstrap"][0] == "null"
+    assert "bootstrap" not in _native_sent(
+        spark, service, connect.RandomForestClassifier(numTrees=3), models
+    )
+
+    assembler = connect.VectorAssembler(inputCols=[], outputCol="f")
+    before = len(service.execute_requests)
+    with pytest.raises(PySparkTypeError, 
match="CANNOT_INFER_ARRAY_ELEMENT_TYPE") as error:
+        assembler.transform(df)
+    assert error.value.getCondition() == "CANNOT_INFER_ARRAY_ELEMENT_TYPE"
+    with pytest.raises(PySparkTypeError, 
match="CANNOT_INFER_ARRAY_ELEMENT_TYPE"):
+        connect.RandomForestClassifier().setThresholds([]).fit(df)
+    with pytest.raises(PySparkTypeError, 
match="CANNOT_INFER_ARRAY_ELEMENT_TYPE"):
+        Pipeline(stages=[]).fit(df)
+    assert len(service.execute_requests) == before
+
+    # Elements given again make the list sendable.
+    assert assembler.setInputCols(["a", "b"]) is assembler
+    _, params = _native_request(spark, service, assembler, models)
+    expected = 'array { element_type { %s } elements { string: "a" } elements 
{ string: "b" } }'
+    assert params.params["inputCols"] == text_format.Parse(
+        expected % _UTF8, pb2.Expression.Literal()
+    )


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

Reply via email to