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 a9398ea1 [SPARK-61524][CONNECT][PYTHON] Raise the errors of protobuf's 
default backend for the values that PySpark sets in proto fields, as PySpark 
does
a9398ea1 is described below

commit a9398ea1a5a5a8b6c9ac24103c519c5534ab2e5f
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 20:28:03 2026 +0900

    [SPARK-61524][CONNECT][PYTHON] Raise the errors of protobuf's default 
backend for the values that PySpark sets in proto fields, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    A follow-up from a review of the last 20 commits (#550 and others). The 
Python drop-in raised the errors of protobuf's **pure-Python** backend where 
PySpark sets a value in a proto field. A default install of `pyspark-client` 
uses protobuf's **upb** backend. The pure-Python backend is used only when 
`PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python` is set, which the environment 
where the earlier changes were calibrated exports. Under upb, official PySpark 
4.3.0 does the following, and t [...]
    
    - **A str that UTF-8 cannot encode** (a lone surrogate) raises the 
`UnicodeEncodeError` of its encoding, `'utf-8' codec can't encode character 
'\ud800' in position 1: surrogates not allowed`. This was `ValueError: '...' 
isn't a valid unicode string and can't be encoded in UTF-8.` in literals, 
options, fills, the runtime conf, table names and sql. `not_utf8_string` is 
removed, and PyO3's error of the extraction is raised as it is.
    - **Bytes in a string field** are decoded as UTF-8 
(`PyUnicode_FromEncodedObject`, as upb), and bytes that are not UTF-8 raise the 
`UnicodeDecodeError` of their decoding. This applies where PySpark sets the 
value as it is:
      - the key and the value of `spark.conf.set`, and the key of `unset` and 
`isModifiable`;
      - the keys of `SparkSession.builder.config`, also of `map=`;
      - the option keys of the writers (`df.write`, `writeTo`, `writeStream`);
      - the text of `spark.sql`;
      - the names of `_joinAsOf`'s `on` and of `replace`'s subset;
      - the values of `createTable`'s options.
    - **Any other object in a string field** raises `TypeError: bad argument 
type for built-in operation`. The drop-in raised `Cannot set 
spark.connect.KeyValue.value to ...`, `... has type ..., but expected one of: 
...`, or PyO3's cast error.
    - **A bool in an int field**, `dropna(thresh=True)` and `sampleBy(..., 
seed=True)`, raises `TypeError: Field spark.connect.NADrop.min_non_nulls: 
Expected an int, got a boolean.` (and `spark.connect.StatSampleBy.seed`). The 
drop-in raised the pure-Python backend's `Cannot set ... to True: True has type 
<class 'bool'>, but expected one of: (int).`
    - **`StreamingQuery.explain(extended)`** reads `extended` as a C long 
(`PyLong_AsLong`), and a NumPy bool by its truth. Another object raises the 
`TypeError` or `OverflowError` of that conversion, and a NumPy array raises 
`[1] has type ndarray, but expected one of: bool`. The conversion now runs in 
the call, as PyO3 would prefix an argument's `TypeError` with its name.
    
    Siblings found while probing the same paths, also as PySpark:
    - `DataFrameReader.option` and `DataStreamReader.option` keep the key in a 
dict, and their `DataSource` plan asserts that a key is a str. A key that is 
not a str, bytes too, raises a bare `AssertionError`.
    - The `option` of a writer or of `DataStreamReader` returns at once for a 
value of None, before it looks at the key (B-4 of the review). 
`DataFrameReader.option` hashes the key even then.
    - A key kept in a dict raises the `TypeError` of an unhashable key 
(`unhashable type: 'bytearray'`).
    - An as-of column of `_joinAsOf` that is not a Column or a str raises 
PySpark's `ColumnReference` `AssertionError`, and the as-of columns are 
converted before `on`.
    - `spark.conf.set(None, v)` and `builder.config(map={None: v})` send the 
empty key, as the constructor of `KeyValue` leaves a field of None unset.
    - `spark.sql` checks `args`, then formats the query object as it is, and 
only then sets it in the plan. So `spark.sql(b"... {x}", x=1)` raises the 
formatter's `expected str, got bytes`.
    
    ### Why are the changes needed?
    
    To match PySpark 4.3.0 as installed by default. Three probe scripts of 
about 130 cases each ran on the same Spark 4.3.0 server: against official 
PySpark under upb (`env -u PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION`), with 
protobuf 7.36.2 and with 6.33.6, and against this branch. This branch's outputs 
are identical to official's on protobuf 7.36.2, apart from the module path in 
the repr of the session and stream writer objects, which this PR does not touch.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. In the Python client:
    - These paths raise the error class and message of PySpark as installed by 
default.
    - Bytes are accepted where PySpark accepts them.
    - A None option value no longer checks its key.
    
    ### How was this patch tested?
    
    - Updated the tests that pinned the pure-Python backend's texts, in 
`python/tests/test_dropin_offline.py`, to upb's exact messages and classes:
      - the conf;
      - the two surrogate tests of options, keys, conf, names and sql;
      - literals and sql args;
      - the seeds of sampleBy;
      - explain;
      - createTable.
    - Two new tests:
      - 
`test_protobuf_string_fields_take_bytes_and_refuse_other_objects_as_pyspark`, 
which checks what is sent for bytes and the errors of other objects;
      - `test_option_keys_are_checked_as_the_dicts_and_the_plans_of_pyspark`.
    - `python/tests/_mock_connect_server.py` records a `KeyValue` with no key 
as the empty key.
    - All 11 changed or new tests fail on the drop-in before this change.
    - `cargo build -p pyspark-rs --release`, the offline drop-in suites 
(`test_dropin_offline.py`, `test_arrow_handoff.py`), `cargo fmt --all --check`, 
`ruff check`, `scripts/audit_no_stubs.sh`, and clippy, with no new warnings in 
the changed code.
    
    ### 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 #560 from HyukjinKwon/SPARK-61524-upb-proto-errors.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/conf.rs           |  34 ++---
 crates/pyspark-rs/src/dataframe.rs      | 116 ++++++---------
 crates/pyspark-rs/src/functions.rs      |  45 ++----
 crates/pyspark-rs/src/options.rs        |  77 +++++-----
 crates/pyspark-rs/src/readwriter.rs     |  12 +-
 crates/pyspark-rs/src/session.rs        |  20 ++-
 crates/pyspark-rs/src/stat.rs           |   5 +-
 crates/pyspark-rs/src/stat_arguments.rs |  19 +--
 crates/pyspark-rs/src/streaming.rs      |  76 +++++++---
 python/tests/_mock_connect_server.py    |   5 +-
 python/tests/test_dropin_offline.py     | 250 +++++++++++++++++++++++++-------
 11 files changed, 401 insertions(+), 258 deletions(-)

diff --git a/crates/pyspark-rs/src/conf.rs b/crates/pyspark-rs/src/conf.rs
index 5b5999a2..442fa353 100644
--- a/crates/pyspark-rs/src/conf.rs
+++ b/crates/pyspark-rs/src/conf.rs
@@ -54,10 +54,10 @@ fn checked_str(obj: &Bound<'_, PyAny>, name: &str) -> 
PyResult<String> {
 }
 
 /// The value of `RuntimeConf.set`, as PySpark sends it in a `KeyValue`: a 
bool as "true" or
-/// "false", an int as its `str()`, a str, or UTF-8 bytes, as it is, and None 
as no value,
-/// which the server rejects. Another value is the `TypeError` of protobuf, as 
in PySpark.
+/// "false", an int as its `str()`, and None as no value, which the server 
rejects. Any other
+/// value is set in the string field as it is, as [`crate::str_argument`] 
converts it.
 fn conf_value(value: &Bound<'_, PyAny>) -> PyResult<Option<String>> {
-    use pyo3::types::{PyBool, PyBytes, PyInt, PyString};
+    use pyo3::types::{PyBool, PyInt};
     if value.is_none() {
         return Ok(None);
     }
@@ -69,25 +69,7 @@ fn conf_value(value: &Bound<'_, PyAny>) -> 
PyResult<Option<String>> {
     if value.is_instance_of::<PyInt>() {
         return Ok(Some(value.str()?.to_cow()?.into_owned()));
     }
-    if let Ok(text) = value.cast::<PyString>() {
-        return Ok(Some(crate::str_argument(text.as_any())?));
-    }
-    let shown = value.repr()?;
-    if let Ok(bytes) = value.cast::<PyBytes>() {
-        return String::from_utf8(bytes.as_bytes().to_vec())
-            .map(Some)
-            .map_err(|_| {
-                pyo3::exceptions::PyValueError::new_err(format!(
-                    "{shown} has type bytes, but isn't valid UTF-8 encoding. 
Non-UTF-8 strings \
-                     must be converted to unicode objects before being added."
-                ))
-            });
-    }
-    Err(pyo3::exceptions::PyTypeError::new_err(format!(
-        "Cannot set spark.connect.KeyValue.value to {shown}: {shown} has type 
{}, but expected \
-         one of: (<class 'bytes'>, <class 'str'>) for field KeyValue.value",
-        value.get_type().repr()?
-    )))
+    crate::str_argument(value).map(Some)
 }
 
 /// Warn each warning of the server, such as of a deprecated or unsupported 
configuration, as
@@ -115,7 +97,13 @@ impl PyRuntimeConf {
         key: &Bound<'_, PyAny>,
         value: &Bound<'_, PyAny>,
     ) -> PyResult<()> {
-        let key = crate::str_argument(key)?;
+        // A key of None is the empty key, as the constructor of PySpark's 
`KeyValue` leaves a
+        // field of None unset.
+        let key = if key.is_none() {
+            String::new()
+        } else {
+            crate::str_argument(key)?
+        };
         let value = conf_value(value)?;
         let warnings = interruptible(py, &self.session, || {
             self.conf
diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index 155eb5b0..1aeccda0 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -519,44 +519,10 @@ fn no_to_plan(obj: &Bound<'_, PyAny>) -> PyErr {
     ))
 }
 
-/// The `TypeError` of protobuf for a name that is not a string, which the 
plan of PySpark's
-/// `_joinAsOf` raises for a name in `on` or an as-of column that is not a 
string.
-fn proto_string_type_error(value: &Bound<'_, PyAny>) -> PyErr {
-    let repr = value
-        .repr()
-        .map(|repr| repr.to_string())
-        .unwrap_or_default();
-    let typ = value
-        .get_type()
-        .repr()
-        .map(|typ| typ.to_string())
-        .unwrap_or_default();
-    pyo3::exceptions::PyTypeError::new_err(format!(
-        "{repr} has type {typ}, but expected one of: (<class 'bytes'>, <class 
'str'>)"
-    ))
-}
-
-/// The text of the `direction` of `_joinAsOf`, as protobuf's default upb 
backend sets the string
-/// field `AsOfJoin.direction` from it when PySpark sends the plan: a str, of 
which one that UTF-8
-/// cannot encode raises the `UnicodeEncodeError` of its encoding, or bytes, 
decoded as UTF-8 with
-/// the `UnicodeDecodeError` of invalid ones. Any other value is upb's 
`TypeError`.
-fn as_of_direction(value: &Bound<'_, PyAny>) -> PyResult<String> {
-    if value.is_instance_of::<pyo3::types::PyString>() {
-        return value.extract::<String>();
-    }
-    if value.is_instance_of::<pyo3::types::PyBytes>() {
-        return value
-            .call_method1(pyo3::intern!(value.py(), "decode"), ("utf-8",))?
-            .extract::<String>();
-    }
-    Err(pyo3::exceptions::PyTypeError::new_err(
-        "bad argument type for built-in operation",
-    ))
-}
-
 /// The join condition of `_joinAsOf` for its `on`, as PySpark's `AsOfJoin` 
plan sends it: a
 /// name or a list of names (`using_columns`), or a Column or a list of 
Columns, which are
-/// joined on their conjunction (`join_expr`).
+/// joined on their conjunction (`join_expr`). The names of a list whose first 
item is a name
+/// are set in the repeated string field as they are, as 
[`crate::str_argument`] converts them.
 fn as_of_join_condition(
     on: &Bound<'_, PyAny>,
 ) -> PyResult<(Option<spark_connect::column::Column>, Vec<String>)> {
@@ -579,10 +545,7 @@ fn as_of_join_condition(
     if first.is_instance_of::<pyo3::types::PyString>() {
         let names = list
             .iter()
-            .map(|item| {
-                item.extract::<String>()
-                    .map_err(|_| proto_string_type_error(&item))
-            })
+            .map(|item| crate::str_argument(&item))
             .collect::<PyResult<Vec<_>>>()?;
         return Ok((None, names));
     }
@@ -600,7 +563,8 @@ fn as_of_join_condition(
 }
 
 /// The as-of column of `_joinAsOf` of `df`: a Column as it is, or the column 
of `df` that
-/// has this name, as PySpark's `df._col(name)`.
+/// has this name, as PySpark's `df._col(name)`, whose `ColumnReference` 
asserts that the name
+/// is a str: any other object is a bare `AssertionError`.
 fn as_of_column(
     df: &DataFrame,
     column: &Bound<'_, PyAny>,
@@ -608,10 +572,10 @@ fn as_of_column(
     if let Ok(column) = column.extract::<PyRef<PyColumn>>() {
         return Ok(column.column.clone());
     }
-    let name = column
-        .extract::<String>()
-        .map_err(|_| proto_string_type_error(column))?;
-    Ok(df.col(&name))
+    if !column.is_instance_of::<pyo3::types::PyString>() {
+        return Err(pyo3::exceptions::PyAssertionError::new_err(()));
+    }
+    Ok(df.col(&column.extract::<String>()?))
 }
 
 /// Resolve a filter/where condition: a Column, or a SQL string parsed via 
`expr`.
@@ -1111,25 +1075,29 @@ impl PyDataFrame {
                 Some(column.column.clone())
             }
         };
+        // The as-of columns before `on`, as PySpark converts them before its 
`AsOfJoin` plan
+        // iterates `on`.
+        let left_as_of = as_of_column(&self.dataframe, leftAsOfColumn)?;
+        let right_as_of = as_of_column(&other.dataframe, rightAsOfColumn)?;
         let (on, using_columns) = match on.filter(|on| !on.is_none()) {
             None => (None, Vec::new()),
             Some(on) => as_of_join_condition(&on)?,
         };
         let options = AsOfJoinOptions {
-            left_as_of: as_of_column(&self.dataframe, leftAsOfColumn)?,
-            right_as_of: as_of_column(&other.dataframe, rightAsOfColumn)?,
+            left_as_of,
+            right_as_of,
             on,
             using_columns,
             join_type,
             tolerance,
             allow_exact_matches: allowExactMatches,
-            // PySpark does not check `direction`, so its errors come last, as 
those of protobuf
-            // when the plan is sent (`as_of_direction`).
+            // PySpark does not check `direction`, so its errors come last, as 
those of protobuf's
+            // string field when the plan is sent (`crate::str_argument`).
             direction: match &direction {
                 DefaultedOption::Omitted => AsOfJoinDirection::Backward,
-                DefaultedOption::Given(direction) => {
-                    
AsOfJoinDirection::parse(&as_of_direction(direction.bind(leftAsOfColumn.py()))?)
-                }
+                DefaultedOption::Given(direction) => AsOfJoinDirection::parse(
+                    &crate::str_argument(direction.bind(leftAsOfColumn.py()))?,
+                ),
             },
         };
         let df = self
@@ -3195,10 +3163,17 @@ fn replace_values(
             ],
         ));
     }
+    // The names of a list or a tuple are set in the repeated string field of 
the plan as they
+    // are, as `crate::str_argument` converts them.
     let subset: Option<Vec<String>> = match subset {
         None => None,
         Some(subset) if subset.is_instance_of::<PyString>() => 
Some(vec![subset.extract()?]),
-        Some(subset) if is_sequence(subset) => Some(subset.extract()?),
+        Some(subset) if is_sequence(subset) => Some(
+            subset
+                .try_iter()?
+                .map(|name| crate::str_argument(&name?))
+                .collect::<PyResult<_>>()?,
+        ),
         Some(subset) => {
             return Err(raise(
                 "PySparkTypeError",
@@ -3600,15 +3575,16 @@ impl PyDataFrameWriter {
         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));
-                Ok(slf.clone())
-            }
-            None => Ok(slf.clone()),
+        // None -> option left unset, before the key is looked at, as 
PySpark's returns at once;
+        // bools -> "true"/"false" (reference `to_str`).
+        if value.is_none() {
+            return Ok(slf.clone());
         }
+        let key = crate::options::option_dict_key(key)?;
+        if let Some(v) = crate::coerce_option_value(value)? {
+            slf.borrow().inner.update(|w| w.option(&key, &v));
+        }
+        Ok(slf.clone())
     }
 
     // Mirrors reference `DataFrameWriter.options(**options)`: keyword args; 
None values
@@ -4027,21 +4003,21 @@ impl PyDataFrameWriterV2 {
         Ok(slf.clone())
     }
 
-    // None -> option left unset; bools -> "true"/"false" (reference 
`to_str`), same as
-    // the other reader/writer option bindings.
+    // None -> option left unset, before the key is looked at, as PySpark's 
returns at once;
+    // bools -> "true"/"false" (reference `to_str`), same as the other writer 
option bindings.
     fn option<'py>(
         slf: &Bound<'py, Self>,
         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));
-                Ok(slf.clone())
-            }
-            None => Ok(slf.clone()),
+        if value.is_none() {
+            return Ok(slf.clone());
         }
+        let key = crate::options::option_dict_key(key)?;
+        if let Some(v) = crate::coerce_option_value(value)? {
+            slf.borrow().inner.update(|w| w.option(&key, &v));
+        }
+        Ok(slf.clone())
     }
 
     // Mirrors reference `DataFrameWriterV2.options(**options)`; None skipped, 
bools lowercased.
diff --git a/crates/pyspark-rs/src/functions.rs 
b/crates/pyspark-rs/src/functions.rs
index d8186191..ad4faefe 100644
--- a/crates/pyspark-rs/src/functions.rs
+++ b/crates/pyspark-rs/src/functions.rs
@@ -220,20 +220,6 @@ pub(crate) fn value_not_between(py: Python<'_>) -> PyErr {
     )
 }
 
-/// The `ValueError` of protobuf's Python string field for a str that is not 
encodable as UTF-8,
-/// with its message, which shows at most 1024 characters of the repr of the 
value.
-pub(crate) fn not_utf8_string(obj: &Bound<'_, PyAny>) -> PyErr {
-    let message = pyo3::types::PyString::new(
-        obj.py(),
-        "%.1024r isn't a valid unicode string and can't be encoded in UTF-8.",
-    )
-    .call_method1("__mod__", ((obj,),));
-    match message {
-        Ok(message) => 
pyo3::exceptions::PyValueError::new_err(message.unbind()),
-        Err(error) => error,
-    }
-}
-
 /// An int32 literal within its range, otherwise a long, as PySpark's 
`_infer_type`.
 fn integer_literal(value: i64) -> LiteralExpression {
     if let Ok(value) = i32::try_from(value) {
@@ -267,12 +253,11 @@ pub fn to_column(obj: &Bound<'_, PyAny>) -> 
PyResult<Column> {
         ))));
     }
     if let Ok(string) = obj.cast_exact::<pyo3::types::PyString>() {
-        return match string.extract::<String>() {
-            Ok(string) => 
Ok(Column::new(Expression::literal(LiteralExpression::string(
-                string,
-            )))),
-            Err(_) => Err(not_utf8_string(obj)),
-        };
+        // A str that UTF-8 cannot encode raises the `UnicodeEncodeError` of 
its encoding, as
+        // the str of a subclass below.
+        return Ok(Column::new(Expression::literal(LiteralExpression::string(
+            string.extract::<String>()?,
+        ))));
     }
     if obj.is_exact_instance_of::<pyo3::types::PyBytes>()
         || obj.is_exact_instance_of::<pyo3::types::PyByteArray>()
@@ -349,14 +334,11 @@ pub fn to_column(obj: &Bound<'_, PyAny>) -> 
PyResult<Column> {
     }
 
     if obj.is_instance_of::<pyo3::types::PyString>() {
-        return match obj.extract::<String>() {
-            Ok(s) => 
Ok(Column::new(Expression::literal(LiteralExpression::string(
-                s,
-            )))),
-            // A str that UTF-8 cannot encode (a lone surrogate), as 
protobuf's string field
-            // rejects it when PySpark sends the literal.
-            Err(_) => Err(not_utf8_string(obj)),
-        };
+        // A str that UTF-8 cannot encode (a lone surrogate) raises the 
`UnicodeEncodeError` of
+        // its encoding, as protobuf's string field does when PySpark sends 
the literal.
+        return Ok(Column::new(Expression::literal(LiteralExpression::string(
+            obj.extract::<String>()?,
+        ))));
     }
 
     // As PySpark's literal conversion for a value of another type.
@@ -563,11 +545,8 @@ fn literal_as(
             if !obj.is_instance_of::<pyo3::types::PyString>() {
                 return Err(assertion());
             }
-            match obj.extract::<String>() {
-                Ok(s) => LiteralExpression::String(s),
-                // A str that UTF-8 cannot encode, as in `to_column`.
-                Err(_) => return Err(not_utf8_string(obj)),
-            }
+            // A str that UTF-8 cannot encode raises, as in `to_column`.
+            LiteralExpression::String(obj.extract::<String>()?)
         }
         // As PySpark's `to_plan`, which sends `bytes(value)`.
         DataType::Binary => match crate::infer::bytes_of(obj)? {
diff --git a/crates/pyspark-rs/src/options.rs b/crates/pyspark-rs/src/options.rs
index 996aa64b..1281995b 100644
--- a/crates/pyspark-rs/src/options.rs
+++ b/crates/pyspark-rs/src/options.rs
@@ -36,21 +36,47 @@ pub(crate) fn coerce_option_value(v: &Bound<'_, PyAny>) -> 
PyResult<Option<Strin
 }
 
 /// The `str()` of `v`, as the reference client sends it in a protobuf string 
field, which raises
-/// protobuf's `ValueError` for a str that UTF-8 cannot encode (a lone 
surrogate) where a lossy
-/// conversion would send another text, such as another path.
+/// the `UnicodeEncodeError` of a str that UTF-8 cannot encode (a lone 
surrogate), as
+/// [`str_argument`], where a lossy conversion would send another text, such 
as another path.
 pub(crate) fn str_text(v: &Bound<'_, PyAny>) -> PyResult<String> {
-    let text = v.str()?;
-    text.extract::<String>()
-        .map_err(|_| crate::functions::not_utf8_string(text.as_any()))
+    str_argument(v.str()?.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.
+/// The text of `v` that PySpark sets in a protobuf string field as it is, as 
protobuf's default
+/// (upb) backend converts it: a str as its UTF-8, and bytes decoded as UTF-8, 
with the error of
+/// that conversion: the `UnicodeEncodeError` of a str that UTF-8 cannot 
encode (a lone
+/// surrogate), the `UnicodeDecodeError` of bytes that are not UTF-8, and the 
`TypeError` of
+/// `PyUnicode_AsUTF8AndSize` for any other object, such as an int, a 
bytearray or None.
 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))
+    if let Ok(text) = v.cast::<PyString>() {
+        return text.extract();
+    }
+    if v.is_instance_of::<PyBytes>() {
+        // As upb's `PyUnicode_FromEncodedObject(obj, "utf-8", NULL)`.
+        return PyString::from_encoded_object(v, Some(c"utf-8"), 
None)?.extract();
+    }
+    Err(pyo3::exceptions::PyTypeError::new_err(
+        "bad argument type for built-in operation",
+    ))
+}
+
+/// The key of an option that PySpark keeps in a dict, which raises the 
`TypeError` of an
+/// unhashable key, and sends in a protobuf string field as it is, as 
[`str_argument`] converts it:
+/// the options of the writers, and of `SparkSession.builder.config`.
+pub(crate) fn option_dict_key(key: &Bound<'_, PyAny>) -> PyResult<String> {
+    key.hash()?;
+    str_argument(key)
+}
+
+/// The key of an option of `DataFrameReader.option` and 
`DataStreamReader.option`, which PySpark
+/// keeps in a dict, which raises the `TypeError` of an unhashable key, and 
whose `DataSource` plan
+/// asserts that each key is a str, a bare `AssertionError` for any other key, 
bytes too.
+pub(crate) fn reader_option_key(key: &Bound<'_, PyAny>) -> PyResult<String> {
+    key.hash()?;
+    if !key.is_instance_of::<PyString>() {
+        return Err(pyo3::exceptions::PyAssertionError::new_err(()));
+    }
+    str_argument(key)
 }
 
 /// A reader or writer that takes string options one at a time.
@@ -148,8 +174,8 @@ pub(crate) fn set_reader_kwargs_unset_none(
 
 /// The `**options` of `Catalog.createTable`, **skipping** those that are 
None. Unlike the
 /// options of the readers and writers these are not converted: PySpark sets 
them in a protobuf
-/// map of strings as they are. That map takes a str, and bytes that are 
UTF-8, which it decodes;
-/// it raises a `TypeError` for any other type, and a `ValueError` for bytes 
that are not UTF-8.
+/// map of strings as they are, which takes a str, and bytes that are UTF-8, 
which it decodes, and
+/// raises the error of [`str_argument`] for any other value.
 pub(crate) fn str_kwargs_skip_none(
     options: Option<&Bound<'_, PyDict>>,
 ) -> PyResult<HashMap<String, String>> {
@@ -158,28 +184,9 @@ pub(crate) fn str_kwargs_skip_none(
         if value.is_none() {
             continue;
         }
-        let text = if let Ok(text) = value.cast::<PyString>() {
-            text.to_cow()?.into_owned()
-        } else if let Ok(bytes) = value.cast::<PyBytes>() {
-            match std::str::from_utf8(bytes.as_bytes()) {
-                Ok(text) => text.to_string(),
-                Err(_) => {
-                    return Err(pyo3::exceptions::PyValueError::new_err(format!(
-                        "{} has type bytes, but isn't valid UTF-8 encoding. 
Non-UTF-8 strings \
-                         must be converted to unicode objects before being 
added.",
-                        value.repr()?
-                    )));
-                }
-            }
-        } else {
-            // As the protobuf map of strings that PySpark sets the options in.
-            return Err(pyo3::exceptions::PyTypeError::new_err(format!(
-                "{} has type {}, but expected one of: (<class 'bytes'>, <class 
'str'>)",
-                value.repr()?,
-                value.get_type().str()?
-            )));
-        };
-        map.insert(key.extract()?, text);
+        // The key first, as protobuf sets an entry of a map.
+        let key = str_argument(&key)?;
+        map.insert(key, str_argument(&value)?);
     }
     Ok(map)
 }
diff --git a/crates/pyspark-rs/src/readwriter.rs 
b/crates/pyspark-rs/src/readwriter.rs
index 16ac91bb..caae0a47 100644
--- a/crates/pyspark-rs/src/readwriter.rs
+++ b/crates/pyspark-rs/src/readwriter.rs
@@ -269,12 +269,22 @@ impl PyDataFrameReader {
 
     /// Set a single read option. `None` unsets the option, as PySpark's does 
(not the
     /// string "None"); booleans lowercase to "true"/"false" (reference 
`to_str` semantics).
+    /// PySpark keeps the options in a dict, which hashes every key, and its 
`DataSource` plan
+    /// checks the keys of the values that are not None only.
     fn option<'py>(
         mut slf: PyRefMut<'py, Self>,
         key: &Bound<'_, PyAny>,
         value: &Bound<'_, PyAny>,
     ) -> PyResult<PyRefMut<'py, Self>> {
-        let key = crate::str_argument(key)?;
+        if value.is_none() {
+            key.hash()?;
+            // Only a str that UTF-8 encodes is the key of an option that is 
set.
+            if let Ok(key) = key.extract::<String>() {
+                slf.inner = slf.inner.clone().unset_option(&key);
+            }
+            return Ok(slf);
+        }
+        let key = crate::options::reader_option_key(key)?;
         slf.inner = set_reader_option_unset_none(slf.inner.clone(), &key, 
value)?;
         Ok(slf)
     }
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index 16cb2018..d61990f7 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -107,8 +107,10 @@ impl PySparkSessionBuilder {
         conf: Option<&Bound<'_, PyAny>>,
     ) -> PyResult<PyRefMut<'py, Self>> {
         let py = slf.py();
+        // PySpark keeps the options in a dict, and sends each in a `KeyValue` 
of the key as it
+        // is, whose constructor leaves a key of None unset, the empty key.
         if let Some(k) = key {
-            let k = crate::str_argument(k)?;
+            let k = crate::options::option_dict_key(k)?;
             let v = match value {
                 Some(v) => crate::coerce_option_value(v)?,
                 None => None,
@@ -117,7 +119,11 @@ impl PySparkSessionBuilder {
         }
         if let Some(m) = map {
             for (k, v) in m.iter() {
-                let ks = crate::str_text(&k)?;
+                let ks = if k.is_none() {
+                    String::new()
+                } else {
+                    crate::str_argument(&k)?
+                };
                 let vs = crate::coerce_option_value(&v)?;
                 slf.set_option_value(py, &ks, vs)?;
             }
@@ -2001,7 +2007,6 @@ 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> =
@@ -2031,21 +2036,22 @@ impl PySparkSession {
                 ));
             }
         }
-        let mut query = sqlQuery.to_string();
+        // The query as it is, formatted with the keyword arguments, if any, 
and then set in the
+        // string field of the plan, as PySpark's, after it checks `args`.
+        let mut query = sqlQuery.clone();
         let mut references = Vec::new();
         if let Some(kwargs) = kwargs.filter(|kwargs| !kwargs.is_empty()) {
             let formatter = py
                 .import("pyspark.sql.connect.sql_formatter")?
                 .getattr("SQLStringFormatter")?
                 .call1((slf,))?;
-            query = formatter
-                .call_method("format", (sqlQuery,), Some(&kwargs))?
-                .extract()?;
+            query = formatter.call_method("format", (sqlQuery,), 
Some(&kwargs))?;
             for view in formatter.getattr("_temp_views")?.try_iter()? {
                 let (df, name): (PyRef<'_, PyDataFrame>, String) = 
view?.extract()?;
                 references.push((df.dataframe.clone(), name));
             }
         }
+        let query = crate::str_argument(&query)?;
         let session = slf.borrow().session.clone();
         // Within a pipeline flow function, the statement is not run here: the 
server analyzes
         // its relation in the pipeline once the flow is defined, as PySpark's 
server returns
diff --git a/crates/pyspark-rs/src/stat.rs b/crates/pyspark-rs/src/stat.rs
index 44a066eb..9a34c5dc 100644
--- a/crates/pyspark-rs/src/stat.rs
+++ b/crates/pyspark-rs/src/stat.rs
@@ -6,7 +6,6 @@ use spark_connect::group::StatFunctions;
 use crate::dataframe::{python_random_seed, PyDataFrame};
 use crate::errors::ResultExt;
 use crate::session::value_out_of_range;
-use crate::stat_arguments::bool_not_proto_int;
 
 /// Python wrapper for DataFrame statistical functions.
 #[pyclass(
@@ -194,7 +193,9 @@ pub(crate) fn sample_by_seed(py: Python<'_>, seed: 
Option<&Bound<'_, PyAny>>) ->
         return Err(pyo3::exceptions::PyAssertionError::new_err(()));
     }
     if seed.is_instance_of::<PyBool>() {
-        return Err(bool_not_proto_int(seed, 
"spark.connect.StatSampleBy.seed"));
+        return Err(crate::stat_arguments::bool_not_proto_int(
+            "spark.connect.StatSampleBy.seed",
+        ));
     }
     seed.extract::<i64>().map_err(|_| value_out_of_range(seed))
 }
diff --git a/crates/pyspark-rs/src/stat_arguments.rs 
b/crates/pyspark-rs/src/stat_arguments.rs
index 3b34c4e4..5533f55a 100644
--- a/crates/pyspark-rs/src/stat_arguments.rs
+++ b/crates/pyspark-rs/src/stat_arguments.rs
@@ -2,7 +2,7 @@
 //! ...), which check their arguments on the client as PySpark Connect's 
DataFrame does.
 
 use pyo3::prelude::*;
-use pyo3::types::{PyBool, PyDict, PyFloat, PyInt, PyList, PyString, PyTuple};
+use pyo3::types::{PyDict, PyFloat, PyInt, PyList, PyString, PyTuple};
 use spark_connect::dataframe::DataFrame;
 use spark_connect::group::StatFunctions;
 
@@ -99,23 +99,20 @@ fn dropna_thresh_and_subset(
     Ok((thresh, columns))
 }
 
-/// The `TypeError` of protobuf for a bool in the int field `field`: a bool is 
an int, but the
-/// proto refuses it.
-pub(crate) fn bool_not_proto_int(value: &Bound<'_, PyAny>, field: &str) -> 
PyErr {
+/// The `TypeError` of protobuf's default (upb) backend for a bool in the int 
field `field`, the
+/// full name of the field: a bool is an int, but protobuf refuses it since 
7.34. Earlier versions
+/// took it as 1 or 0, with a `DeprecationWarning`.
+pub(crate) fn bool_not_proto_int(field: &str) -> PyErr {
     pyo3::exceptions::PyTypeError::new_err(format!(
-        "Cannot set {field} to {value}: {value} has type {}, but expected one 
of: (int).",
-        value.get_type()
+        "Field {field}: Expected an int, got a boolean."
     ))
 }
 
 /// An int, the `thresh` of `dropna`, as the proto's int32. A bool, which is 
an int, is refused as
 /// the proto refuses it, `TypeError`, and an int out of the range of an int32 
is a `ValueError`.
 fn proto_int32(thresh: &Bound<'_, PyAny>) -> PyResult<i32> {
-    if thresh.is_instance_of::<PyBool>() {
-        return Err(bool_not_proto_int(
-            thresh,
-            "spark.connect.NADrop.min_non_nulls",
-        ));
+    if thresh.is_instance_of::<pyo3::types::PyBool>() {
+        return Err(bool_not_proto_int("spark.connect.NADrop.min_non_nulls"));
     }
     match thresh.extract::<i32>() {
         Ok(thresh) => Ok(thresh),
diff --git a/crates/pyspark-rs/src/streaming.rs 
b/crates/pyspark-rs/src/streaming.rs
index 953041dd..e6749ae5 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -325,9 +325,13 @@ impl PyDataStreamReader {
         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`).
+        // None -> option left unset, before the key is looked at, as 
PySpark's returns at once;
+        // other values as `str()`, so a bool is "True" (reference 
`DataStreamReader.option`,
+        // unlike `options` and `load`).
+        if value.is_none() {
+            return Ok(slf);
+        }
+        let key = crate::options::reader_option_key(key)?;
         match crate::options::stream_option_value(value)? {
             Some(v) => {
                 slf.inner = slf.inner.clone().option(&key, &v);
@@ -837,15 +841,17 @@ impl PyDataStreamWriter {
         key: &Bound<'_, PyAny>,
         value: &Bound<'_, PyAny>,
     ) -> PyResult<Bound<'py, Self>> {
+        // None -> option left unset, before the key is looked at, as 
PySpark's returns at once;
+        // bools -> "true"/"false" (reference `to_str`). PySpark sets the 
option in the protobuf
+        // map of its command at once, with the key as it is.
+        if value.is_none() {
+            return Ok(slf.clone());
+        }
         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));
-                Ok(slf.clone())
-            }
-            None => Ok(slf.clone()),
+        if let Some(v) = crate::coerce_option_value(value)? {
+            slf.borrow().inner.update(|w| w.option(&key, &v));
         }
+        Ok(slf.clone())
     }
 
     // Mirrors reference `DataStreamWriter.options(**options)`: keyword args; 
None values
@@ -1115,23 +1121,46 @@ fn positive_timeout(timeout: Option<&Bound<'_, PyAny>>) 
-> PyResult<Option<f64>>
     }
 }
 
-/// A bool argument that PySpark sets on a proto bool field, which takes a 
bool or an int, and
-/// raises the `TypeError` of protobuf for another value.
-pub(crate) struct ProtoBool(pub(crate) bool);
+/// A bool argument that PySpark sets in a proto bool field, taken as it is 
(None when it is
+/// omitted) and converted in the call by [`ProtoBool::value`], as PyO3 would 
prefix the
+/// `TypeError` of the conversion of an argument with its name.
+pub(crate) struct ProtoBool(Option<Py<PyAny>>);
 
 impl<'a, 'py> FromPyObject<'a, 'py> for ProtoBool {
     type Error = PyErr;
 
     fn extract(obj: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
-        if obj.is_instance_of::<pyo3::types::PyInt>() {
-            return Ok(ProtoBool(obj.is_truthy()?));
+        Ok(ProtoBool(Some(obj.to_owned().unbind())))
+    }
+}
+
+impl ProtoBool {
+    /// The bool of the argument, false when it is omitted, as protobuf's 
default (upb) backend
+    /// converts it for a bool field: a NumPy bool by its truth, a NumPy array 
is protobuf's
+    /// `TypeError`, and any other object is read as a C long, true when it is 
not 0, which raises
+    /// the `TypeError` of an object that is not an int, and the 
`OverflowError` of an int that a
+    /// C long cannot hold.
+    pub(crate) fn value(&self, py: Python<'_>) -> PyResult<bool> {
+        let Some(obj) = &self.0 else {
+            return Ok(false);
+        };
+        let obj = obj.bind(py);
+        let typ = obj.get_type();
+        let module = typ.module().ok();
+        if module.is_some_and(|module| module.to_cow().is_ok_and(|module| 
module == "numpy")) {
+            let name = typ.name()?;
+            let name = name.to_cow()?;
+            if name == "ndarray" {
+                return Err(pyo3::exceptions::PyTypeError::new_err(format!(
+                    "{} has type ndarray, but expected one of: bool",
+                    obj.str()?
+                )));
+            }
+            if name == "bool" {
+                return obj.is_truthy();
+            }
         }
-        let shown = obj.repr()?;
-        Err(pyo3::exceptions::PyTypeError::new_err(format!(
-            "Cannot set 
spark.connect.StreamingQueryCommand.ExplainCommand.extended to {shown}: \
-             {shown} has type {}, but expected one of: (<class 'bool'>, <class 
'int'>)",
-            obj.get_type().repr()?
-        )))
+        Ok(obj.extract::<std::os::raw::c_long>()? != 0)
     }
 }
 
@@ -1265,10 +1294,11 @@ impl PyStreamingQuery {
 
     /// Print the plan of the query with Python's `print`, as PySpark's
     /// `StreamingQuery.explain(extended=False)`.
-    #[pyo3(signature = (extended=ProtoBool(false)))]
+    #[pyo3(signature = (extended=ProtoBool(None)))]
     fn explain(&self, py: Python<'_>, extended: ProtoBool) -> PyResult<()> {
+        let extended = extended.value(py)?;
         let plan = interruptible(py, &self.inner.spark_session(), || {
-            self.inner.explain(extended.0).map_err(Box::new)
+            self.inner.explain(extended).map_err(Box::new)
         })?;
         py.import("builtins")?.call_method1("print", (plan,))?;
         Ok(())
diff --git a/python/tests/_mock_connect_server.py 
b/python/tests/_mock_connect_server.py
index 21309dfb..34e18b87 100644
--- a/python/tests/_mock_connect_server.py
+++ b/python/tests/_mock_connect_server.py
@@ -830,10 +830,11 @@ def serve(connection):
                 pairs = []
                 for pair in set_request.get(1, []):
                     pair = parse_message(pair)
-                    # A KeyValue of no value=2, as PySpark sends None, is 
recorded as None.
+                    # A KeyValue of no value=2, as PySpark sends None, is 
recorded as None, and
+                    # one of no key=1, the empty key of proto3, as "".
                     value = pair.get(2, [None])[0]
                     value = None if value is None else value.decode()
-                    pairs.append((pair[1][0].decode(), value))
+                    pairs.append((pair.get(1, [b""])[0].decode(), value))
                 self.set_confs.append((pairs, set_request.get(2, [None])[0]))
                 return message_field(1, request[1][0]) + self.warnings_fields()
             if 6 in operation:
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 00c83baa..c8797779 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -1017,11 +1017,15 @@ def 
test_conf_warns_the_warnings_of_the_server_and_checks_its_arguments_as_pyspa
         [("v", None)],
         [("v", "y")],
     ]
-    for value in [1.5, [1], object()]:
-        with pytest.raises(TypeError, match="Cannot set 
spark.connect.KeyValue.value"):
+    # As protobuf's default (upb) backend, a value of another type is the 
TypeError of its string
+    # field, and bytes that are not UTF-8 the UnicodeDecodeError of their 
decoding.
+    for value in [1.5, [1], object(), bytearray(b"y")]:
+        with pytest.raises(TypeError) as e:
             spark.conf.set("v", value)
-    with pytest.raises(ValueError, match="isn't valid UTF-8"):
+        assert str(e.value) == "bad argument type for built-in operation"
+    with pytest.raises(UnicodeDecodeError) as e:
         spark.conf.set("v", b"\xff")
+    assert str(e.value) == "'utf-8' codec can't decode byte 0xff in position 
0: invalid start byte"
     assert len(service.set_confs) == 6
     for args, arg_name, arg_type in [
         ((1,), "key", "int"),
@@ -4081,21 +4085,17 @@ def 
test_na_and_stat_functions_check_their_arguments_as_pyspark():
 
 def test_dropna_thresh_that_the_proto_refuses_is_refused_as_pyspark():
     # As PySpark sends `thresh` as a proto int, after it checks `how` and 
`subset`: a bool, which
-    # is an int, is a TypeError, and an int out of the range of an int32 a 
ValueError.
+    # is an int, is the TypeError of protobuf's default (upb) backend, since 
protobuf 7.34, and an
+    # int out of the range of an int32 a ValueError.
     from pyspark.errors import PySparkTypeError
     from pyspark.sql import DataFrame
 
     df = _offline_session().range(1)
+    refused = "Field spark.connect.NADrop.min_non_nulls: Expected an int, got 
a boolean."
     cases = (
-        (lambda: df.dropna(thresh=True), TypeError,
-         "Cannot set spark.connect.NADrop.min_non_nulls to True: True has type 
<class 'bool'>, "
-         "but expected one of: (int)."),
-        (lambda: df.na.drop(thresh=False), TypeError,
-         "Cannot set spark.connect.NADrop.min_non_nulls to False: False has 
type <class 'bool'>, "
-         "but expected one of: (int)."),
-        (lambda: df.dropna(thresh=True, subset=["id"]), TypeError,
-         "Cannot set spark.connect.NADrop.min_non_nulls to True: True has type 
<class 'bool'>, "
-         "but expected one of: (int)."),
+        (lambda: df.dropna(thresh=True), TypeError, refused),
+        (lambda: df.na.drop(thresh=False), TypeError, refused),
+        (lambda: df.dropna(thresh=True, subset=["id"]), TypeError, refused),
         (lambda: df.dropna(thresh=2**40), ValueError, "Value out of range: 
1099511627776"),
         (lambda: df.na.drop(thresh=-(2**31) - 1), ValueError, "Value out of 
range: -2147483649"),
         (lambda: df.dropna(how="all", thresh=2**40), ValueError,
@@ -6893,14 +6893,16 @@ def 
test_the_exception_of_a_done_call_replaces_the_error_of_a_batch_as_pyspark(m
 def 
test_strings_that_utf8_cannot_encode_raise_value_error_as_options_and_fills_as_pyspark(
     mock_connect,
 ):
-    # As PySpark, whose protobuf string fields raise ValueError for a str that 
UTF-8 cannot encode
-    # (a lone surrogate): an option is not sent as another text (another 
path), and a fill value
-    # raises the ValueError of its encoding rather than a TypeError of its 
type.
+    # As PySpark, whose protobuf string fields raise the UnicodeEncodeError, a 
ValueError, of a str
+    # that UTF-8 cannot encode (a lone surrogate), in protobuf's default (upb) 
backend: an option
+    # is not sent as another text (another path), and a fill value raises the 
error of its
+    # encoding rather than a TypeError of its type.
     from pyspark.sql import SparkSession
 
     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.")
+    message = re.escape(
+        "'utf-8' codec can't encode character '\\ud800' in position 1: 
surrogates not allowed")
     df = spark.range(1)
     for call in [
         lambda: spark.read.option("path", bad),
@@ -6915,7 +6917,7 @@ def 
test_strings_that_utf8_cannot_encode_raise_value_error_as_options_and_fills_
         lambda: SparkSession.builder.config(map={bad: "v"}),
         lambda: SparkSession.builder.config(bad, "v"),
     ]:
-        with pytest.raises(ValueError, match=message):
+        with pytest.raises(UnicodeEncodeError, match=message):
             call()
     # 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 [
@@ -6923,19 +6925,20 @@ def 
test_strings_that_utf8_cannot_encode_raise_value_error_as_options_and_fills_
         lambda: df.fillna({bad: 1}),
         lambda: df.fillna("x", subset=[bad]),
     ]:
-        with pytest.raises(ValueError, match=message):
+        with pytest.raises(UnicodeEncodeError, 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.
+    # As PySpark, whose protobuf string fields raise the UnicodeEncodeError of 
a str that UTF-8
+    # cannot encode, in protobuf's default (upb) backend, 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.
     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.")
+    message = re.escape(
+        "'utf-8' codec can't encode character '\\ud800' in position 1: 
surrogates not allowed")
     df = spark.range(1)
     for call in [
         lambda: spark.read.option(bad, "v"),
@@ -6950,13 +6953,13 @@ def 
test_strings_that_utf8_cannot_encode_raise_value_error_in_option_keys_conf_a
         lambda: spark.conf.isModifiable(bad),
         lambda: spark.table(bad),
     ]:
-        with pytest.raises(ValueError, match=message):
+        with pytest.raises(UnicodeEncodeError, match=message):
             call()
     query = "select '" + bad + "'"
-    with pytest.raises(ValueError) as error:
+    with pytest.raises(UnicodeEncodeError) 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."
+        "'utf-8' codec can't encode character '\\ud800' in position 9: 
surrogates not allowed"
     )
     assert service.execute_requests == []
 
@@ -7065,6 +7068,127 @@ def 
test_stream_writers_keep_their_settings_when_the_path_is_not_a_str_as_pyspar
     assert 11 not in start
 
 
+def 
test_protobuf_string_fields_take_bytes_and_refuse_other_objects_as_pyspark(mock_connect):
+    # As protobuf's default (upb) backend, whose string fields PySpark sets as 
they are with the
+    # keys of the runtime conf and of the options of the builder, the text of 
sql, the names of
+    # `on` of _joinAsOf and the subset of replace: bytes are decoded as UTF-8, 
bytes that are not
+    # UTF-8 raise the UnicodeDecodeError of their decoding, and another object 
the TypeError of
+    # the field. A key of None is the empty key, as the constructor of 
KeyValue leaves it unset.
+    from pyspark.errors import PySparkTypeError
+    from pyspark.sql import SparkSession
+
+    spark, service = mock_connect
+    df = spark.range(1)
+    spark.conf.set(b"spark.k", b"v")
+    spark.conf.set(None, "w")
+    spark.conf.unset(b"spark.k")
+    assert [pairs for pairs, _ in service.set_confs[-2:]] == [[("spark.k", 
"v")], [("", "w")]]
+    assert service.unset_confs[-1] == ["spark.k"]
+    builder = 
SparkSession.builder.remote("sc://localhost:1").config(b"spark.sql.b", "1")
+    assert builder.config(map={b"spark.sql.m": "2"}).getOrCreate() is spark
+    assert sorted(service.set_confs[-1][0]) == [("spark.sql.b", "1"), 
("spark.sql.m", "2")]
+    spark.sql(b"select 1")
+    # ExecutePlanRequest.plan=3, Plan.command=2, Command.sql_command=5, 
SqlCommand.input=6,
+    # Relation.sql=10, SQL.query=1.
+    command = 
parse_message(parse_message(service.execute_requests[-1])[3][0])[2][0]
+    relation = parse_message(parse_message(parse_message(command)[5][0])[6][0])
+    assert parse_message(relation[10][0])[1] == [b"select 1"]
+    # Relation.as_of_join=39 of AsOfJoin.using_columns=6, and 
Relation.replace=92 of
+    # NAReplace.cols=2.
+    df._joinAsOf(spark.range(1), "id", "id", on=["id", b"id"]).collect()
+    assert _sent_relation(service.execute_requests[-1], 39, execute=True)[6] 
== [b"id", b"id"]
+    df.replace(1, 2, subset=[b"id"]).collect()
+    assert _sent_relation(service.execute_requests[-1], 92, execute=True)[2] 
== [b"id"]
+    sent = len(service.execute_requests), len(service.set_confs), 
len(service.unset_confs)
+    for call in [
+        lambda: spark.conf.set(1, "v"),
+        lambda: spark.conf.set("spark.k", 1.5),
+        lambda: spark.conf.unset(None),
+        lambda: spark.conf.isModifiable(1),
+        lambda: SparkSession.builder.config(1, "v"),
+        lambda: SparkSession.builder.config(map={1: "v"}),
+        lambda: spark.sql(None),
+        lambda: spark.sql(1),
+        lambda: df._joinAsOf(spark.range(1), "id", "id", on=["id", 1]),
+        lambda: df._joinAsOf(spark.range(1), "id", "id", on=["id", None]),
+        lambda: df.replace(1, 2, subset=["id", 1]),
+        lambda: df.replace(1, 2, subset=("id", bytearray(b"id"))),
+    ]:
+        with pytest.raises(TypeError) as error:
+            call()
+        assert type(error.value) is TypeError
+        assert str(error.value) == "bad argument type for built-in operation"
+    with pytest.raises(UnicodeDecodeError) as error:
+        spark.sql(b"select \xff")
+    assert str(error.value) == (
+        "'utf-8' codec can't decode byte 0xff in position 7: invalid start 
byte")
+    # The query is formatted as it is, and `args` are checked before it is set 
in the plan.
+    with pytest.raises(TypeError, match="^expected str, got bytes$"):
+        spark.sql(b"select {x}", x=1)
+    with pytest.raises(PySparkTypeError) as error:
+        spark.sql(1, args=1)
+    assert error.value.getCondition() == "INVALID_TYPE"
+    # An as-of column that is not a Column is a name, which PySpark's 
ColumnReference asserts is
+    # a str, before `on` is looked at.
+    for column in (1, b"id", None):
+        for left, right in ((column, "id"), ("id", column)):
+            with pytest.raises(AssertionError) as error:
+                df._joinAsOf(spark.range(1), left, right, on=5)
+            assert type(error.value) is AssertionError and str(error.value) == 
""
+    assert (len(service.execute_requests), len(service.set_confs),
+            len(service.unset_confs)) == sent
+
+
+def 
test_option_keys_are_checked_as_the_dicts_and_the_plans_of_pyspark(mock_connect):
+    # As PySpark: the option of a writer of a value of None returns before it 
looks at the key,
+    # as DataStreamReader.option does, while DataFrameReader.option keeps the 
None in its dict,
+    # which hashes the key. The writers keep their other options in a dict 
too, which raises the
+    # TypeError of an unhashable key, and set the key in a protobuf map of 
strings as it is, as
+    # the writer of a stream does at once: bytes are decoded, and another 
object is the
+    # TypeError of the field. The DataSource plan of the readers asserts that 
a key is a str.
+    spark, service = mock_connect
+    df = spark.range(1)
+    stream = spark.readStream.format("rate").load().writeStream
+    for writer in (df.write, df.writeTo("t"), stream, spark.readStream):
+        assert writer.option([1], None) is writer
+    with pytest.raises(TypeError, match="^unhashable type: 'list'$"):
+        spark.read.option([1], None)
+    reader = spark.read.option("k", "v")
+    assert reader.option(1, None) is reader and reader.option(b"k", None) is 
reader
+    assert reader._options == {"k": "v"}
+    assert stream.option(b"k", "v") is stream
+    for call in [
+        lambda: df.write.option(bytearray(b"k"), "v"),
+        lambda: df.writeTo("t").option([1], "v"),
+        lambda: spark.read.option({}, "v"),
+        lambda: spark.readStream.option(bytearray(b"k"), "v"),
+    ]:
+        with pytest.raises(TypeError, match="^unhashable type: "):
+            call()
+    for call in [
+        lambda: df.write.option(1, "v"),
+        lambda: df.writeTo("t").option(None, "v"),
+        lambda: stream.option(bytearray(b"k"), "v"),
+        lambda: stream.option(1, "v"),
+    ]:
+        with pytest.raises(TypeError, match="^bad argument type for built-in 
operation$"):
+            call()
+    for call in [
+        lambda: spark.read.option(1, "v"),
+        lambda: spark.read.option(b"k", "v"),
+        lambda: spark.readStream.option(b"k", "v"),
+        lambda: spark.readStream.option(None, "v"),
+    ]:
+        with pytest.raises(AssertionError) as error:
+            call()
+        assert type(error.value) is AssertionError and str(error.value) == ""
+    # A bytes key of a writer is sent decoded: Command.write_operation=2, 
WriteOperation.options=9.
+    df.write.format("noop").option(b"k", "v").save()
+    plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+    write = parse_message(parse_message(plan[2][0])[2][0])
+    assert [parse_message(entry) for entry in write[9]] == [{1: [b"k"], 2: 
[b"v"]}]
+
+
 def test_functions_levenshtein():
     """Test levenshtein distance function."""
     from pyspark.sql import functions as F
@@ -9380,24 +9504,24 @@ def 
test_lit_takes_an_int_or_a_float_by_its_type_as_pyspark(mock_connect):
         assert repr(F.lit(value)) == f"Column<'{text}'>"
 
 
-def 
test_a_str_that_utf8_cannot_encode_is_the_value_error_of_protobuf_as_pyspark(mock_connect):
-    # As PySpark's, whose protobuf string field rejects a str with a lone 
surrogate: a ValueError
-    # of protobuf's message, of at most 1024 characters of the repr of the 
value, for a literal
-    # and the arguments of sql.
+def 
test_a_str_that_utf8_cannot_encode_is_the_encode_error_of_protobuf_as_pyspark(mock_connect):
+    # As PySpark's, whose protobuf string field rejects a str with a lone 
surrogate, in protobuf's
+    # default (upb) backend: the UnicodeEncodeError of its encoding, of the 
position of the
+    # surrogate, for a literal and the arguments of sql.
     from pyspark.sql import functions as F
 
     spark, service = mock_connect
     value, long_value = "a\ud800b", "x" * 2000 + "\ud800"
-    message = "%.1024r isn't a valid unicode string and can't be encoded in 
UTF-8."
-    for build, text in ((lambda: F.lit(value), message % value),
-                        (lambda: F.col("id") == value, message % value),
-                        (lambda: F.lit([value]), message % value),
-                        (lambda: F.lit(long_value), message % long_value),
-                        (lambda: spark.sql("SELECT :x", args={"x": value}), 
message % value),
-                        (lambda: spark.sql("SELECT ?", args=[value]), message 
% value)):
-        with pytest.raises(ValueError) as error:
+    message = "'utf-8' codec can't encode character '\\ud800' in position %d: 
surrogates not allowed"
+    for build, text in ((lambda: F.lit(value), message % 1),
+                        (lambda: F.col("id") == value, message % 1),
+                        (lambda: F.lit([value]), message % 1),
+                        (lambda: F.lit(long_value), message % 2000),
+                        (lambda: spark.sql("SELECT :x", args={"x": value}), 
message % 1),
+                        (lambda: spark.sql("SELECT ?", args=[value]), message 
% 1)):
+        with pytest.raises(UnicodeEncodeError) as error:
             build()
-        assert type(error.value) is ValueError and str(error.value) == text
+        assert type(error.value) is UnicodeEncodeError and str(error.value) == 
text
     assert service.execute_requests == []
 
 
@@ -11069,7 +11193,8 @@ def 
test_seeds_that_pyspark_cannot_send_are_refused_as_pyspark(mock_connect):
     # As PySpark Connect's: randomSplit and sample take int() of the seed, and 
an int out of the
     # range of a long is the ValueError of protobuf. sampleBy's StatSampleBy 
asserts an int, so
     # a float, a str or an np.int64 is a bare AssertionError, and a bool 
passes the assertion but
-    # is refused by the proto. Its checks of col and fractions come first.
+    # is refused by the proto, the TypeError of protobuf's default (upb) 
backend since protobuf
+    # 7.34. Its checks of col and fractions come first.
     from pyspark.errors import PySparkTypeError
 
     spark, service = mock_connect
@@ -11116,9 +11241,7 @@ def 
test_seeds_that_pyspark_cannot_send_are_refused_as_pyspark(mock_connect):
             with pytest.raises(TypeError) as error:
                 call(seed)
             assert str(error.value) == (
-                f"Cannot set spark.connect.StatSampleBy.seed to {seed}: {seed} 
has type "
-                "<class 'bool'>, but expected one of: (int)."
-            )
+                "Field spark.connect.StatSampleBy.seed: Expected an int, got a 
boolean.")
         for seed, shown in out_of_range[1:3]:
             with pytest.raises(ValueError) as error:
                 call(seed)
@@ -21317,7 +21440,7 @@ def 
test_streaming_queries_check_their_timeouts_as_pyspark(mock_connect):
     # As PySpark's: StreamingQueryException of pyspark.sql.streaming is that of
     # pyspark.errors; the waits of a query and of spark.streams raise 
VALUE_NOT_POSITIVE of a
     # timeout that is not a positive number, of the name of its type; and 
explain takes an
-    # int as a bool, but no other value.
+    # int, or a NumPy bool, as a bool, but no other value.
     import pyspark.errors
     import pyspark.sql.streaming
     import pyspark.sql.streaming.query
@@ -21342,9 +21465,31 @@ def 
test_streaming_queries_check_their_timeouts_as_pyspark(mock_connect):
                 "arg_name": "timeout",
                 "arg_value": type(timeout).__name__,
             }
-    for extended in (1.5, "x", None):
-        with pytest.raises(TypeError, match="but expected one of"):
+    # As protobuf's default (upb) backend, which reads the `extended` that 
PySpark sets in its
+    # ExplainCommand as a C long, true when it is not 0, and a NumPy bool by 
its truth: another
+    # object raises the error of that conversion, and a NumPy array protobuf's 
TypeError.
+    for extended, error, message in (
+        (1.5, TypeError, "'float' object cannot be interpreted as an integer"),
+        ("x", TypeError, "'str' object cannot be interpreted as an integer"),
+        (None, TypeError, "'NoneType' object cannot be interpreted as an 
integer"),
+        (b"x", TypeError, "'bytes' object cannot be interpreted as an 
integer"),
+        (np.float64(1), TypeError, "'numpy.float64' object cannot be 
interpreted as an integer"),
+        (2**70, OverflowError, "Python int too large to convert to C long"),
+        (np.array([1]), TypeError, "[1] has type ndarray, but expected one of: 
bool"),
+    ):
+        with pytest.raises(error) as e:
             query.explain(extended)
+        assert type(e.value) is error and str(e.value) == message
+    # ExecutePlanResponse.streaming_query_command_result=9: query_id=1, 
explain=4 (result=1).
+    service.execute_payload = message_field(9, message_field(
+        1, message_field(1, "q") + message_field(2, "r")) + message_field(4, 
message_field(1, "p")))
+    for extended, sent in ((np.True_, 1), (np.int64(0), 0), (2, 1), (-1, 1), 
(False, 0)):
+        query.explain(extended)
+        # ExecutePlanRequest.plan=3, Plan.command=2, 
Command.streaming_query_command=7,
+        # StreamingQueryCommand.explain=7, ExplainCommand.extended=1.
+        command = 
parse_message(parse_message(service.execute_requests[-1])[3][0])[2][0]
+        query_command = parse_message(parse_message(command)[7][0])
+        assert parse_message(query_command[7][0]).get(1, [0]) == [sent]
 
 
 def test_stream_writer_setters_mutate_and_return_self(offline_spark):
@@ -21940,7 +22085,7 @@ def 
test_catalog_creates_tables_eagerly_as_pyspark(mock_connect):
     assert (create[1], create[2], create[3], create[4]) == ([b"t"], [b"/p"], 
[b"parquet"], [b"d"])
     assert _struct_field_names(create[5][0]) == ["a", "b"]
     assert [parse_message(entry) for entry in create[6]] == [{1: [b"k"], 2: 
[b"v"]}]
-    with pytest.raises(TypeError, match="1 has type <class 'int'>"):
+    with pytest.raises(TypeError, match="^bad argument type for built-in 
operation$"):
         spark.catalog.createTable("t", source="parquet", k=1)
     for schema in ("a INT", T.LongType()):
         with pytest.raises(PySparkTypeError) as error:
@@ -21966,8 +22111,9 @@ def 
test_catalog_creates_tables_eagerly_as_pyspark(mock_connect):
 
 def 
test_catalog_create_table_takes_bytes_options_as_protobuf_does(mock_connect):
     spark, service = mock_connect
-    # As PySpark's protobuf map of strings, bytes that are UTF-8 are sent 
decoded, while bytes
-    # that are not UTF-8 raise a ValueError, and a bytearray or a memoryview a 
TypeError.
+    # As PySpark's protobuf map of strings, in protobuf's default (upb) 
backend: bytes that are
+    # UTF-8 are sent decoded, while bytes that are not UTF-8 raise the 
UnicodeDecodeError of their
+    # decoding, and a bytearray or a memoryview the TypeError of the string 
field.
     spark.catalog.createTable("t", source="parquet", a=b"x", b=None)
     create = _sent_catalog(service.execute_requests[-1], 14)
     assert [parse_message(entry) for entry in create[6]] == [{1: [b"a"], 2: 
[b"x"]}]
@@ -21975,10 +22121,12 @@ def 
test_catalog_create_table_takes_bytes_options_as_protobuf_does(mock_connect)
     create = _sent_catalog(service.execute_requests[-1], 14)
     assert [parse_message(entry) for entry in create[6]] == [{1: [b"a"], 2: 
[b"\xc3\xa9"]}]
     calls = len(service.execute_requests)
-    with pytest.raises(ValueError, match="has type bytes, but isn't valid 
UTF-8 encoding"):
+    with pytest.raises(UnicodeDecodeError) as error:
         spark.catalog.createTable("t", source="parquet", a=b"\xff\xfe")
+    assert str(error.value) == (
+        "'utf-8' codec can't decode byte 0xff in position 0: invalid start 
byte")
     for value in (bytearray(b"x"), memoryview(b"x")):
-        with pytest.raises(TypeError, match=r"has type <class 
'(bytearray|memoryview)'>"):
+        with pytest.raises(TypeError, match="^bad argument type for built-in 
operation$"):
             spark.catalog.createTable("t", source="parquet", a=value)
     assert len(service.execute_requests) == calls
 


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

Reply via email to