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 7bf255ef [SPARK-61609][CONNECT][PYTHON] Raise PySpark's errors for a 
keyword option key that is not a str, the jdbc predicates and an out-of-range 
show count, in the Python client
7bf255ef is described below

commit 7bf255efa77a0fe293b05b6a33d1e89c7f368a6e
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 12:22:28 2026 +0900

    [SPARK-61609][CONNECT][PYTHON] Raise PySpark's errors for a keyword option 
key that is not a str, the jdbc predicates and an out-of-range show count, in 
the Python client
    
    ### What changes were proposed in this pull request?
    
    A follow-up of the post-merge review of #571 and #568, in the Python client:
    
    - The `**options` and `**kwargs` methods raise PySpark's `TypeError: 
keywords must be strings` for a key that is not a str. They raise it before 
anything is done or set, and send nothing:
      - readers, stream readers, writers, stream writers and writer V2: 
`options`, `load`, `parquet`, `save`, `saveAsTable`, `start`, `toTable`, 
`_set_opts`;
      - `catalog.createTable` and `createExternalTable`;
      - `show` and `_show_string`, `sort`, `orderBy`, `sortWithinPartitions`, 
`_to_pandas`;
      - `Column.alias` and `name`.
    
      PySpark's methods are Python functions, so CPython refuses such a key 
before the call runs. The check is shared with #568's jdbc properties.
    - `DataFrameReader.jdbc` asserts that `predicates` is a list of str, after 
the reader has its url and dbtable, as PySpark's `DataSource` plan does. A 
tuple, a str or an item that is not a str raises a bare `AssertionError`.
    - `show`'s `n` and `truncate` are converted as protobuf's int32 fields 
(`ShowString.num_rows` and `truncate`), as #571 did for `limit`, `offset` and 
the others.
    
    ### Why are the changes needed?
    
    For parity with PySpark 4.3.0 (under protobuf's default upb backend). Each 
pair below is ours before this change, then PySpark:
    
    - `spark.read.format("json").options(**{b"multiLine": True}).load(p)`: the 
option was set as the name `b'multiLine'` and silently ignored, so a multi-line 
JSON file read as corrupt records / `TypeError: keywords must be strings`.
    - `df.show(**{1: "1"})`: `TypeError: 'int' object is not an instance of 
'str'` / `TypeError: keywords must be strings`.
    - `F.col("id").alias("x", **{1: "1"})`: `AssertionError: Unexpected kwargs 
where passed` / `TypeError: keywords must be strings`.
    - `df.sort("id", **{1: True})`: accepted / `TypeError`.
    - `spark.read.jdbc(url, "t", predicates=("a=1",))`: accepted / 
`AssertionError`.
    - `predicates=[1]`: `TypeError` / `AssertionError`.
    - `df._show_string(2**31)`: `OverflowError` / `ValueError: Value out of 
range: 2147483648`.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. A non-str option key raises PySpark's `TypeError` instead of being set 
or ignored. The jdbc predicates and an out-of-range `show` count raise 
PySpark's errors.
    
    ### How was this patch tested?
    
    - New offline tests in `python/tests/test_dropin_offline.py`, each checked 
to fail without the change and to send nothing for a refused call:
      - `test_option_keys_that_are_not_str_are_keywords_as_pyspark`: int and 
bytes keys at 22 call sites;
      - `test_jdbc_predicates_are_checked_as_pyspark`;
      - `test_show_counts_are_proto_int32_as_pyspark`.
    - A probe of 24 entry points matches the reference under upb.
    - With `TZ=UTC`: CI's offline set, 3282 passed; `test_dropin_e2e.py`, 276 
passed; `test_arrow_e2e.py`, 11 passed.
    - The Rust lib tests, the `--no-run` builds with and without `wasm-udf`, 
`cargo fmt`, the stub audit and ruff pass.
    
    ### 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 #604 from HyukjinKwon/SPARK-61609-kwargs-keys.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/catalog.rs    |  2 +
 crates/pyspark-rs/src/column.rs     |  1 +
 crates/pyspark-rs/src/dataframe.rs  | 14 +++++--
 crates/pyspark-rs/src/options.rs    | 22 ++++++++++
 crates/pyspark-rs/src/readwriter.rs | 36 +++++++++++-----
 crates/pyspark-rs/src/streaming.rs  |  2 +
 python/tests/test_dropin_offline.py | 84 +++++++++++++++++++++++++++++++++++++
 7 files changed, 147 insertions(+), 14 deletions(-)

diff --git a/crates/pyspark-rs/src/catalog.rs b/crates/pyspark-rs/src/catalog.rs
index f4c629e9..9d05718e 100644
--- a/crates/pyspark-rs/src/catalog.rs
+++ b/crates/pyspark-rs/src/catalog.rs
@@ -410,6 +410,7 @@ impl PyCatalog {
         description: Option<&str>,
         options: Option<&Bound<'_, pyo3::types::PyDict>>,
     ) -> PyResult<PyDataFrame> {
+        crate::options::check_keyword_keys(options)?;
         let schema = table_schema(schema)?;
         let options = crate::options::str_kwargs_skip_none(options)?;
         interruptible(py, self.catalog.spark_session(), || {
@@ -441,6 +442,7 @@ impl PyCatalog {
         description: Option<&str>,
         options: Option<&Bound<'_, pyo3::types::PyDict>>,
     ) -> PyResult<PyDataFrame> {
+        crate::options::check_keyword_keys(options)?;
         py.import("warnings")?.call_method1(
             "warn",
             (
diff --git a/crates/pyspark-rs/src/column.rs b/crates/pyspark-rs/src/column.rs
index ff9fc3b1..1d387fe1 100644
--- a/crates/pyspark-rs/src/column.rs
+++ b/crates/pyspark-rs/src/column.rs
@@ -162,6 +162,7 @@ impl PyColumn {
         alias: Vec<String>,
         kwargs: Option<&Bound<'_, PyDict>>,
     ) -> PyResult<PyColumn> {
+        crate::options::check_keyword_keys(kwargs)?;
         let _origin = crate::origin::with_origin("alias")?;
         let mut metadata = None;
         if let Some(kwargs) = kwargs {
diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index 2022abf9..395a0334 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -157,6 +157,7 @@ impl PyDataFrame {
         args: &Bound<'_, PyTuple>,
         kwargs: Option<&Bound<'_, PyDict>>,
     ) -> PyResult<String> {
+        crate::options::check_keyword_keys(kwargs)?;
         let [n, truncate, vertical] = bind_arguments(
             function,
             args,
@@ -176,18 +177,22 @@ impl PyDataFrame {
         }
         let truncate =
             if truncate.is_instance_of::<pyo3::types::PyBool>() && 
truncate.is_truthy()? {
-                20
+                20i32.into_pyobject(py)?.into_any()
             } else {
                 // As `int(truncate)`, whose ValueError is PySpark's 
NOT_EXPECTED_TYPE.
                 match 
py.import("builtins")?.getattr("int")?.call1((&truncate,)) {
-                    Ok(value) => value.extract::<i32>()?,
+                    Ok(value) => value,
                     Err(err) if 
err.is_instance_of::<pyo3::exceptions::PyValueError>(py) => {
                         return Err(not_expected_type(&truncate, "truncate", 
"bool"));
                     }
                     Err(err) => return Err(err),
                 }
             };
-        let (n, vertical) = (n.extract::<i32>()?, vertical.extract::<bool>()?);
+        // The proto's int32 fields, as PySpark's `ShowString` sets them: 
`num_rows`, then
+        // `truncate`.
+        let n = proto_int::<i32>(&n, "spark.connect.ShowString.num_rows")?;
+        let truncate = proto_int::<i32>(&truncate, 
"spark.connect.ShowString.truncate")?;
+        let vertical = vertical.extract::<bool>()?;
         interruptible(py, &self.dataframe.spark_session(), || {
             self.dataframe
                 .show_string(n, truncate, vertical)
@@ -293,6 +298,7 @@ impl PyDataFrame {
         kwargs: Option<&Bound<'_, PyDict>>,
     ) -> PyResult<Vec<spark_connect::expression::Expression>> {
         use pyo3::types::{PyBool, PyString};
+        crate::options::check_keyword_keys(kwargs)?;
         if cols.is_empty() {
             return Err(crate::column::raise_pyspark(
                 py,
@@ -2454,6 +2460,7 @@ impl PyDataFrame {
         py: Python<'_>,
         kwargs: Option<&Bound<'_, pyo3::types::PyDict>>,
     ) -> PyResult<Py<PyAny>> {
+        crate::options::check_keyword_keys(kwargs)?;
         let mode = match kwargs {
             Some(kwargs) => kwargs.get_item("pandasStructHandlingMode")?,
             None => None,
@@ -3603,6 +3610,7 @@ fn apply_write_common(
     partitionBy: Option<&Bound<'_, PyAny>>,
     options: Option<&Bound<'_, PyDict>>,
 ) -> PyResult<spark_connect::readwriter::DataFrameWriter> {
+    crate::options::check_keyword_keys(options)?;
     if let Some(f) = format {
         w = w.format(f);
     }
diff --git a/crates/pyspark-rs/src/options.rs b/crates/pyspark-rs/src/options.rs
index 1281995b..319648c7 100644
--- a/crates/pyspark-rs/src/options.rs
+++ b/crates/pyspark-rs/src/options.rs
@@ -60,6 +60,24 @@ pub(crate) fn str_argument(v: &Bound<'_, PyAny>) -> 
PyResult<String> {
     ))
 }
 
+/// The keys of the `**options` of a call, which PySpark's Python function 
takes: a key that is not
+/// a str raises the `TypeError` of CPython's unpacking, `keywords must be 
strings`, before the call
+/// does anything. Every method that takes `**options` checks its keys first, 
with this.
+pub(crate) fn check_keyword_keys(options: Option<&Bound<'_, PyDict>>) -> 
PyResult<()> {
+    if let Some(options) = options {
+        if options
+            .keys()
+            .iter()
+            .any(|key| !key.is_instance_of::<PyString>())
+        {
+            return Err(pyo3::exceptions::PyTypeError::new_err(
+                "keywords must be strings",
+            ));
+        }
+    }
+    Ok(())
+}
+
 /// 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`.
@@ -133,6 +151,7 @@ pub(crate) fn set_options_skip_none<B: OptionBuilder>(
 pub(crate) fn kwargs_skip_none(
     options: Option<&Bound<'_, PyDict>>,
 ) -> PyResult<HashMap<String, String>> {
+    check_keyword_keys(options)?;
     let mut map = HashMap::new();
     if let Some(options) = options {
         for (key, value) in options.iter() {
@@ -163,6 +182,7 @@ pub(crate) fn set_reader_kwargs_unset_none(
     mut reader: DataFrameReader,
     options: Option<&Bound<'_, PyDict>>,
 ) -> PyResult<DataFrameReader> {
+    check_keyword_keys(options)?;
     if let Some(options) = options {
         for (key, value) in options.iter() {
             let key = str_text(&key)?;
@@ -179,6 +199,7 @@ pub(crate) fn set_reader_kwargs_unset_none(
 pub(crate) fn str_kwargs_skip_none(
     options: Option<&Bound<'_, PyDict>>,
 ) -> PyResult<HashMap<String, String>> {
+    check_keyword_keys(options)?;
     let mut map = HashMap::new();
     for (key, value) in options.into_iter().flat_map(|options| options.iter()) 
{
         if value.is_none() {
@@ -199,6 +220,7 @@ pub(crate) fn set_opts(
     schema: Option<&Bound<'_, PyAny>>,
     options: Option<&Bound<'_, PyDict>>,
 ) -> PyResult<()> {
+    check_keyword_keys(options)?;
     if let Some(schema) = schema.filter(|schema| !schema.is_none()) {
         slf.call_method1("schema", (schema,))?;
     }
diff --git a/crates/pyspark-rs/src/readwriter.rs 
b/crates/pyspark-rs/src/readwriter.rs
index a6727b18..39f89dda 100644
--- a/crates/pyspark-rs/src/readwriter.rs
+++ b/crates/pyspark-rs/src/readwriter.rs
@@ -9,7 +9,7 @@ use spark_connect::readwriter::DataFrameReader;
 use crate::dataframe::PyDataFrame;
 use crate::errors::{not_expected_type, ResultExt};
 use crate::options::{
-    set_option_skip_none, set_options_skip_none, set_reader_kwargs_unset_none,
+    check_keyword_keys, set_option_skip_none, set_options_skip_none, 
set_reader_kwargs_unset_none,
     set_reader_option_unset_none, DefaultedOption,
 };
 
@@ -109,6 +109,24 @@ fn path_list(paths: &[Bound<'_, PyAny>]) -> 
PyResult<Vec<String>> {
         .collect()
 }
 
+/// The `predicates` of `jdbc`, which PySpark's `DataSource` plan asserts to 
be a list, and each of
+/// its items a str: a bare `AssertionError` for a tuple, a str, or an item 
that is not a str.
+fn jdbc_predicates(predicates: &Bound<'_, PyAny>) -> PyResult<Vec<String>> {
+    let Ok(predicates) = predicates.cast::<pyo3::types::PyList>() else {
+        return Err(pyo3::exceptions::PyAssertionError::new_err(()));
+    };
+    predicates
+        .iter()
+        .map(|predicate| {
+            if predicate.is_instance_of::<pyo3::types::PyString>() {
+                crate::str_argument(&predicate)
+            } else {
+                Err(pyo3::exceptions::PyAssertionError::new_err(()))
+            }
+        })
+        .collect()
+}
+
 /// The path of a writer, as PySpark sets it in its protobuf string field, 
which the default
 /// (upb) backend converts as [`crate::str_argument`] does: a str, or bytes 
decoded as UTF-8, and
 /// the error of that conversion for another object.
@@ -483,6 +501,7 @@ impl PyDataFrameReader {
         paths: Vec<Bound<'_, PyAny>>,
         options: Option<&Bound<'_, PyDict>>,
     ) -> PyResult<PyDataFrame> {
+        check_keyword_keys(options)?;
         let mut r = self.inner.clone();
         for name in [
             "mergeSchema",
@@ -731,7 +750,7 @@ impl PyDataFrameReader {
         lowerBound: Option<&Bound<'_, PyAny>>,
         upperBound: Option<&Bound<'_, PyAny>>,
         numPartitions: Option<&Bound<'_, PyAny>>,
-        predicates: Option<Vec<String>>,
+        predicates: Option<&Bound<'_, PyAny>>,
         properties: Option<&Bound<'_, PyDict>>,
     ) -> PyResult<PyDataFrame> {
         self.inner = self.inner.clone().format("jdbc");
@@ -766,22 +785,17 @@ impl PyDataFrameReader {
             // As PySpark's `options(**properties)`, whose unpacking raises 
for a key that is not
             // a str before any property is set, with the format and the 
options of a column kept
             // on the reader.
-            if properties
-                .keys()
-                .iter()
-                .any(|key| !key.is_instance_of::<pyo3::types::PyString>())
-            {
+            if let Err(err) = check_keyword_keys(Some(properties)) {
                 self.inner = r;
-                return Err(pyo3::exceptions::PyTypeError::new_err(
-                    "keywords must be strings",
-                ));
+                return Err(err);
             }
             for (key, value) in properties.iter() {
                 r = set_option_skip_none(r, &crate::str_argument(&key)?, 
Some(&value))?;
             }
         }
-        // PySpark's jdbc also leaves url/dbtable on the reader.
+        // PySpark's jdbc also leaves url/dbtable on the reader, before it 
asserts the predicates.
         self.inner = r.clone().option("url", url).option("dbtable", table);
+        let predicates = predicates.map(jdbc_predicates).transpose()?;
         Ok(PyDataFrame::new(r.jdbc(url, table, predicates)))
     }
 }
diff --git a/crates/pyspark-rs/src/streaming.rs 
b/crates/pyspark-rs/src/streaming.rs
index 5bbf5774..c6bce701 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -379,6 +379,7 @@ impl PyDataStreamReader {
         schema: Option<&Bound<'_, PyAny>>,
         options: Option<&Bound<'_, PyDict>>,
     ) -> PyResult<PyDataFrame> {
+        crate::options::check_keyword_keys(options)?;
         let mut r = self.inner.clone();
         if let Some(fmt) = format {
             r = r.format(fmt);
@@ -799,6 +800,7 @@ impl PyDataStreamWriter {
         query_name: Option<&Bound<'_, PyAny>>,
         options: Option<&Bound<'_, PyDict>>,
     ) -> PyResult<DataStreamWriter> {
+        crate::options::check_keyword_keys(options)?;
         let mut w = self.inner.get();
         if let Some(fmt) = format {
             w = w.format(fmt);
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index a1f0a533..dbe95992 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -23295,6 +23295,90 @@ def 
test_jdbc_properties_are_keywords_as_pyspark(mock_connect):
     assert (len(service.execute_requests), len(service.analyze_requests)) == 
sent
 
 
+def test_option_keys_that_are_not_str_are_keywords_as_pyspark(mock_connect):
+    # As PySpark's `**options` methods, which are Python functions: CPython 
unpacks a key that is
+    # not a str as the TypeError `keywords must be strings`, before the method 
does anything, so
+    # no option is set (bytes and int keys used to be set as their str()), and 
nothing is sent.
+    import warnings
+
+    from pyspark.sql import functions as F
+
+    spark, service = mock_connect
+    df = spark.range(1)
+    sent = len(service.execute_requests), len(service.analyze_requests)
+    for key in (1, b"multiLine"):
+        kwargs = {key: True}
+        reader = spark.read.format("json")
+        with pytest.raises(TypeError, match="^keywords must be strings$"):
+            reader.options(**kwargs)
+        assert reader._format == "json" and reader._options == {}
+        calls = [
+            lambda: spark.read.load("p", **kwargs),
+            lambda: spark.read.parquet("p", **kwargs),
+            lambda: spark.read._set_opts(**kwargs),
+            lambda: spark.readStream.options(**kwargs),
+            lambda: spark.readStream.load("p", **kwargs),
+            lambda: spark.range(1).write.options(**kwargs),
+            lambda: spark.range(1).write.save("p", **kwargs),
+            lambda: spark.range(1).write.saveAsTable("t", **kwargs),
+            lambda: spark.range(1).writeTo("t").options(**kwargs),
+            lambda: spark.range(1).writeStream.options(**kwargs),
+            lambda: spark.range(1).writeStream.start("p", **kwargs),
+            lambda: spark.range(1).writeStream.toTable("t", **kwargs),
+            lambda: df.show(**kwargs),
+            lambda: df._show_string(**kwargs),
+            lambda: df.sort("id", **kwargs),
+            lambda: df.orderBy("id", **kwargs),
+            lambda: df.sortWithinPartitions("id", **kwargs),
+            lambda: df._to_pandas(**kwargs),
+            lambda: df.select(F.col("id").alias("x", **kwargs)),
+            lambda: df.select(F.col("id").name("x", **kwargs)),
+            lambda: spark.catalog.createTable("t", "p", "json", **kwargs),
+            lambda: spark.catalog.createExternalTable("t", "p", "json", 
**kwargs),
+        ]
+        for call in calls:
+            with pytest.raises(TypeError, match="^keywords must be strings$"):
+                call()
+        with warnings.catch_warnings(record=True) as caught:
+            warnings.simplefilter("always")
+            with pytest.raises(TypeError, match="^keywords must be strings$"):
+                spark.catalog.createExternalTable("t", "p", "json", **kwargs)
+        assert not caught
+    assert (len(service.execute_requests), len(service.analyze_requests)) == 
sent
+
+
+def test_jdbc_predicates_are_checked_as_pyspark(mock_connect):
+    # As PySpark's jdbc, whose DataSource plan asserts that the predicates are 
a list of str,
+    # after the reader has its format, url and dbtable: a bare AssertionError 
for any other value.
+    # The predicates are not checked when a column is given, which reads its 
partitions instead.
+    spark, service = mock_connect
+    sent = len(service.execute_requests), len(service.analyze_requests)
+    for predicates in (("a=1",), "a=1", [1], [None], [b"a=1"], ["a=1", 2], ()):
+        reader = spark.read
+        with pytest.raises(AssertionError) as error:
+            reader.jdbc("jdbc:x", "t", predicates=predicates)
+        assert str(error.value) == ""
+        assert reader._format == "jdbc" and reader._options == {"url": 
"jdbc:x", "dbtable": "t"}
+    assert (len(service.execute_requests), len(service.analyze_requests)) == 
sent
+    spark.read.jdbc("jdbc:x", "t", column="c", lowerBound=1, upperBound=2, 
numPartitions=2,
+                    predicates="a=1").columns
+
+
+def test_show_counts_are_proto_int32_as_pyspark(mock_connect):
+    # As PySpark's ShowString, whose num_rows and truncate are proto int32 
fields that protobuf
+    # converts: an int out of their range raises the ValueError of the value, 
not an OverflowError.
+    spark, service = mock_connect
+    df = spark.range(1)
+    sent = len(service.execute_requests), len(service.analyze_requests)
+    for value in (2**31, -(2**31) - 1, 2**70):
+        for kwargs in ({"n": value}, {"truncate": value}):
+            with pytest.raises(ValueError, match=f"^Value out of range: 
{value}$"):
+                df._show_string(**kwargs)
+        with pytest.raises(ValueError, match=f"^Value out of range: {value}$"):
+            df.show(n=value)
+    assert (len(service.execute_requests), len(service.analyze_requests)) == 
sent
+
+
 def test_reader_paths_are_checked_as_pyspark(offline_spark):
     from pyspark.errors import PySparkTypeError
 


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

Reply via email to