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 bae21f3b [SPARK-61497][CONNECT][PYTHON] Raise for a str that UTF-8
cannot encode in the options of the stream reader, and set the wholetext
default of text(), in the Python client as PySpark does
bae21f3b is described below
commit bae21f3be8e0f447c55f49089da0b129f8a21d1b
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 12:21:31 2026 +0900
[SPARK-61497][CONNECT][PYTHON] Raise for a str that UTF-8 cannot encode in
the options of the stream reader, and set the wholetext default of text(), in
the Python client as PySpark does
### What changes were proposed in this pull request?
[SPARK-61497](https://issues.apache.org/jira/browse/SPARK-61497):
follow-ups of a post-hoc review of SPARK-61475 (#532), checked against PySpark
4.3.0.
- **Options of the stream reader** (`crates/pyspark-rs/src/options.rs`,
`stream_option_value`): a value is converted with `str_text`, as the batch
reader's `coerce_option_value` does. This covers `DataStreamReader.option` and
the options of its format methods, including the `path` option that `load()`
sends.
- **`text()`'s `wholetext`** (`crates/pyspark-rs/src/readwriter.rs`,
`crates/pyspark-rs/src/streaming.rs`):
- The batch and stream readers' `text` now take PySpark's default
`wholetext=False` and set it on every call, as PySpark's `_set_opts` does. An
explicit `wholetext=None` is still skipped.
- A new `DefaultedOption` (`options.rs`) tells an omitted argument apart
from None, as `replace` and `range` already do.
- The signatures show `wholetext=False`.
### Why are the changes needed?
- **Lossy stream options.**
- SPARK-61475 made the stream reader's options the `str()` of their
values, through PyO3's lossy `Display`.
- So a str that UTF-8 cannot encode was sent as U+FFFD three times, which
is another text, for example another path. Such a str is, for example, a lone
surrogate from a `surrogateescape`-decoded path.
- PySpark raises protobuf's `ValueError`. So do the batch reader,
`readStream.options()` and `load(**options)` of the Python client.
- **The wholetext default.**
- PySpark's `text(paths, wholetext=False, ...)` sets `wholetext` on every
call.
- So `spark.read.option("wholetext", True).text(path)` reads one row per
line in PySpark. The Python client kept the earlier option and read one row per
file.
- The same holds for `read.options(wholetext="true")` and the stream
reader.
- `readStream.text(path)` also leaves `wholetext` in the reader's options
in PySpark (`{'wholetext': 'False'}`), and left none in the Python client.
### Does this PR introduce _any_ user-facing change?
Yes, as in PySpark:
- A stream reader option that UTF-8 cannot encode raises `ValueError`.
- `text()` overrides an earlier `wholetext` option with its default.
### How was this patch tested?
- Offline (`python/tests/test_dropin_offline.py`):
-
`test_strings_that_utf8_cannot_encode_raise_value_error_as_options_and_fills_as_pyspark`
also checks `readStream.option`, `readStream.text(lineSep=...)` and
`readStream.format("text").option("path", ...)`.
- New
`test_text_sets_its_wholetext_default_over_an_earlier_option_as_pyspark`,
placed before `test_writer_setters_mutate_and_return_self`. It checks the
options of the batch and stream readers after `text()`: with the default, with
`wholetext=None` and with `wholetext=True`. It also checks the default `False`
of their signatures.
- Both fail without the change: `DID NOT RAISE <class 'ValueError'>` and
`assert 'true' == 'false'`.
- Live, against a local Spark 4.3.0 server, on one file of two lines:
- `read.option("wholetext", True).text(d).count()`,
`read.options(wholetext="true").text(d).count()`, and the rows of the stream
reader's equivalent (availableNow), are 2, 2 and 2, as with PySpark 4.3.0. They
were 1, 1 and 1.
- The stream reader's surrogate cases raise `ValueError`, as with
PySpark. Ours raises at the call, as the batch reader already does; PySpark
raises when the plan is serialized.
- Checks:
- the lib tests of both crates (828 passed);
- the build of all tests, also with `wasm-udf` and `datafusion,polars`,
without warnings;
- `cargo fmt --all --check`, and clippy with no diagnostics on the
changed lines;
- `ruff check`;
- a full trial on master before the merge.
### 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 #544 from HyukjinKwon/s19-reader-options.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/options.rs | 32 ++++++++++++++++++++++++++++++--
crates/pyspark-rs/src/readwriter.rs | 16 +++++++++++-----
crates/pyspark-rs/src/streaming.rs | 15 +++++++++++----
python/tests/test_dropin_offline.py | 26 ++++++++++++++++++++++++++
4 files changed, 78 insertions(+), 11 deletions(-)
diff --git a/crates/pyspark-rs/src/options.rs b/crates/pyspark-rs/src/options.rs
index 85908dde..98d9cfaa 100644
--- a/crates/pyspark-rs/src/options.rs
+++ b/crates/pyspark-rs/src/options.rs
@@ -198,12 +198,40 @@ pub(crate) fn set_opts(
/// 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.
+/// it through `to_str`. None is left out. A str that UTF-8 cannot encode
raises, as
+/// [`str_text`].
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()))
+ Ok(Some(str_text(v)?))
+}
+
+/// An option argument of a format method whose Python default is not None,
which PySpark's
+/// `_set_opts` then sets on every call, over an earlier option of the same
name: `text`'s
+/// `wholetext=False`. An omitted argument is that default, and None is
skipped, as PySpark
+/// tells them apart.
+pub(crate) enum DefaultedOption {
+ Omitted,
+ Given(Py<PyAny>),
+}
+
+impl<'a, 'py> FromPyObject<'a, 'py> for DefaultedOption {
+ type Error = PyErr;
+
+ fn extract(obj: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
+ Ok(DefaultedOption::Given(obj.to_owned().unbind()))
+ }
+}
+
+impl DefaultedOption {
+ /// The value of the argument, `default` when it is omitted.
+ pub(crate) fn or_bool<'py>(&self, py: Python<'py>, default: bool) ->
Bound<'py, PyAny> {
+ match self {
+ DefaultedOption::Omitted => PyBool::new(py,
default).to_owned().into_any(),
+ DefaultedOption::Given(value) => value.bind(py).clone(),
+ }
+ }
}
/// `builder` with the option `name` of `value` for the stream reader,
**skipping** a `value` that
diff --git a/crates/pyspark-rs/src/readwriter.rs
b/crates/pyspark-rs/src/readwriter.rs
index 6d74200d..04932658 100644
--- a/crates/pyspark-rs/src/readwriter.rs
+++ b/crates/pyspark-rs/src/readwriter.rs
@@ -10,7 +10,7 @@ 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,
- set_reader_option_unset_none,
+ set_reader_option_unset_none, DefaultedOption,
};
/// Python wrapper for the batch DataFrameReader.
@@ -547,24 +547,30 @@ impl PyDataFrameReader {
}
/// Read TEXT file(s) - full pyspark signature; each named option is
- /// applied as a read option when provided.
- #[pyo3(signature = (paths, wholetext=None, lineSep=None,
pathGlobFilter=None, recursiveFileLookup=None, modifiedBefore=None,
modifiedAfter=None))]
+ /// applied as a read option when provided. As PySpark's
`wholetext=False`, an omitted
+ /// `wholetext` sets `false`, also over an earlier `wholetext` option.
+ #[pyo3(
+ signature = (paths, wholetext=DefaultedOption::Omitted, lineSep=None,
pathGlobFilter=None, recursiveFileLookup=None, modifiedBefore=None,
modifiedAfter=None),
+ text_signature = "($self, paths, wholetext=False, lineSep=None,
pathGlobFilter=None, recursiveFileLookup=None, modifiedBefore=None,
modifiedAfter=None)"
+ )]
#[allow(non_snake_case, clippy::too_many_arguments)]
fn text(
&mut self,
+ py: Python<'_>,
paths: &Bound<'_, PyAny>,
- wholetext: Option<&Bound<'_, PyAny>>,
+ wholetext: DefaultedOption,
lineSep: Option<&Bound<'_, PyAny>>,
pathGlobFilter: Option<&Bound<'_, PyAny>>,
recursiveFileLookup: Option<&Bound<'_, PyAny>>,
modifiedBefore: Option<&Bound<'_, PyAny>>,
modifiedAfter: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyDataFrame> {
+ let wholetext = wholetext.or_bool(py, false);
let mut r = self.inner.clone();
r = set_options_skip_none(
r,
&[
- ("wholetext", wholetext),
+ ("wholetext", Some(&wholetext)),
("lineSep", lineSep),
("pathGlobFilter", pathGlobFilter),
("recursiveFileLookup", recursiveFileLookup),
diff --git a/crates/pyspark-rs/src/streaming.rs
b/crates/pyspark-rs/src/streaming.rs
index 1e5b2410..88ebf58f 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_stream_option_skip_none,
set_stream_options_skip_none};
+use crate::options::{set_stream_option_skip_none,
set_stream_options_skip_none, DefaultedOption};
/// 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
@@ -683,21 +683,28 @@ impl PyDataStreamReader {
Ok(PyDataFrame::new(r.orc(&path)))
}
- #[pyo3(signature = (path, wholetext=None, lineSep=None,
pathGlobFilter=None, recursiveFileLookup=None))]
+ /// As PySpark's `wholetext=False`, an omitted `wholetext` sets `False`,
also over an earlier
+ /// `wholetext` option.
+ #[pyo3(
+ signature = (path, wholetext=DefaultedOption::Omitted, lineSep=None,
pathGlobFilter=None, recursiveFileLookup=None),
+ text_signature = "($self, path, wholetext=False, lineSep=None,
pathGlobFilter=None, recursiveFileLookup=None)"
+ )]
#[allow(non_snake_case)]
fn text(
&mut self,
+ py: Python<'_>,
path: &Bound<'_, PyAny>,
- wholetext: Option<&Bound<'_, PyAny>>,
+ wholetext: DefaultedOption,
lineSep: Option<&Bound<'_, PyAny>>,
pathGlobFilter: Option<&Bound<'_, PyAny>>,
recursiveFileLookup: Option<&Bound<'_, PyAny>>,
) -> PyResult<PyDataFrame> {
+ let wholetext = wholetext.or_bool(py, false);
let mut r = self.inner.clone();
r = set_stream_options_skip_none(
r,
&[
- ("wholetext", wholetext),
+ ("wholetext", Some(&wholetext)),
("lineSep", lineSep),
("pathGlobFilter", pathGlobFilter),
("recursiveFileLookup", recursiveFileLookup),
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 7c9f57f6..df082e92 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -6908,6 +6908,9 @@ def
test_strings_that_utf8_cannot_encode_raise_value_error_as_options_and_fills_
lambda: df.write.option("path", bad),
lambda: df.write.options(**{bad: "v"}),
lambda: spark.readStream.options(**{bad: "v"}),
+ lambda: spark.readStream.option("lineSep", bad),
+ lambda: spark.readStream.text("/t", lineSep=bad),
+ lambda: spark.readStream.format("text").option("path", bad),
lambda: SparkSession.builder.config(map={bad: "v"}),
]:
with pytest.raises(ValueError, match=message):
@@ -20280,6 +20283,29 @@ def
test_stream_reader_converts_bool_options_as_pyspark(offline_spark):
assert r._options["header"] == "True"
+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.
+ # The batch reader sets "false", as to_str, and the stream reader "False",
as str.
+ import inspect
+
+ for reader, default, given in [
+ (lambda: offline_spark.read, "false", "true"),
+ (lambda: offline_spark.readStream, "False", "True"),
+ ]:
+ r = reader().option("wholetext", True)
+ r.text("/t")
+ assert r._options["wholetext"] == default
+ r = reader().option("wholetext", True)
+ r.text("/t", wholetext=None)
+ assert r._options["wholetext"] == given
+ r = reader()
+ r.text("/t", wholetext=True)
+ assert r._options["wholetext"] == given
+ signature = inspect.signature(reader().text)
+ assert signature.parameters["wholetext"].default is False
+
+
def test_writer_setters_mutate_and_return_self(offline_spark):
w = offline_spark.range(3).write
assert w.mode("overwrite") is w
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]