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 507378ea [SPARK-61475][CONNECT][PYTHON] Send a bytes option of
createTable and a bool option of the streaming reader as PySpark does
507378ea is described below
commit 507378ea2fcd5679d598675a6cda5d39c37887f5
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 09:44:45 2026 +0900
[SPARK-61475][CONNECT][PYTHON] Send a bytes option of createTable and a
bool option of the streaming reader as PySpark does
### What changes were proposed in this pull request?
- `Catalog.createTable(..., **options)` now takes a bytes option as
PySpark's protobuf map of strings does: UTF-8 bytes are sent decoded, bytes
that are not UTF-8 raise protobuf's `ValueError`, and a bytearray or memoryview
raises its `TypeError`.
- `DataStreamReader.option` and the reader's format methods (`csv`, `json`,
`orc`, `parquet`, `text`, `xml`) now send a value as `str()` gives it, so a
bool is `"True"`/`"False"`, as PySpark's `DataStreamReader.option` does.
`options()` and `load()`, which lowercase a bool through `to_str` in PySpark,
are unchanged, as are the batch reader and writers and the stream writer.
### Why are the changes needed?
```python
spark.catalog.createTable("t", source="no_such_source", a=b"x")
# before: TypeError: b'x' has type <class 'bytes'>, but expected one of:
(<class 'bytes'>, <class 'str'>)
# PySpark 4.3.0: the request is sent (here the server answers
DATA_SOURCE_NOT_FOUND)
spark.readStream.option("a", True) # before {'a':
'true'}, PySpark {'a': 'True'}
spark.readStream.csv(p, header=True, inferSchema=False) # before
'true'/'false', PySpark 'True'/'False'
spark.readStream.options(a=True) # 'true' in both,
unchanged
```
The server reads both spellings of a built-in boolean option, but a custom
data source sees the text as sent. This is a follow-up of SPARK-61429 (#504).
### Does this PR introduce _any_ user-facing change?
Yes. `createTable` takes UTF-8 bytes options, and the stream reader's
`option` and format methods send a bool as `"True"`/`"False"`, both as PySpark
does.
### How was this patch tested?
- New offline tests in `python/tests/test_dropin_offline.py`,
`test_stream_reader_converts_bool_options_as_pyspark` and
`test_catalog_create_table_takes_bytes_options_as_protobuf_does`, which fail
without the fix. The existing
`test_stream_reader_checks_its_arguments_as_pyspark` now expects `"True"` for
`json(..., multiLine=True)`, as the reference gives.
- A new e2e test in `python/tests/test_dropin_e2e.py` runs a stream
`csv(header=True)` and a `createTable` with `compression=b"snappy"` against a
Spark 4.3.0 server.
- Probes of the reference client and this one give the same values and
errors.
- The offline suite (1837 passed), the e2e suite against Spark 4.3.0 (262
passed), the Rust library tests, the `--no-run` builds (with and without
`wasm-udf`), `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 #532 from HyukjinKwon/SPARK-61475-options.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/options.rs | 65 +++++++++++++++++++++++++++++++++----
crates/pyspark-rs/src/streaming.rs | 21 ++++++------
python/tests/test_dropin_e2e.py | 16 +++++++++
python/tests/test_dropin_offline.py | 38 +++++++++++++++++++++-
4 files changed, 123 insertions(+), 17 deletions(-)
diff --git a/crates/pyspark-rs/src/options.rs b/crates/pyspark-rs/src/options.rs
index 4a0f027b..85908dde 100644
--- a/crates/pyspark-rs/src/options.rs
+++ b/crates/pyspark-rs/src/options.rs
@@ -10,12 +10,13 @@
//! - **unset**: the `None` removes the key from the builder. This is
`DataFrameReader.option`,
//! `options` and `load`.
//!
-//! Every other value goes through [`coerce_option_value`].
+//! Every other value goes through [`coerce_option_value`], or through
[`stream_option_value`] for
+//! the option and the format methods of the stream reader, which PySpark
converts differently.
use std::collections::HashMap;
use pyo3::prelude::*;
-use pyo3::types::{PyBool, PyDict, PyString};
+use pyo3::types::{PyBool, PyBytes, PyDict, PyString};
use spark_connect::readwriter::{DataFrameReader, DataFrameWriter};
use spark_connect::streaming::DataStreamReader;
@@ -138,7 +139,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, which takes a str and raises a `TypeError` for
anything else.
+/// 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.
pub(crate) fn str_kwargs_skip_none(
options: Option<&Bound<'_, PyDict>>,
) -> PyResult<HashMap<String, String>> {
@@ -147,15 +149,28 @@ pub(crate) fn str_kwargs_skip_none(
if value.is_none() {
continue;
}
- if !value.is_instance_of::<PyString>() {
+ 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()?, value.extract()?);
+ };
+ map.insert(key.extract()?, text);
}
Ok(map)
}
@@ -180,3 +195,41 @@ pub(crate) fn set_opts(
}
Ok(())
}
+
+/// The text of an option of the stream reader, as `DataStreamReader.option`
and its format methods
+/// send it: the `str()` of the value, so a bool is `"True"`, where `options`
and `load` lowercase
+/// it through `to_str`. None is left out.
+pub(crate) fn stream_option_value(v: &Bound<'_, PyAny>) ->
PyResult<Option<String>> {
+ if v.is_none() {
+ return Ok(None);
+ }
+ Ok(Some(v.str()?.to_string()))
+}
+
+/// `builder` with the option `name` of `value` for the stream reader,
**skipping** a `value` that
+/// is absent or None, as [`set_option_skip_none`] does with
[`stream_option_value`].
+pub(crate) fn set_stream_option_skip_none(
+ builder: DataStreamReader,
+ name: &str,
+ value: Option<&Bound<'_, PyAny>>,
+) -> PyResult<DataStreamReader> {
+ match value {
+ Some(value) => match stream_option_value(value)? {
+ Some(value) => Ok(builder.option(name, &value)),
+ None => Ok(builder),
+ },
+ None => Ok(builder),
+ }
+}
+
+/// `builder` with each of `options` in order for the stream reader,
**skipping** those that are
+/// absent or None, as [`set_options_skip_none`] does with
[`set_stream_option_skip_none`].
+pub(crate) fn set_stream_options_skip_none(
+ mut builder: DataStreamReader,
+ options: &[(&str, Option<&Bound<'_, PyAny>>)],
+) -> PyResult<DataStreamReader> {
+ for (name, value) in options {
+ builder = set_stream_option_skip_none(builder, name, *value)?;
+ }
+ Ok(builder)
+}
diff --git a/crates/pyspark-rs/src/streaming.rs
b/crates/pyspark-rs/src/streaming.rs
index efff48b9..3f5c470f 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -14,7 +14,7 @@ use std::sync::Arc;
use crate::dataframe::{PyDataFrame, WriterState};
use crate::errors::spark_error_to_py_exception;
use crate::interrupt::{interruptible, interruptible_outcome};
-use crate::options::{set_option_skip_none, set_options_skip_none};
+use crate::options::{set_stream_option_skip_none,
set_stream_options_skip_none};
/// Adapts Python listeners to the native bus: deserialize one typed event for
the whole
/// snapshot, then dispatch it through Python's callback-exception isolation
helper. Decode
@@ -315,8 +315,9 @@ impl PyDataStreamReader {
key: &str,
value: &Bound<'_, PyAny>,
) -> PyResult<PyRefMut<'py, Self>> {
- // None -> option left unset; bools -> "true"/"false" (reference
`to_str`).
- match crate::coerce_option_value(value)? {
+ // None -> option left unset; other values as `str()`, so a bool is
"True" (reference
+ // `DataStreamReader.option`, unlike `options` and `load`).
+ match crate::options::stream_option_value(value)? {
Some(v) => {
slf.inner = slf.inner.clone().option(key, &v);
Ok(slf)
@@ -446,11 +447,11 @@ impl PyDataStreamReader {
locale: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyDataFrame> {
let mut r = self.inner.clone().format("xml");
- r = set_option_skip_none(r, "rowTag", rowTag)?;
+ r = set_stream_option_skip_none(r, "rowTag", rowTag)?;
if let Some(v) = schema {
r = apply_stream_schema(r, v)?;
}
- r = set_options_skip_none(
+ r = set_stream_options_skip_none(
r,
&[
("excludeAttribute", excludeAttribute),
@@ -515,7 +516,7 @@ impl PyDataStreamReader {
if let Some(v) = schema {
r = apply_stream_schema(r, v)?;
}
- r = set_options_skip_none(
+ r = set_stream_options_skip_none(
r,
&[
("primitivesAsString", primitivesAsString),
@@ -562,7 +563,7 @@ impl PyDataStreamReader {
int96RebaseMode: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyDataFrame> {
let mut r = self.inner.clone();
- r = set_options_skip_none(
+ r = set_stream_options_skip_none(
r,
&[
("mergeSchema", mergeSchema),
@@ -618,7 +619,7 @@ impl PyDataStreamReader {
if let Some(v) = schema {
r = apply_stream_schema(r, v)?;
}
- r = set_options_skip_none(
+ r = set_stream_options_skip_none(
r,
&[
("sep", sep),
@@ -668,7 +669,7 @@ impl PyDataStreamReader {
recursiveFileLookup: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyDataFrame> {
let mut r = self.inner.clone();
- r = set_options_skip_none(
+ r = set_stream_options_skip_none(
r,
&[
("mergeSchema", mergeSchema),
@@ -693,7 +694,7 @@ impl PyDataStreamReader {
recursiveFileLookup: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyDataFrame> {
let mut r = self.inner.clone();
- r = set_options_skip_none(
+ r = set_stream_options_skip_none(
r,
&[
("wholetext", wholetext),
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 573e610c..7fabf624 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -1854,6 +1854,22 @@ def test_reader_schema_keeps_field_metadata(session,
tmp_path, ddl):
assert stream.schema.fields[0].metadata == {"comment": "the key"}
+def
test_bool_stream_options_and_bytes_table_options_are_read_by_the_server(session,
tmp_path):
+ # As PySpark's: the stream format methods send a bool as "True", which the
server reads as
+ # true, and createTable sends bytes that are UTF-8 as their text, as its
compression.
+ (tmp_path / "s").mkdir()
+ schema = StructType([StructField("a", LongType())])
+ stream = session.readStream.schema(schema).csv(str(tmp_path / "s"),
header=True)
+ assert stream.isStreaming
+ session.sql("DROP TABLE IF EXISTS e2e_bytes_table_option")
+ try:
+ session.catalog.createTable(
+ "e2e_bytes_table_option", source="parquet", schema=schema,
compression=b"snappy")
+ assert session.catalog.tableExists("e2e_bytes_table_option")
+ finally:
+ session.sql("DROP TABLE IF EXISTS e2e_bytes_table_option")
+
+
def
test_reader_none_unsets_an_option_and_external_description_is_the_comment(session,
tmp_path):
# As PySpark's: DataFrameReader.option, options and load unset an option
given None, while
# the format methods skip None and keep it. createExternalTable's
description is the
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index ca74ad35..af8308e1 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -19254,7 +19254,8 @@ def
test_stream_reader_checks_its_arguments_as_pyspark(offline_spark):
assert e.value.getCondition() == "VALUE_NOT_NON_EMPTY_STR"
with pytest.raises(PySparkTypeError):
reader.json(1, multiLine=True)
- assert reader._options["multiLine"] == "true"
+ # As PySpark's format methods, which set their options through option, a
bool is "True".
+ assert reader._options["multiLine"] == "True"
with pytest.raises(AnalysisException) as e:
offline_spark.readStream.schema("id long").changes("t")
assert e.value.getCondition() == "_LEGACY_ERROR_TEMP_1189"
@@ -19367,6 +19368,22 @@ def
test_stream_reader_setters_mutate_and_return_self(offline_spark):
assert type(r.load()).__name__ == "DataFrame"
+def test_stream_reader_converts_bool_options_as_pyspark(offline_spark):
+ # As PySpark's DataStreamReader: option sets str(value), and so do the
format methods, which
+ # set their options through option, so a bool is "True"; options and load
lower it, as to_str.
+ r = offline_spark.readStream
+ assert r.option("a", True) is r and r.option("b", False) is r
+ assert r.option("c", None) is r
+ assert r._options == {"a": "True", "b": "False"}
+ assert r.options(d=True, e=False, f=None) is r
+ assert r._options == {"a": "True", "b": "False", "d": "true", "e": "false"}
+ r.csv("/c", header=True, inferSchema=False)
+ assert r._options["header"] == "True" and r._options["inferSchema"] ==
"False"
+ r.load("/l", format="json", g=True)
+ assert r._options["g"] == "true"
+ assert r._options["header"] == "True"
+
+
def test_writer_setters_mutate_and_return_self(offline_spark):
w = offline_spark.range(3).write
assert w.mode("overwrite") is w
@@ -20147,6 +20164,25 @@ def
test_catalog_creates_tables_eagerly_as_pyspark(mock_connect):
spark.catalog.createExternalTable("e", schema=1)
+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.
+ 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"]}]
+ spark.catalog.createTable("t", source="parquet", a="\u00e9".encode())
+ 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"):
+ spark.catalog.createTable("t", source="parquet", a=b"\xff\xfe")
+ for value in (bytearray(b"x"), memoryview(b"x")):
+ with pytest.raises(TypeError, match=r"has type <class
'(bytearray|memoryview)'>"):
+ spark.catalog.createTable("t", source="parquet", a=value)
+ assert len(service.execute_requests) == calls
+
+
@pytest.mark.parametrize("call, method", [
(lambda catalog, *db: catalog.tableExists("t", *db), "tableExists"),
(lambda catalog, *db: catalog.functionExists("f", *db), "functionExists"),
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]