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 db86e783 [SPARK-61435][CONNECT][PYTHON] Send the bytes() of a bytes or
bytearray subclass in a binary column of createDataFrame in the Python client,
as PySpark does
db86e783 is described below
commit db86e78352ed3ac603ae358bd9fef93eb9011509
Author: Timothy Meehan <[email protected]>
AuthorDate: Thu Nov 12 08:31:52 2026 +0900
[SPARK-61435][CONNECT][PYTHON] Send the bytes() of a bytes or bytearray
subclass in a binary column of createDataFrame in the Python client, as PySpark
does
### What changes were proposed in this pull request?
[SPARK-61435](https://issues.apache.org/jira/browse/SPARK-61435):
createDataFrame of the Python client sends the bytes() of a bytes or bytearray
subclass in a binary column, as PySpark does.
- The `BinaryType` branch of `convert` (`crates/pyspark-rs/src/infer.rs`)
read the buffer of any `bytes` or `bytearray`, subclasses included.
- Now an exact `bytes` or `bytearray` is read as before, and a subclass
goes through `bytes(value)`, which takes its `__bytes__`.
### Why are the changes needed?
PySpark's `convert_binary` (`pyspark/sql/conversion.py`) first asserts that
the value is `bytes` or `bytearray`, then returns an exact `bytes` as it is and
calls `bytes(value)` on any other. For a subclass with its own `__bytes__`, the
Python client sent the buffer instead, so the data differed with no error.
### Does this PR introduce _any_ user-facing change?
Yes. A `bytes` or `bytearray` subclass with a `__bytes__` in a binary
column is sent as the result of `bytes()`. Before, with `class B(bytes)`
returning `b"other"` from `__bytes__`, `createDataFrame([(B(b"orig"),)], "b
binary").collect()` gave `b'orig'`; PySpark and now the client give `b'other'`.
### How was this patch tested?
- Python offline: `test_binary_subclasses_are_sent_as_the_bytes_of_pyspark`
checks the Arrow data sent for a bytes subclass and a bytearray subclass with
`__bytes__`, a subclass without it, plain bytes, bytearray and None, a subclass
inside `array<binary>`, and the errors of a `__bytes__` that returns a
non-bytes (`TypeError`) or raises (passed through). It fails on the base build
(`b'orig'` against `b'other'`).
- Python e2e (`test_dropin_e2e.py`):
`test_binary_subclasses_are_sent_as_the_bytes_of_pyspark` against a local Spark
4.3.0 Connect server; it passes with pyspark-client 4.3.0 as well.
- Rust library: 602 passed, and `-p apache-spark-connect-core` passes.
Python offline suites: 3119 passed, 8 skipped. Python e2e suites: 292 passed, 1
skipped. `ruff check` passes. All Rust test targets compile with and without
`wasm-udf`; `cargo fmt --all --check` passes, and clippy reports nothing in
`infer.rs`.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5 and Claude Sonnet 5.5
This pull request and its description were written by Isaac.
Closes #521 from tdcmeehan/SPARK-61435-binary-subclasses.
Authored-by: Timothy Meehan <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/infer.rs | 8 +++++--
python/tests/test_dropin_e2e.py | 17 +++++++++++++++
python/tests/test_dropin_offline.py | 43 +++++++++++++++++++++++++++++++++++++
3 files changed, 66 insertions(+), 2 deletions(-)
diff --git a/crates/pyspark-rs/src/infer.rs b/crates/pyspark-rs/src/infer.rs
index a0512236..bf022020 100644
--- a/crates/pyspark-rs/src/infer.rs
+++ b/crates/pyspark-rs/src/infer.rs
@@ -1222,10 +1222,14 @@ pub(crate) fn convert(obj: &Bound<'_, PyAny>, dt:
&DataType, nullable: bool) ->
Ok(Value::Map(entries))
}
DataType::Binary => {
- if let Ok(bytes) = obj.cast::<PyBytes>() {
+ if let Ok(bytes) = obj.cast_exact::<PyBytes>() {
Ok(Value::Binary(bytes.as_bytes().to_vec()))
- } else if let Ok(bytes) = obj.cast::<PyByteArray>() {
+ } else if let Ok(bytes) = obj.cast_exact::<PyByteArray>() {
Ok(Value::Binary(bytes.to_vec()))
+ } else if obj.is_instance_of::<PyBytes>() ||
obj.is_instance_of::<PyByteArray>() {
+ // bytes(obj) honors a __bytes__ of the subclass, which its
buffer does not.
+ let bytes = py.get_type::<PyBytes>().call1((obj,))?;
+ Ok(Value::Binary(bytes.cast::<PyBytes>()?.as_bytes().to_vec()))
} else {
Err(assertion())
}
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index c24086f1..ac85c0d6 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -5360,3 +5360,20 @@ def
test_decision_tree_classifier_rejects_invalid_parameters_and_training_data(s
DecisionTreeClassifier().fit(training.drop("features"))
with pytest.raises(Exception):
DecisionTreeClassifier().fit(training.withColumn("features",F.array(F.lit(1.0))))
+
+
+def test_binary_subclasses_are_sent_as_the_bytes_of_pyspark(session):
+ class Bytes(bytes):
+ def __bytes__(self):
+ return b"other"
+
+ class ByteArray(bytearray):
+ def __bytes__(self):
+ return b"other"
+
+ rows = session.createDataFrame(
+ [(Bytes(b"orig"),), (ByteArray(b"orig"),), (bytearray(b"ba"),),
(None,)], "b binary"
+ ).collect()
+ assert [row.b for row in rows] == [b"other", b"other", b"ba", None]
+ rows = session.createDataFrame([([Bytes(b"orig")],)], "a
array<binary>").collect()
+ assert rows[0].a == [b"other"]
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 3ddf86a8..162c6770 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -2801,6 +2801,49 @@ def test_udtfs_are_created_as_pyspark(mock_connect):
assert service.read_confs == [arrow_conf] + [binary_conf] * 5 +
[arrow_conf] + [binary_conf] * 2
+def test_binary_subclasses_are_sent_as_the_bytes_of_pyspark(mock_connect):
+ # As PySpark: bytes(value), which takes the __bytes__ of a subclass, not
its buffer.
+ import pyarrow as pa
+
+ class Bytes(bytes):
+ def __bytes__(self):
+ return b"other"
+
+ class ByteArray(bytearray):
+ def __bytes__(self):
+ return b"other"
+
+ class Plain(bytes):
+ pass
+
+ spark, service = mock_connect
+ values = [Bytes(b"orig"), ByteArray(b"orig"), Plain(b"plain"),
bytearray(b"ba"), b"b", None]
+ df = spark.createDataFrame([(v,) for v in values], "b binary")
+ df.columns
+ relation = _sent_relation(service.analyze_requests[-1], 11)
+ table = pa.ipc.open_stream(relation[1][0]).read_all()
+ assert table.column(0).to_pylist() == [b"other", b"other", b"plain",
b"ba", b"b", None]
+
+ class NotBytes(bytes):
+ def __bytes__(self):
+ return "x"
+
+ class Raises(bytes):
+ def __bytes__(self):
+ raise KeyError("boom")
+
+ with pytest.raises(TypeError, match="__bytes__ returned non-bytes"):
+ spark.createDataFrame([(NotBytes(b"a"),)], "b binary")
+ with pytest.raises(KeyError, match="boom"):
+ spark.createDataFrame([(Raises(b"a"),)], "b binary")
+
+ df = spark.createDataFrame([([Bytes(b"orig"), None],)], "a array<binary>")
+ df.columns
+ relation = _sent_relation(service.analyze_requests[-1], 11)
+ table = pa.ipc.open_stream(relation[1][0]).read_all()
+ assert table.column(0).to_pylist() == [[b"other", None]]
+
+
def test_time_values_are_sent_as_pyspark(mock_connect):
# As PySpark: a datetime.time is of TimeType(), and createDataFrame sends
it as PyArrow's
# time64[ns] of the value, which takes the nanoseconds of an int too, and
lit() of it is
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]