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 0df54550 [SPARK-61057][CONNECT][PYTHON][FOLLOWUP] Keep the format of 
the stream reader when a format reader gets a path that is not a str, as 
PySpark does
0df54550 is described below

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

    [SPARK-61057][CONNECT][PYTHON][FOLLOWUP] Keep the format of the stream 
reader when a format reader gets a path that is not a str, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    A follow-up of #266 (SPARK-61057), from a review of #544 (SPARK-61497), 
which rewrote `text()`.
    
    The format readers of the Python client's `DataStreamReader` are `csv`, 
`json`, `orc`, `parquet`, `text` and `xml` 
(`crates/pyspark-rs/src/streaming.rs`). They set their format on the reader 
before they checked that `path` is a str, so a `NOT_EXPECTED_TYPE` of `path` 
left the reader with their format. PySpark's set their options, then raise 
`NOT_EXPECTED_TYPE` for a path that is not a str, before they call 
`load(path=path, format=...)`, which sets the format (pyspark/sql/connect/strea 
[...]
    
    The check is now one method, `PyDataStreamReader::format_path`:
    - the reader takes the options of the call;
    - a path that is not a str is `NOT_EXPECTED_TYPE`;
    - then the reader takes the format, and the path is checked as `load` 
checks it, so `VALUE_NOT_NON_EMPTY_STR` of an empty path still leaves the 
format, as in PySpark.
    
    ### Why are the changes needed?
    
    To match PySpark 4.3.0, and so that a later `load()` of the reader reads 
the format it was given:
    
    ```python
    r = spark.readStream.format("rate")
    r.json(123)       # PySparkTypeError: NOT_EXPECTED_TYPE, in both clients
    r._format         # PySpark 4.3.0: 'rate'; this client before: 'json'
    ```
    
    The same applies to the six readers, from a reader with no format (PySpark: 
`None`) and from one with a format, as checked with the Connect client of 
official PySpark 4.3.0. An empty path (`"  "`) leaves the reader's format, as 
in PySpark. The options of the call stay on the reader, as before.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, on unreleased changes. In the Python client, a stream format reader 
called with a path that is not a str no longer changes the reader's format.
    
    ### How was this patch tested?
    
    - 
`test_stream_format_readers_set_their_format_for_a_str_path_only_as_pyspark` in 
`python/tests/test_dropin_offline.py`, new. For the six readers, a path that is 
not a str, from no format and from a format, and an empty path. Also the 
options that `text()` leaves. It fails on an extension built from master and 
passes with the change. Every expected value was checked with official PySpark 
4.3.0.
    - The offline drop-in and ML suites (`tests/test_dropin_offline.py 
tests/test_ml_offline.py`), `cargo build -p pyspark-rs --release`, `cargo fmt 
--all -- --check`, `ruff check` and `ruff format --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 #547 from HyukjinKwon/SPARK-61057-followup-stream-format.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/streaming.rs  | 66 ++++++++++++++++++++-----------------
 python/tests/test_dropin_offline.py | 29 ++++++++++++++++
 2 files changed, 64 insertions(+), 31 deletions(-)

diff --git a/crates/pyspark-rs/src/streaming.rs 
b/crates/pyspark-rs/src/streaming.rs
index 88ebf58f..40f79bed 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -203,17 +203,6 @@ fn load_path(path: &Bound<'_, PyAny>) -> PyResult<String> {
     ))
 }
 
-/// The path of a format reader of `DataStreamReader`, such as `json`, as 
PySpark's takes it: a
-/// str, else `NOT_EXPECTED_TYPE` of `path`, which it then loads as `load` 
does.
-fn format_path(path: &Bound<'_, PyAny>) -> PyResult<String> {
-    if !path.is_instance_of::<pyo3::types::PyString>() {
-        return Err(crate::stat_arguments::not_expected_type(
-            path, "path", "str",
-        ));
-    }
-    load_path(path)
-}
-
 /// Coerce a `partitionBy` argument (a single column name or a list of names) 
to a
 /// column-name vector, mirroring PySpark's `str | list[str]` acceptance.
 fn extract_partition_cols(v: &Bound<'_, PyAny>) -> PyResult<Vec<String>> {
@@ -272,6 +261,27 @@ impl PyDataStreamReader {
     pub fn new(reader: DataStreamReader) -> Self {
         PyDataStreamReader { inner: reader }
     }
+
+    /// The path of a format reader, such as `json`, as PySpark's takes it, 
and the state that
+    /// it leaves on this reader, which takes `reader`, with the options of 
the call. A path that
+    /// is not a str is `NOT_EXPECTED_TYPE`, and the format of the reader 
stays as it was. Else
+    /// the reader takes `format`, and the path is checked as `load`, which 
PySpark's format
+    /// readers call with their format, checks it after setting the format.
+    fn format_path(
+        &mut self,
+        reader: &DataStreamReader,
+        format: &str,
+        path: &Bound<'_, PyAny>,
+    ) -> PyResult<String> {
+        self.inner = reader.clone();
+        if !path.is_instance_of::<pyo3::types::PyString>() {
+            return Err(crate::stat_arguments::not_expected_type(
+                path, "path", "str",
+            ));
+        }
+        self.inner = reader.clone().format(format);
+        load_path(path)
+    }
 }
 
 #[pymethods]
@@ -446,7 +456,7 @@ impl PyDataStreamReader {
         samplingRatio: Option<&Bound<'_, PyAny>>,
         locale: Option<&Bound<'_, PyAny>>,
     ) -> PyResult<PyDataFrame> {
-        let mut r = self.inner.clone().format("xml");
+        let mut r = self.inner.clone();
         r = set_stream_option_skip_none(r, "rowTag", rowTag)?;
         if let Some(v) = schema {
             r = apply_stream_schema(r, v)?;
@@ -473,10 +483,9 @@ impl PyDataStreamReader {
                 ("locale", locale),
             ],
         )?;
-        // Like PySpark, the options and the xml format stay on the reader.
-        self.inner = r.clone();
-        let path = format_path(path)?;
-        Ok(PyDataFrame::new(r.load(Some(&path))))
+        // Like PySpark, the options stay on the reader, and the format of a 
str path.
+        let path = self.format_path(&r, "xml", path)?;
+        Ok(PyDataFrame::new(r.format("xml").load(Some(&path))))
     }
 
     fn table(&self, tableName: &str) -> PyResult<PyDataFrame> {
@@ -545,9 +554,8 @@ impl PyDataStreamReader {
                 ("useUnsafeRow", useUnsafeRow),
             ],
         )?;
-        // Like PySpark, the options and the format stay on the reader.
-        self.inner = r.clone().format("json");
-        let path = format_path(path)?;
+        // Like PySpark, the options stay on the reader, and the format of a 
str path.
+        let path = self.format_path(&r, "json", path)?;
         Ok(PyDataFrame::new(r.json(&path)))
     }
 
@@ -573,9 +581,8 @@ impl PyDataStreamReader {
                 ("int96RebaseMode", int96RebaseMode),
             ],
         )?;
-        // Like PySpark, the options and the format stay on the reader.
-        self.inner = r.clone().format("parquet");
-        let path = format_path(path)?;
+        // Like PySpark, the options stay on the reader, and the format of a 
str path.
+        let path = self.format_path(&r, "parquet", path)?;
         Ok(PyDataFrame::new(r.parquet(&path)))
     }
 
@@ -653,9 +660,8 @@ impl PyDataStreamReader {
                 ("unescapedQuoteHandling", unescapedQuoteHandling),
             ],
         )?;
-        // Like PySpark, the options and the format stay on the reader.
-        self.inner = r.clone().format("csv");
-        let path = format_path(path)?;
+        // Like PySpark, the options stay on the reader, and the format of a 
str path.
+        let path = self.format_path(&r, "csv", path)?;
         Ok(PyDataFrame::new(r.csv(&path)))
     }
 
@@ -677,9 +683,8 @@ impl PyDataStreamReader {
                 ("recursiveFileLookup", recursiveFileLookup),
             ],
         )?;
-        // Like PySpark, the options and the format stay on the reader.
-        self.inner = r.clone().format("orc");
-        let path = format_path(path)?;
+        // Like PySpark, the options stay on the reader, and the format of a 
str path.
+        let path = self.format_path(&r, "orc", path)?;
         Ok(PyDataFrame::new(r.orc(&path)))
     }
 
@@ -710,9 +715,8 @@ impl PyDataStreamReader {
                 ("recursiveFileLookup", recursiveFileLookup),
             ],
         )?;
-        // Like PySpark, the options and the format stay on the reader.
-        self.inner = r.clone().format("text");
-        let path = format_path(path)?;
+        // Like PySpark, the options stay on the reader, and the format of a 
str path.
+        let path = self.format_path(&r, "text", path)?;
         Ok(PyDataFrame::new(r.text(&path)))
     }
 }
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 85cb7722..90047b8c 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -20628,6 +20628,35 @@ def 
test_stream_reader_converts_bool_options_as_pyspark(offline_spark):
     assert r._options["header"] == "True"
 
 
+def 
test_stream_format_readers_set_their_format_for_a_str_path_only_as_pyspark(offline_spark):
+    # As PySpark's DataStreamReader.json, csv, parquet, orc, text and xml: 
their options stay on
+    # the reader, and a path that is not a str is NOT_EXPECTED_TYPE before 
load, which sets the
+    # format, so the format of the reader stays as it was. A str path goes to 
load, which sets
+    # the format before its VALUE_NOT_NON_EMPTY_STR.
+    from pyspark.errors import PySparkTypeError, PySparkValueError
+
+    for name in ("json", "csv", "parquet", "orc", "text", "xml"):
+        kwargs = {"rowTag": "row"} if name == "xml" else {}
+        for start in (None, "rate"):
+            r = offline_spark.readStream
+            if start is not None:
+                r = r.format(start)
+            with pytest.raises(PySparkTypeError) as e:
+                getattr(r, name)(123, **kwargs)
+            assert e.value.getCondition() == "NOT_EXPECTED_TYPE"
+            assert r._format == start, name
+        r = offline_spark.readStream.format("rate")
+        with pytest.raises(PySparkValueError) as e:
+            getattr(r, name)("  ", **kwargs)
+        assert e.value.getCondition() == "VALUE_NOT_NON_EMPTY_STR"
+        assert r._format == name
+    r = offline_spark.readStream
+    with pytest.raises(PySparkTypeError):
+        r.text(123, lineSep="|")
+    assert r._format is None
+    assert r._options == {"wholetext": "False", "lineSep": "|"}
+
+
 def 
test_text_sets_its_wholetext_default_over_an_earlier_option_as_pyspark(offline_spark):
     # As PySpark's text(paths, wholetext=False, ...), whose _set_opts sets the 
default on every
     # call: an earlier wholetext option is overridden, unless wholetext=None, 
which is skipped.


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

Reply via email to