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 cdf38e87 [SPARK-61417][CONNECT][PYTHON][FOLLOWUP] Take probabilityCol 
in BinaryClassificationEvaluator, and raise protobuf's ValueError for a str 
that UTF-8 cannot encode in option keys, the runtime conf, fills and SQL text, 
as PySpark does
cdf38e87 is described below

commit cdf38e8734619bf95aa9a0e6d12ed53240bb29ac
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 16:36:06 2026 +0900

    [SPARK-61417][CONNECT][PYTHON][FOLLOWUP] Take probabilityCol in 
BinaryClassificationEvaluator, and raise protobuf's ValueError for a str that 
UTF-8 cannot encode in option keys, the runtime conf, fills and SQL text, as 
PySpark does
    
    ### What changes were proposed in this pull request?
    
    A follow-up of #495 (SPARK-61417), from a review of it. Two of its items 
did not hold for every path.
    
    1. **`BinaryClassificationEvaluator` takes PySpark's `probabilityCol`.** 
#495 said that the three evaluators of `pyspark.ml.connect` show PySpark's 
signatures. The binary one took `rawPredictionCol='rawPrediction'`. PySpark's 
is `BinaryClassificationEvaluator(*, metricName='areaUnderROC', 
labelCol='label', probabilityCol='probability')` 
(pyspark/ml/connect/evaluation.py:186-203), and it has no `rawPredictionCol`.
       - The Python class now takes `probabilityCol`, defaulting to 
`"probability"`, and `setProbabilityCol`. `rawPredictionCol=` raises the 
`TypeError` of an unexpected argument, as in PySpark.
       - The class still evaluates through the server's evaluator, which scores 
its `rawPredictionCol`. So the probability column is sent as that param 
(`Native::jvm_name`). The JVM evaluator reads a probability vector at its 
element 1, the positive class, and takes a double column as it is.
       - The constructor sends the default, as the multiclass evaluator sends 
`accuracy`, because the JVM default is `rawPrediction`.
       - The Rust API (`crates/spark-connect`) keeps Spark's 
`raw_prediction_col`. `docs/compatibility.md` says so.
    2. **Protobuf's `ValueError` for a str that UTF-8 cannot encode, in the 
paths that #495 missed.** #495 made the keys and values of the reader, writer, 
stream and session options raise protobuf's `ValueError` for a str with a lone 
surrogate. Several sibling paths still raised the `UnicodeEncodeError` that 
PyO3's extraction of a str gives. PySpark raises protobuf's `ValueError` 
("'a\ud800b' isn't a valid unicode string and can't be encoded in UTF-8.") when 
the str goes into a request. T [...]
       - the key of `option()` of `DataFrameReader`, `DataFrameWriter`, 
`DataFrameWriterV2`, `DataStreamReader` and `DataStreamWriter`;
       - the key and the value of `RuntimeConf.set`, and the key of `get`, 
`unset` and `isModifiable`;
       - the key of `SparkSession.builder.config(key, value)`;
       - a str fill value of `fillna`, a key of its dict and a name of its 
subset. #495 had made these raise the `UnicodeEncodeError` of the encoding;
       - the text of `spark.sql`, the keys of its `args` dict, and the name of 
`spark.table`.
    
    ### Why are the changes needed?
    
    To match PySpark 4.3.0. Probes with the Connect client of official PySpark 
4.3.0 and with this client, against a local Spark 4.3.0 server:
    
    - PySpark's docstring example of `BinaryClassificationEvaluator` (a 
DataFrame with the columns `label` and `probability`, evaluated with the 
defaults) failed in this client with `[FIELD_NOT_FOUND] No such struct field 
'rawPrediction'`. It now evaluates on `probability`. The metric is the 
server's, as before. Its `areaUnderPR` is 0.9027777777777777 (Spark's 
trapezoids over the thresholds), where PySpark's torcheval metric gives the 
docstring's 0.9166666865348816. That is an existing di [...]
    - Of 18 calls with a str that has a lone surrogate (the fill value, dict 
key and subset of `fillna`, the option keys of the five readers and writers, 
the four conf methods, `builder.config`, `table` and `sql`), this client raised 
`UnicodeEncodeError` for 14. PySpark raises protobuf's `ValueError` for each. 
All 18 now raise PySpark's `ValueError`, with its message.
    
    One difference remains: PySpark keeps the options of a reader or writer, 
and `builder.config`, and raises when it builds the request of the action 
(`load`, `save`, `getOrCreate`). This client raises at the call, as before this 
PR.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, on unreleased changes:
    - `pyspark.ml.connect.evaluation.BinaryClassificationEvaluator` takes 
`probabilityCol` (default `"probability"`) and `setProbabilityCol`, instead of 
`rawPredictionCol` and `setRawPredictionCol`.
    - The paths above raise protobuf's `ValueError` instead of 
`UnicodeEncodeError` for a str that UTF-8 cannot encode. `UnicodeEncodeError` 
is a `ValueError` too.
    
    ### How was this patch tested?
    
    Each new or changed test fails on an extension built from master and passes 
with the change:
    - `test_ml_offline.py`:
      - 
`test_ml_connect_evaluators_take_the_signatures_and_defaults_of_pyspark` now 
expects `probabilityCol`;
      - new 
`test_ml_connect_binary_evaluator_sends_its_probability_col_as_the_jvm_raw_prediction`;
      - the tests that compare the params a class sends include the default 
`probabilityCol`.
    - `test_ml_e2e.py`, against a local Spark 4.3.0 server:
      - new 
`test_ml_connect_binary_evaluator_scores_the_probability_of_pyspark_docstring`;
      - the existing evaluator test uses `probabilityCol`.
    - `test_dropin_offline.py`:
      - 
`test_strings_that_utf8_cannot_encode_raise_value_error_as_options_and_fills_as_pyspark`
 now asserts the message of the fill value, dict key and subset;
      - new 
`test_strings_that_utf8_cannot_encode_raise_value_error_in_option_keys_conf_and_names_as_pyspark`.
    - The offline drop-in and ML suites (2007 passed), the live 
`test_ml_e2e.py` and `test_dropin_e2e.py` against a Spark 4.3.0 server (288 
passed), `cargo build -p pyspark-rs --release`, `cargo test -p 
apache-spark-connect -p apache-spark-connect-core --release --no-run`, `cargo 
fmt --all -- --check`, `ruff check`, and `scripts/audit_no_stubs.sh`.
    
    ### 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 #550 from HyukjinKwon/SPARK-61417-followup-evaluator-strings.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/conf.rs           | 26 +++++++++----
 crates/pyspark-rs/src/dataframe.rs      | 12 +++---
 crates/pyspark-rs/src/lib.rs            |  2 +-
 crates/pyspark-rs/src/ml.rs             | 68 ++++++++++++++++++++++++++-------
 crates/pyspark-rs/src/options.rs        |  9 +++++
 crates/pyspark-rs/src/readwriter.rs     |  7 ++--
 crates/pyspark-rs/src/session.rs        | 14 ++++---
 crates/pyspark-rs/src/stat_arguments.rs | 13 +++++--
 crates/pyspark-rs/src/streaming.rs      | 10 +++--
 docs/compatibility.md                   | 10 +++--
 python/tests/test_dropin_offline.py     | 45 +++++++++++++++++++++-
 python/tests/test_ml_e2e.py             | 28 +++++++++++---
 python/tests/test_ml_offline.py         | 65 ++++++++++++++++++++++++++-----
 13 files changed, 245 insertions(+), 64 deletions(-)

diff --git a/crates/pyspark-rs/src/conf.rs b/crates/pyspark-rs/src/conf.rs
index 5dce064f..5b5999a2 100644
--- a/crates/pyspark-rs/src/conf.rs
+++ b/crates/pyspark-rs/src/conf.rs
@@ -48,7 +48,7 @@ impl<'a, 'py> FromPyObject<'a, 'py> for ConfDefault {
 /// `RuntimeConf._checkType`.
 fn checked_str(obj: &Bound<'_, PyAny>, name: &str) -> PyResult<String> {
     match obj.cast::<pyo3::types::PyString>() {
-        Ok(text) => Ok(text.to_cow()?.into_owned()),
+        Ok(text) => crate::str_argument(text.as_any()),
         Err(_) => Err(crate::stat_arguments::not_expected_type(obj, name, 
"str")),
     }
 }
@@ -70,7 +70,7 @@ fn conf_value(value: &Bound<'_, PyAny>) -> 
PyResult<Option<String>> {
         return Ok(Some(value.str()?.to_cow()?.into_owned()));
     }
     if let Ok(text) = value.cast::<PyString>() {
-        return Ok(Some(text.to_cow()?.into_owned()));
+        return Ok(Some(crate::str_argument(text.as_any())?));
     }
     let shown = value.repr()?;
     if let Ok(bytes) = value.cast::<PyBytes>() {
@@ -109,11 +109,17 @@ impl PyRuntimeConf {
     /// Set a configuration value, as PySpark's: a bool as "true" or "false", 
an int as its
     /// `str()`, a str as it is, and None as no value, which the server 
rejects. Warns each
     /// warning of the server.
-    fn set(&self, py: Python<'_>, key: &str, value: &Bound<'_, PyAny>) -> 
PyResult<()> {
+    fn set(
+        &self,
+        py: Python<'_>,
+        key: &Bound<'_, PyAny>,
+        value: &Bound<'_, PyAny>,
+    ) -> PyResult<()> {
+        let key = crate::str_argument(key)?;
         let value = conf_value(value)?;
         let warnings = interruptible(py, &self.session, || {
             self.conf
-                .set_pairs(&[(key, value.as_deref())], None)
+                .set_pairs(&[(key.as_str(), value.as_deref())], None)
                 .map_err(Box::new)
         })?;
         warn_all(py, &warnings)
@@ -153,8 +159,11 @@ impl PyRuntimeConf {
 
     /// Reset a configuration value to its default. Warns each warning of the 
server, as
     /// PySpark's.
-    fn unset(&self, py: Python<'_>, key: &str) -> PyResult<()> {
-        let warnings = interruptible(py, &self.session, || 
self.conf.unset(key).map_err(Box::new))?;
+    fn unset(&self, py: Python<'_>, key: &Bound<'_, PyAny>) -> PyResult<()> {
+        let key = crate::str_argument(key)?;
+        let warnings = interruptible(py, &self.session, || {
+            self.conf.unset(&key).map_err(Box::new)
+        })?;
         warn_all(py, &warnings)
     }
 
@@ -186,9 +195,10 @@ impl PyRuntimeConf {
     }
 
     #[pyo3(name = "isModifiable")]
-    fn is_modifiable(&self, py: Python<'_>, key: &str) -> PyResult<bool> {
+    fn is_modifiable(&self, py: Python<'_>, key: &Bound<'_, PyAny>) -> 
PyResult<bool> {
+        let key = crate::str_argument(key)?;
         interruptible(py, &self.session, || {
-            self.conf.is_modifiable(key).map_err(Box::new)
+            self.conf.is_modifiable(&key).map_err(Box::new)
         })
     }
 
diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index eb365d47..52da6bd6 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -3563,13 +3563,14 @@ impl PyDataFrameWriter {
 
     fn option<'py>(
         slf: &Bound<'py, Self>,
-        key: &str,
+        key: &Bound<'_, PyAny>,
         value: &Bound<'_, PyAny>,
     ) -> PyResult<Bound<'py, Self>> {
+        let key = crate::str_argument(key)?;
         // None -> option left unset; bools -> "true"/"false" (reference 
`to_str`).
         match crate::coerce_option_value(value)? {
             Some(v) => {
-                slf.borrow().inner.update(|w| w.option(key, &v));
+                slf.borrow().inner.update(|w| w.option(&key, &v));
                 Ok(slf.clone())
             }
             None => Ok(slf.clone()),
@@ -3666,7 +3667,7 @@ impl PyDataFrameWriter {
         if let Some(props) = properties {
             for (key, value) in props.iter() {
                 if let Some(value) = crate::coerce_option_value(&value)? {
-                    w = w.option(&key.str()?.to_cow()?, &value);
+                    w = w.option(&crate::str_text(&key)?, &value);
                 }
             }
         }
@@ -3986,12 +3987,13 @@ impl PyDataFrameWriterV2 {
     // the other reader/writer option bindings.
     fn option<'py>(
         slf: &Bound<'py, Self>,
-        key: &str,
+        key: &Bound<'_, PyAny>,
         value: &Bound<'_, PyAny>,
     ) -> PyResult<Bound<'py, Self>> {
+        let key = crate::str_argument(key)?;
         match crate::coerce_option_value(value)? {
             Some(v) => {
-                slf.borrow().inner.update(|w| w.option(key, &v));
+                slf.borrow().inner.update(|w| w.option(&key, &v));
                 Ok(slf.clone())
             }
             None => Ok(slf.clone()),
diff --git a/crates/pyspark-rs/src/lib.rs b/crates/pyspark-rs/src/lib.rs
index 4beb2d55..e4b30ff7 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -57,7 +57,7 @@ use dataframe::{
 };
 use datasource::PyDataSourceRegistration;
 use group::{PyCoGroupedData, PyGroupedData};
-pub(crate) use options::{coerce_option_value, str_text};
+pub(crate) use options::{coerce_option_value, str_argument, str_text};
 use readwriter::PyDataFrameReader;
 use resource::{
     PyExecutorResourceRequests, PyResourceProfile, PyResourceProfileBuilder, 
PyTaskResourceRequests,
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index de337bf8..de7029ea 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -118,6 +118,10 @@ trait Native {
     fn params(&self) -> &Params;
     fn unsendable(&self) -> &[&'static str];
     fn unsendable_mut(&mut self) -> &mut Vec<&'static str>;
+    /// The name of the param `name` in the JVM class, where it is not the 
name of PySpark's.
+    fn jvm_name(name: &'static str) -> &'static str {
+        name
+    }
 }
 
 macro_rules! native {
@@ -146,19 +150,20 @@ macro_rules! native {
 /// Set the param `name` of `target` to `value`.
 fn apply<T: Native>(target: &mut T, name: &'static str, value: Converted) {
     target.unsendable_mut().retain(|unsent| *unsent != name);
+    let jvm = T::jvm_name(name);
     let params = std::mem::take(target.params_mut());
     let params = match value {
-        Converted::Null => params.set_param_null(name),
+        Converted::Null => params.set_param_null(jvm),
         Converted::Unsendable => {
             target.unsendable_mut().push(name);
-            params.clear_param(name)
+            params.clear_param(jvm)
         }
-        Converted::Int(value) => params.set_param_int_narrow(name, value),
-        Converted::Float(value) => params.set_param_double(name, value),
-        Converted::Str(value) => params.set_param_string(name, &value),
-        Converted::Bool(value) => params.set_param_bool(name, value),
-        Converted::StrList(values) => params.set_param_string_array(name, 
values),
-        Converted::FloatList(values) => params.set_param_double_array(name, 
values),
+        Converted::Int(value) => params.set_param_int_narrow(jvm, value),
+        Converted::Float(value) => params.set_param_double(jvm, value),
+        Converted::Str(value) => params.set_param_string(jvm, &value),
+        Converted::Bool(value) => params.set_param_bool(jvm, value),
+        Converted::StrList(values) => params.set_param_string_array(jvm, 
values),
+        Converted::FloatList(values) => params.set_param_double_array(jvm, 
values),
     };
     *target.params_mut() = params;
 }
@@ -1925,21 +1930,57 @@ pub struct PyBinaryClassificationEvaluator {
     unsendable: Vec<&'static str>,
 }
 
+/// The JVM evaluator scores its rawPredictionCol, so the probability column 
of PySpark's
+/// evaluator is sent as that param: a probability vector is read at its 
element 1, as the
+/// positive class of PySpark's evaluator.
+impl Native for PyBinaryClassificationEvaluator {
+    type Core = BinaryClassificationEvaluator;
+    fn inner(&self) -> &BinaryClassificationEvaluator {
+        &self.inner
+    }
+    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
+    }
+    fn unsendable_mut(&mut self) -> &mut Vec<&'static str> {
+        &mut self.unsendable
+    }
+    fn jvm_name(name: &'static str) -> &'static str {
+        if name == "probabilityCol" {
+            "rawPredictionCol"
+        } else {
+            name
+        }
+    }
+}
+
 #[pymethods]
 impl PyBinaryClassificationEvaluator {
     #[new]
     #[pyo3(
         signature = (*args, **kwargs),
-        text_signature = "(*, metricName='areaUnderROC', labelCol='label', 
rawPredictionCol='rawPrediction')"
+        text_signature = "(*, metricName='areaUnderROC', labelCol='label', 
probabilityCol='probability')"
     )]
     fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) -> 
PyResult<Self> {
         let mut this = Self {
             inner: BinaryClassificationEvaluator::new(),
             unsendable: Vec::new(),
         };
+        // As PySpark's, whose constructor sets the probability column 
"probability" by default,
+        // where the JVM evaluator's default is "rawPrediction".
+        apply(
+            &mut this,
+            "probabilityCol",
+            Converted::Str("probability".to_string()),
+        );
         let params = &[
             ("labelCol", Kind::Str),
-            ("rawPredictionCol", Kind::Str),
+            ("probabilityCol", Kind::Str),
             ("metricName", Kind::Str),
         ];
         init_params(
@@ -1959,12 +2000,12 @@ impl PyBinaryClassificationEvaluator {
     ) -> PyResult<Bound<'py, Self>> {
         set_param(slf, "labelCol", Kind::Str, value)
     }
-    #[pyo3(name = "setRawPredictionCol")]
-    fn set_raw_prediction_col<'py>(
+    #[pyo3(name = "setProbabilityCol")]
+    fn set_probability_col<'py>(
         slf: Bound<'py, Self>,
         value: &Bound<'py, PyAny>,
     ) -> PyResult<Bound<'py, Self>> {
-        set_param(slf, "rawPredictionCol", Kind::Str, value)
+        set_param(slf, "probabilityCol", Kind::Str, value)
     }
     #[pyo3(name = "setMetricName")]
     fn set_metric_name<'py>(
@@ -2150,7 +2191,6 @@ native!(
     PyRandomForestRegressor => RandomForestRegressor,
     PyKMeans => KMeans,
     PyRegressionEvaluator => RegressionEvaluator,
-    PyBinaryClassificationEvaluator => BinaryClassificationEvaluator,
     PyMulticlassClassificationEvaluator => MulticlassClassificationEvaluator,
     PyPipeline => Pipeline,
     PyCrossValidator => CrossValidator,
diff --git a/crates/pyspark-rs/src/options.rs b/crates/pyspark-rs/src/options.rs
index 98d9cfaa..996aa64b 100644
--- a/crates/pyspark-rs/src/options.rs
+++ b/crates/pyspark-rs/src/options.rs
@@ -44,6 +44,15 @@ pub(crate) fn str_text(v: &Bound<'_, PyAny>) -> 
PyResult<String> {
         .map_err(|_| crate::functions::not_utf8_string(text.as_any()))
 }
 
+/// The text of a str argument, as a protobuf string field takes it: the text 
of the str itself,
+/// which PyO3's extraction of a str gives, and protobuf's `ValueError` for a 
str that UTF-8
+/// cannot encode. Another type is a `TypeError`, as that extraction raises.
+pub(crate) fn str_argument(v: &Bound<'_, PyAny>) -> PyResult<String> {
+    let text = v.cast::<PyString>()?;
+    text.extract::<String>()
+        .map_err(|_| crate::functions::not_utf8_string(v))
+}
+
 /// A reader or writer that takes string options one at a time.
 pub(crate) trait OptionBuilder: Sized {
     fn with_option(self, key: &str, value: &str) -> Self;
diff --git a/crates/pyspark-rs/src/readwriter.rs 
b/crates/pyspark-rs/src/readwriter.rs
index 04932658..114c5a6a 100644
--- a/crates/pyspark-rs/src/readwriter.rs
+++ b/crates/pyspark-rs/src/readwriter.rs
@@ -244,10 +244,11 @@ impl PyDataFrameReader {
     /// string "None"); booleans lowercase to "true"/"false" (reference 
`to_str` semantics).
     fn option<'py>(
         mut slf: PyRefMut<'py, Self>,
-        key: &str,
+        key: &Bound<'_, PyAny>,
         value: &Bound<'_, PyAny>,
     ) -> PyResult<PyRefMut<'py, Self>> {
-        slf.inner = set_reader_option_unset_none(slf.inner.clone(), key, 
value)?;
+        let key = crate::str_argument(key)?;
+        slf.inner = set_reader_option_unset_none(slf.inner.clone(), &key, 
value)?;
         Ok(slf)
     }
 
@@ -692,7 +693,7 @@ impl PyDataFrameReader {
         };
         if let Some(properties) = properties {
             for (key, value) in properties.iter() {
-                r = set_option_skip_none(r, &key.str()?.to_cow()?, 
Some(&value))?;
+                r = set_option_skip_none(r, &crate::str_text(&key)?, 
Some(&value))?;
             }
         }
         // PySpark's jdbc also leaves url/dbtable on the reader.
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index dd24a4c9..0d315ef9 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -101,18 +101,19 @@ impl PySparkSessionBuilder {
     #[pyo3(signature = (key=None, value=None, map=None, conf=None))]
     fn config<'py>(
         mut slf: PyRefMut<'py, Self>,
-        key: Option<&str>,
+        key: Option<&Bound<'_, PyAny>>,
         value: Option<&Bound<'_, PyAny>>,
         map: Option<&Bound<'_, PyDict>>,
         conf: Option<&Bound<'_, PyAny>>,
     ) -> PyResult<PyRefMut<'py, Self>> {
         let py = slf.py();
         if let Some(k) = key {
+            let k = crate::str_argument(k)?;
             let v = match value {
                 Some(v) => crate::coerce_option_value(v)?,
                 None => None,
             };
-            slf.set_option_value(py, k, v)?;
+            slf.set_option_value(py, &k, v)?;
         }
         if let Some(m) = map {
             for (k, v) in m.iter() {
@@ -1982,7 +1983,7 @@ impl PySparkSession {
     #[pyo3(signature = (sqlQuery, args=None, **kwargs))]
     fn sql(
         slf: &Bound<'_, Self>,
-        sqlQuery: &str,
+        sqlQuery: &Bound<'_, PyAny>,
         args: Option<Bound<'_, PyAny>>,
         kwargs: Option<Bound<'_, PyDict>>,
     ) -> PyResult<PyDataFrame> {
@@ -1993,6 +1994,7 @@ impl PySparkSession {
             }
             Ok(crate::functions::to_column(v)?.expression().clone())
         }
+        let sqlQuery = crate::str_argument(sqlQuery)?;
         let py = slf.py();
         let mut pos: Vec<spark_connect::expression::Expression> = Vec::new();
         let mut named: std::collections::HashMap<String, 
spark_connect::expression::Expression> =
@@ -2004,7 +2006,7 @@ impl PySparkSession {
                     let k = k
                         .cast::<pyo3::types::PyString>()
                         .map_err(|_| 
pyo3::exceptions::PyAssertionError::new_err(()))?;
-                    named.insert(k.to_cow()?.into_owned(), to_lit(&v)?);
+                    named.insert(crate::str_argument(k.as_any())?, 
to_lit(&v)?);
                 }
             } else if let Ok(lst) = a.cast::<PyList>() {
                 for v in lst.iter() {
@@ -3009,7 +3011,9 @@ impl PySparkSession {
             ));
         };
         Ok(PyDataFrame::new(
-            self.session.table(&name.to_cow()?).to_pyerr()?,
+            self.session
+                .table(&crate::str_argument(name.as_any())?)
+                .to_pyerr()?,
         ))
     }
 
diff --git a/crates/pyspark-rs/src/stat_arguments.rs 
b/crates/pyspark-rs/src/stat_arguments.rs
index 1138e296..3b34c4e4 100644
--- a/crates/pyspark-rs/src/stat_arguments.rs
+++ b/crates/pyspark-rs/src/stat_arguments.rs
@@ -40,7 +40,7 @@ fn subset_columns(subset: Option<&Bound<'_, PyAny>>, 
expected: &str) -> PyResult
         return Ok(Vec::new());
     };
     if subset.is_instance_of::<PyString>() {
-        return Ok(vec![subset.extract()?]);
+        return Ok(vec![crate::str_argument(subset)?]);
     }
     if !is_sequence(subset) {
         return Err(not_expected_type(subset, "subset", expected));
@@ -50,7 +50,7 @@ fn subset_columns(subset: Option<&Bound<'_, PyAny>>, 
expected: &str) -> PyResult
         .map(|column| {
             let column = column?;
             if column.is_instance_of::<PyString>() {
-                column.extract()
+                crate::str_argument(&column)
             } else {
                 Err(not_expected_type(&column, "cols", "list, str or tuple"))
             }
@@ -167,7 +167,7 @@ pub(crate) fn fillna(
     if let Some(dict) = dict {
         let mut pairs = Vec::with_capacity(dict.len());
         for (column, fill) in dict.iter() {
-            pairs.push((column.extract()?, fill_value(&fill)?));
+            pairs.push((crate::str_argument(&column)?, fill_value(&fill)?));
         }
         return Ok(PyDataFrame::new(df.fillna_map(pairs).to_pyerr()?));
     }
@@ -180,6 +180,13 @@ pub(crate) fn fillna(
 /// The value of a fill. As PySpark sends it as a proto literal, an int beyond 
a long is out of
 /// range for the proto, which raises `ValueError`, not the error of a literal.
 fn fill_value(value: &Bound<'_, PyAny>) -> PyResult<spark_connect::row::Value> 
{
+    // A str is sent in a protobuf string field, which raises the ValueError 
of a str that UTF-8
+    // cannot encode, as `str_argument` does.
+    if value.is_instance_of::<PyString>() {
+        return Ok(spark_connect::row::Value::String(crate::str_argument(
+            value,
+        )?));
+    }
     if value.is_instance_of::<PyInt>()
         && !value.is_instance_of::<pyo3::types::PyBool>()
         && value.extract::<i64>().is_err()
diff --git a/crates/pyspark-rs/src/streaming.rs 
b/crates/pyspark-rs/src/streaming.rs
index 40f79bed..c2b5d953 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -322,14 +322,15 @@ impl PyDataStreamReader {
 
     fn option<'py>(
         mut slf: PyRefMut<'py, Self>,
-        key: &str,
+        key: &Bound<'_, PyAny>,
         value: &Bound<'_, PyAny>,
     ) -> PyResult<PyRefMut<'py, Self>> {
+        let key = crate::str_argument(key)?;
         // None -> option left unset; other values as `str()`, so a bool is 
"True" (reference
         // `DataStreamReader.option`, unlike `options` and `load`).
         match crate::options::stream_option_value(value)? {
             Some(v) => {
-                slf.inner = slf.inner.clone().option(key, &v);
+                slf.inner = slf.inner.clone().option(&key, &v);
                 Ok(slf)
             }
             None => Ok(slf),
@@ -833,13 +834,14 @@ impl PyDataStreamWriter {
 
     fn option<'py>(
         slf: &Bound<'py, Self>,
-        key: &str,
+        key: &Bound<'_, PyAny>,
         value: &Bound<'_, PyAny>,
     ) -> PyResult<Bound<'py, Self>> {
+        let key = crate::str_argument(key)?;
         // None -> option left unset; bools -> "true"/"false" (reference 
`to_str`).
         match crate::coerce_option_value(value)? {
             Some(v) => {
-                slf.borrow().inner.update(|w| w.option(key, &v));
+                slf.borrow().inner.update(|w| w.option(&key, &v));
                 Ok(slf.clone())
             }
             None => Ok(slf.clone()),
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 1a66cdf3..454c0cdb 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -23,8 +23,10 @@ Python `timedelta` map keys are not yet supported.
 `BinaryClassificationEvaluator::set_score_col` and `score_col`, and the Python
 `scoreCol=` argument and `setScoreCol` of v4.2.0 are removed, without an alias:
 Spark's evaluator has no `scoreCol` param, so no value of it worked on the 
server.
-Use `set_raw_prediction_col` and `raw_prediction_col` (Python 
`rawPredictionCol=` and
-`setRawPredictionCol`), the column of raw prediction vectors that the 
evaluator scores.
+Use `set_raw_prediction_col` and `raw_prediction_col` in Rust, the column of 
raw prediction
+vectors that the evaluator scores. In Python, as in PySpark, it is 
`probabilityCol=` and
+`setProbabilityCol`, the column of probabilities, which the server reads as 
its raw prediction
+column.
 
 The native ML classes take a JVM `Int` param as an `i32`: 
`LogisticRegression::set_max_iter`,
 `LinearSVC::set_max_iter` and `LinearSVC::set_aggregation_depth` take an 
`i32`, and
@@ -181,7 +183,9 @@ The Python classes of the native estimators, transformers 
and evaluators of
 keyword-only, raising PySpark's `TypeError`, except 
`MulticlassClassificationEvaluator`,
 which takes `metricName`, `labelCol` and `predictionCol` by position as well, 
as
 PySpark's does; its `metricName` is `accuracy` by default, as in PySpark, 
where the JVM
-evaluator and the Rust API default to `f1`. Each value is converted by the 
`TypeConverters` of its param in
+evaluator and the Rust API default to `f1`. The `probabilityCol` of
+`BinaryClassificationEvaluator` is `probability` by default, as in PySpark, 
and is sent as the
+`rawPredictionCol` that the JVM evaluator scores. Each value is converted by 
the `TypeConverters` of its param in
 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
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 90047b8c..dab7ba86 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -6912,11 +6912,52 @@ def 
test_strings_that_utf8_cannot_encode_raise_value_error_as_options_and_fills_
         lambda: spark.readStream.text("/t", lineSep=bad),
         lambda: spark.readStream.format("text").option("path", bad),
         lambda: SparkSession.builder.config(map={bad: "v"}),
+        lambda: SparkSession.builder.config(bad, "v"),
     ]:
         with pytest.raises(ValueError, match=message):
             call()
-    with pytest.raises(ValueError):
-        df.fillna(bad)
+    # The fill of a value, of a dict's key and of a subset column is sent in a 
string field too.
+    for call in [
+        lambda: df.fillna(bad),
+        lambda: df.fillna({bad: 1}),
+        lambda: df.fillna("x", subset=[bad]),
+    ]:
+        with pytest.raises(ValueError, match=message):
+            call()
+
+
+def 
test_strings_that_utf8_cannot_encode_raise_value_error_in_option_keys_conf_and_names_as_pyspark(
+    mock_connect,
+):
+    # As PySpark, whose protobuf string fields raise the ValueError of a str 
that UTF-8 cannot
+    # encode, for the key of an option, a key or value of the runtime conf, a 
name of a table and
+    # the text of a query, where the UnicodeEncodeError of its encoding raised 
before.
+    spark, service = mock_connect
+    bad = "a\ud800b"
+    message = re.escape(f"{bad!r} isn't a valid unicode string and can't be 
encoded in UTF-8.")
+    df = spark.range(1)
+    for call in [
+        lambda: spark.read.option(bad, "v"),
+        lambda: df.write.option(bad, "v"),
+        lambda: df.writeTo("t").option(bad, "v"),
+        lambda: spark.readStream.option(bad, "v"),
+        lambda: spark.readStream.format("rate").load().writeStream.option(bad, 
"v"),
+        lambda: spark.conf.set(bad, "v"),
+        lambda: spark.conf.set("spark.k", bad),
+        lambda: spark.conf.get(bad),
+        lambda: spark.conf.unset(bad),
+        lambda: spark.conf.isModifiable(bad),
+        lambda: spark.table(bad),
+    ]:
+        with pytest.raises(ValueError, match=message):
+            call()
+    query = "select '" + bad + "'"
+    with pytest.raises(ValueError) as error:
+        spark.sql(query)
+    assert str(error.value) == (
+        f"{query!r} isn't a valid unicode string and can't be encoded in 
UTF-8."
+    )
+    assert service.execute_requests == []
 
 
 def test_functions_levenshtein():
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index e2d75507..ea24f115 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -375,8 +375,8 @@ def test_ml_feature_transformers_as_pyspark(session):
 
 def test_ml_connect_vector_assembler_and_evaluator_as_pyspark(session):
     # pyspark.ml.connect's VectorAssembler sends inputCols as a list of 
strings, and the native
-    # BinaryClassificationEvaluator scores its rawPredictionCol (default 
rawPrediction), with
-    # the values of PySpark 4.3.0.
+    # BinaryClassificationEvaluator scores its probabilityCol (default 
probability), which the
+    # JVM evaluator reads as its rawPredictionCol, with the values of PySpark 
4.3.0.
     from pyspark.ml.connect.evaluation import BinaryClassificationEvaluator
     from pyspark.ml.connect.feature import VectorAssembler
     from pyspark.ml.functions import array_to_vector
@@ -392,15 +392,31 @@ def 
test_ml_connect_vector_assembler_and_evaluator_as_pyspark(session):
     scores = [(0.0, 0.1), (0.0, 0.4), (1.0, 0.35), (1.0, 0.8)]
     raw = session.createDataFrame(scores, "label double, score double").select(
         "label",
-        array_to_vector(F.array(1.0 - F.col("score"), 
F.col("score"))).alias("rawPrediction"),
+        array_to_vector(F.array(1.0 - F.col("score"), 
F.col("score"))).alias("probability"),
     )
     assert BinaryClassificationEvaluator().evaluate(raw) == 0.75
-    evaluator = 
BinaryClassificationEvaluator(rawPredictionCol="rawPrediction", 
labelCol="label")
+    evaluator = BinaryClassificationEvaluator(probabilityCol="probability", 
labelCol="label")
     assert evaluator.evaluate(raw) == 0.75
-    pr = BinaryClassificationEvaluator(metricName="areaUnderPR", 
rawPredictionCol="rawPrediction")
+    pr = BinaryClassificationEvaluator(metricName="areaUnderPR", 
probabilityCol="probability")
     assert pr.evaluate(raw) == pytest.approx(0.7916666666666666)
 
 
+def 
test_ml_connect_binary_evaluator_scores_the_probability_of_pyspark_docstring(session):
+    # The example of PySpark's BinaryClassificationEvaluator: probabilities 
that are not vectors,
+    # and the default probabilityCol, which the evaluator reads with no other 
option. The metric
+    # is that of the server's evaluator: its areaUnderPR is the trapezoids of 
Spark's thresholds,
+    # 0.9027777777777777, where PySpark's torcheval metric of the docstring 
gives 0.9166666865.
+    from pyspark.ml.connect.evaluation import BinaryClassificationEvaluator
+
+    dataset = session.createDataFrame(
+        [(1, 0.6), (0, 0.55), (0, 0.1), (1, 0.6), (1, 0.4)],
+        schema=["label", "probability"],
+    )
+    pr = BinaryClassificationEvaluator(metricName="areaUnderPR")
+    assert pr.evaluate(dataset) == pytest.approx(0.9027777777777777, abs=1e-9)
+    assert BinaryClassificationEvaluator().evaluate(dataset) == 
pytest.approx(5 / 6, abs=1e-9)
+
+
 def 
test_ml_connect_setters_change_the_next_evaluate_and_fit_as_pyspark(session):
     # As PySpark's Params._set: a setter of pyspark.ml.connect sets the param 
of the evaluator or
     # estimator itself and returns it, so the next evaluate or fit uses the 
value of a setter whose
@@ -430,7 +446,7 @@ def 
test_ml_connect_setters_change_the_next_evaluate_and_fit_as_pyspark(session)
     assert multiclass.setMetricName("accuracy") is multiclass
     assert multiclass.evaluate(scored) == 0.75  # The f1 is 0.733.
     binary = BinaryClassificationEvaluator()
-    assert binary.setRawPredictionCol("score") is binary  # No rawPrediction 
column is there.
+    assert binary.setProbabilityCol("score") is binary  # No probability 
column is there.
     assert binary.evaluate(scored) == 0.75
     assert binary.setMetricName("areaUnderPR") is binary
     assert binary.evaluate(scored) == pytest.approx(0.7916666666666666)
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index 516f1516..a018f7a2 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -274,7 +274,7 @@ def 
test_ml_connect_setters_set_the_params_of_their_receiver_as_pyspark(ml_mock)
         (RegressionEvaluator, dict(labelCol="y", predictionCol="p", 
metricName="r2")),
         (
             BinaryClassificationEvaluator,
-            dict(labelCol="y", rawPredictionCol="r", metricName="areaUnderPR"),
+            dict(labelCol="y", probabilityCol="p", metricName="areaUnderPR"),
         ),
         (
             MulticlassClassificationEvaluator,
@@ -289,7 +289,8 @@ def 
test_ml_connect_setters_set_the_params_of_their_receiver_as_pyspark(ml_mock)
             # By the name of the argument of PySpark's setters, value.
             assert getattr(receiver, setter)(value=values[name]) is receiver, 
(cls, setter)
         params = sent_params(receiver)
-        assert {name: params.get(name) for name in values} == values, cls
+        sent_values = {_sent_name(cls.__name__, name): value for name, value 
in values.items()}
+        assert {name: params.get(name) for name in sent_values} == 
sent_values, cls
         assert params == sent_params(cls(**values)), cls
 
 
@@ -388,7 +389,7 @@ _NATIVE_PARAMS = {
         solver="str", maxBlockSizeInMB="float",
     ),
     "RegressionEvaluator": dict(labelCol="str", predictionCol="str", 
metricName="str"),
-    "BinaryClassificationEvaluator": dict(labelCol="str", 
rawPredictionCol="str", metricName="str"),
+    "BinaryClassificationEvaluator": dict(labelCol="str", 
probabilityCol="str", metricName="str"),
     "MulticlassClassificationEvaluator": dict(
         metricName="str", labelCol="str", predictionCol="str"
     ),
@@ -450,11 +451,22 @@ def _literal_value(literal):
     return kind, getattr(literal, kind)
 
 
+def _sent_name(name, param):
+    # The name of a param in the request: the probability column of PySpark's
+    # BinaryClassificationEvaluator is the rawPredictionCol that the JVM 
evaluator scores.
+    if (name, param) == ("BinaryClassificationEvaluator", "probabilityCol"):
+        return "rawPredictionCol"
+    return param
+
+
 def _defaults_sent(name):
     # The params that a native class sends unless it is given them: the metric 
of
-    # MulticlassClassificationEvaluator, which PySpark's constructor sets.
+    # MulticlassClassificationEvaluator and the probability column of
+    # BinaryClassificationEvaluator, which PySpark's constructor sets.
     if name == "MulticlassClassificationEvaluator":
         return {"metricName": ("string", "accuracy")}
+    if name == "BinaryClassificationEvaluator":
+        return {"rawPredictionCol": ("string", "probability")}
     return {}
 
 
@@ -524,7 +536,9 @@ def 
test_ml_connect_params_convert_with_the_type_converters_of_pyspark(ml_mock):
                     if name in _NOT_FITTABLE:
                         continue  # Their params are sent by no request.
                     sent = _native_sent(spark, service, obj, models)
-                    assert sent == {**_defaults_sent(name), param: expected}, 
(name, param, value)
+                    assert sent == {
+                        **_defaults_sent(name), _sent_name(name, param): 
expected
+                    }, (name, param, value)
             for value, message in _NATIVE_REJECTED[kind]:
                 expected = f'Invalid param value given for param "{param}". 
{message}'
                 with pytest.raises(TypeError) as error:
@@ -572,7 +586,7 @@ def 
test_ml_connect_evaluators_take_the_signatures_and_defaults_of_pyspark(ml_mo
     signatures = {
         "RegressionEvaluator": "(*, metricName='rmse', labelCol='label', 
predictionCol='prediction')",
         "BinaryClassificationEvaluator":
-            "(*, metricName='areaUnderROC', labelCol='label', 
rawPredictionCol='rawPrediction')",
+            "(*, metricName='areaUnderROC', labelCol='label', 
probabilityCol='probability')",
         "MulticlassClassificationEvaluator":
             "(metricName='accuracy', labelCol='label', 
predictionCol='prediction')",
     }
@@ -591,6 +605,36 @@ def 
test_ml_connect_evaluators_take_the_signatures_and_defaults_of_pyspark(ml_mo
     }
 
 
+def 
test_ml_connect_binary_evaluator_sends_its_probability_col_as_the_jvm_raw_prediction(ml_mock):
+    # As PySpark's BinaryClassificationEvaluator, whose probabilityCol 
defaults to "probability"
+    # and which has no rawPredictionCol. The JVM evaluator scores its 
rawPredictionCol, so the
+    # probability column is sent as that param.
+    import pyspark.ml.connect as connect
+
+    spark, service = ml_mock
+    models = []
+    evaluator = connect.BinaryClassificationEvaluator
+    assert _native_sent(spark, service, evaluator(), models) == {
+        "rawPredictionCol": ("string", "probability")
+    }
+    assert _native_sent(spark, service, evaluator(probabilityCol="p"), models) 
== {
+        "rawPredictionCol": ("string", "p")
+    }
+    binary = evaluator(metricName="areaUnderPR", labelCol="y", 
probabilityCol="p")
+    assert _native_sent(spark, service, binary, models) == {
+        "metricName": ("string", "areaUnderPR"),
+        "labelCol": ("string", "y"),
+        "rawPredictionCol": ("string", "p"),
+    }
+    with pytest.raises(TypeError) as error:
+        evaluator(rawPredictionCol="r")
+    assert str(error.value) == (
+        "BinaryClassificationEvaluator.__init__() got an unexpected keyword 
argument "
+        "'rawPredictionCol'"
+    )
+    assert not hasattr(evaluator(), "setRawPredictionCol")
+
+
 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
@@ -635,13 +679,14 @@ 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
+            sent_name = _sent_name(name, param)
             sent = _native_sent(spark, service, obj, models)
-            assert sent.keys() == {param} | _defaults_sent(name).keys(), 
(name, param)
-            assert _native_sent(spark, service, obj, models)[param][0] == 
"null", (name, param)
+            assert sent.keys() == {sent_name} | _defaults_sent(name).keys(), 
(name, param)
+            assert sent[sent_name][0] == "null", (name, param)
             if param != "thresholds":
                 sent = _native_sent(spark, service, cls(**{param: None}), 
models)
-                assert sent.keys() == {param} | _defaults_sent(name).keys(), 
(name, param)
-                assert sent[param][0] == "null", (name, param)
+                assert sent.keys() == {sent_name} | 
_defaults_sent(name).keys(), (name, param)
+                assert sent[sent_name][0] == "null", (name, param)
         operator, _ = _native_request(spark, service, cls(), models)
         assert re.fullmatch(name + "_[0-9a-f]{12}", operator.uid), operator.uid
 


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

Reply via email to