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 d8f6c22b [SPARK-61535][CONNECT][PYTHON] Write to a bytes path in the 
writers of the Python client, as PySpark does
d8f6c22b is described below

commit d8f6c22b54e669c4c69280b2e512431d371ea62a
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 20:46:50 2026 +0900

    [SPARK-61535][CONNECT][PYTHON] Write to a bytes path in the writers of the 
Python client, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    The path of the writers of the Python client (`save` and 
`parquet`/`json`/`csv`/`orc`/`text`/`xml` of `DataFrameWriter`, and 
`DataStreamWriter.start`) is now converted with `str_argument`, which converts 
a protobuf string field as protobuf's default (upb) backend does: a str as its 
UTF-8, bytes decoded as UTF-8, the `UnicodeDecodeError` of bytes that are not 
UTF-8, and the `TypeError` "bad argument type for built-in operation" of 
another object.
    
    ### Why are the changes needed?
    
    SPARK-61521 (#559) checked the path for a str only, so a bytes path raised 
`TypeError`. PySpark sets the path in a protobuf string field as it is, which 
upb takes as the UTF-8 text of bytes:
    
    ```python
    spark.range(2).write.mode("overwrite").save(b"/tmp/out")
    # PySpark 4.3.0 (upb): writes /tmp/out; before: TypeError: bad argument 
type for built-in operation
    spark.range(2).write.save(b"/tmp/\xff")
    # PySpark: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in 
position 5: invalid start byte
    spark.range(2).write.save(bytearray(b"/tmp/x"))
    # PySpark and this client: TypeError: bad argument type for built-in 
operation
    ```
    
    `str_argument` came with SPARK-61524 (#560), and this makes the writers' 
path use it. This is a follow-up of SPARK-61521.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. A writer or `DataStreamWriter.start` writes to a bytes path, and 
raises `UnicodeDecodeError` for bytes that are not UTF-8, as PySpark does.
    
    ### How was this patch tested?
    
    - A new offline test, `test_writers_take_a_bytes_path_as_pyspark`, checks 
the path sent for a bytes path of `save`, `json`, `parquet` and 
`DataStreamWriter.start`, and the `UnicodeDecodeError` for bytes that are not 
UTF-8. It fails without the change. The existing test of paths that are not a 
str now also covers a bytearray.
    - The reference client (protobuf 7.36.2, upb) gives the same results for 
these paths.
    - The offline suites (`test_dropin_offline.py`, `test_ml_offline.py`, 
`test_arrow_handoff.py`: 3232 passed) under upb, `cargo fmt --check`, 
`scripts/audit_no_stubs.sh` and the ruff gates.
    
    ### 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 #566 from HyukjinKwon/SPARK-61535-bytes-writer-path.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/readwriter.rs | 12 ++++--------
 python/tests/test_dropin_offline.py | 34 +++++++++++++++++++++++++++++++++-
 2 files changed, 37 insertions(+), 9 deletions(-)

diff --git a/crates/pyspark-rs/src/readwriter.rs 
b/crates/pyspark-rs/src/readwriter.rs
index caae0a47..552e50ee 100644
--- a/crates/pyspark-rs/src/readwriter.rs
+++ b/crates/pyspark-rs/src/readwriter.rs
@@ -109,15 +109,11 @@ fn path_list(paths: &[Bound<'_, PyAny>]) -> 
PyResult<Vec<String>> {
         .collect()
 }
 
-/// The path of a writer, a str, as its protobuf field takes it. Another type 
raises the TypeError
-/// of protobuf, which the upb backend of PySpark raises with this message.
+/// 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.
 pub(crate) fn writer_path(path: &Bound<'_, PyAny>) -> PyResult<String> {
-    if path.is_instance_of::<pyo3::types::PyString>() {
-        return path.extract();
-    }
-    Err(pyo3::exceptions::PyTypeError::new_err(
-        "bad argument type for built-in operation",
-    ))
+    crate::str_argument(path)
 }
 
 /// The columns of `df.write.bucketBy(numBuckets, col, *cols)` and 
`sortBy(col, *cols)`, as
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 1f15fdef..2d1698d9 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -7232,7 +7232,7 @@ def 
test_writers_and_readers_reject_a_path_that_is_not_a_str_as_pyspark(mock_con
     df = spark.range(1)
     stream = spark.readStream.format("rate").load().writeStream
     message = "bad argument type for built-in operation"
-    for path in [123, 1.5, ["a", 1]]:
+    for path in [123, 1.5, ["a", 1], bytearray(b"p")]:
         for call in [
             lambda: df.write.save(path),
             lambda: df.write.json(path),
@@ -7249,6 +7249,38 @@ def 
test_writers_and_readers_reject_a_path_that_is_not_a_str_as_pyspark(mock_con
     assert service.execute_requests == []
 
 
+def test_writers_take_a_bytes_path_as_pyspark(mock_connect):
+    # As PySpark's default protobuf backend (upb), which sets a bytes value of 
a string field as
+    # its UTF-8 text: the writers and DataStreamWriter.start write to a bytes 
path, and bytes that
+    # are not UTF-8 raise the UnicodeDecodeError of their decoding.
+    spark, service = mock_connect
+
+    def sent_command():
+        # ExecutePlanRequest.plan=3 -> Plan.command=2.
+        plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+        return parse_message(plan[2][0])
+
+    for write in [
+        lambda path: spark.range(1).write.save(path),
+        lambda path: spark.range(1).write.json(path),
+        lambda path: spark.range(1).write.parquet(path),
+    ]:
+        write(b"p")
+        # Command.write_operation=2 -> WriteOperation.path=3.
+        assert parse_message(sent_command()[2][0])[3] == [b"p"]
+        with pytest.raises(UnicodeDecodeError) as error:
+            write(b"\xff")
+        assert str(error.value) == (
+            "'utf-8' codec can't decode byte 0xff in position 0: invalid start 
byte"
+        )
+    # ExecutePlanResponse.write_stream_operation_start_result=8: query_id=1 
(id=1, run_id=2).
+    service.execute_payload = message_field(
+        8, message_field(1, message_field(1, "q") + message_field(2, "r")))
+    spark.readStream.format("rate").load().writeStream.start(b"s")
+    # Command.write_stream_operation_start=6 -> 
WriteStreamOperationStart.path=11.
+    assert parse_message(sent_command()[6][0])[11] == [b"s"]
+
+
 def 
test_readers_keep_their_settings_when_the_path_is_not_a_str_as_pyspark(mock_connect):
     # As PySpark, whose format readers set the options and the format before 
they check the path,
     # which is an AssertionError for a path that is not a str.


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

Reply via email to