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 db17d281 [SPARK-61264][CONNECT][PYTHON] Raise UnicodeDecodeError for a
string that is not valid UTF-8 in collect, in the Python client as PySpark does
db17d281 is described below
commit db17d2816078b5674db7e40a88a80d602d305c5e
Author: Timothy Meehan <[email protected]>
AuthorDate: Tue Nov 10 10:28:54 2026 +0900
[SPARK-61264][CONNECT][PYTHON] Raise UnicodeDecodeError for a string that
is not valid UTF-8 in collect, in the Python client as PySpark does
### What changes were proposed in this pull request?
[SPARK-61264](https://issues.apache.org/jira/browse/SPARK-61264):
`collect()` of a string that is not valid UTF-8 raises a `PySparkRuntimeError`
("Failed to decode Arrow batch") in the Python client. The reference client
raises the `UnicodeDecodeError` of Python's own decoder for the bytes.
- `crates/spark-connect/src/dataframe.rs`: the normal decode is unchanged
and still validates every batch. Only when arrow-rs fails a batch for its UTF-8
check, `decode_error` decodes the stream again with its string types read as
binary types of the same layout (`binary_schema`, `binary_type`,
`read_strings_as_binary`). The stream is split into its messages as arrow-rs's
stream reader does, and each record batch is read with `read_record_batch` and
the rewritten schema. So arrow-rs s [...]
- `crates/spark-connect-core/src/error.rs`: the new
`SparkErrorKind::UnicodeDecode` (as `RecursionError` is), with
`SparkError::invalid_utf8` and accessors for its column and bytes.
- `crates/pyspark-rs/src/errors.rs`: the Python client raises the error of
`bytes.decode("utf-8")` for the bytes, so the message is Python's own.
`collect`, `first`, `head`, `take` and `toLocalIterator` now raise the same
`UnicodeDecodeError` as PySpark, for a top-level string, a string in an array,
struct or map, and in any column. Nested values are ordered column by column,
then row by row, which matches PySpark for a single invalid value; with several
in one column, the reported one can differ from PySpark's, whose bulk path
converts struct fields field by field.
Out of scope: `toArrow` and `toPandas`, which are unchanged here. PySpark's
`toArrow` does not check the strings: it returns the table with the invalid
bytes. PySpark's `toPandas` raises `pyarrow.lib.ArrowException: Unknown error:
Wrapping � failed`. Here both still raise the `PySparkRuntimeError` of the
Arrow decode.
### Why are the changes needed?
A collected string that is not valid UTF-8 can come from a cast of binary
to string. The Python client raised `PySparkRuntimeError`, which is not a
`ValueError` either, so code that catches `UnicodeDecodeError` or `ValueError`
missed it. The reference client raises `UnicodeDecodeError`.
### Does this PR introduce _any_ user-facing change?
Yes, in the Python client: `collect`, `first`, `head`, `take` and
`toLocalIterator` raise `UnicodeDecodeError` with the message `'utf-8' codec
can't decode byte 0xc3 in position 0: unexpected end of data` for `SELECT
CAST(X'C3' AS STRING)`, instead of `PySparkRuntimeError: Failed to decode Arrow
batch: Invalid argument error: Invalid UTF8 sequence at string index 0 (0..1):
incomplete utf-8 byte sequence from index 0`. Valid strings are unchanged.
In Rust: the collect of such a result returns the new
`SparkErrorKind::UnicodeDecode` (as `RecursionError` is added), whose message
names the column. The enum has one more variant, so exhaustive matches on it
need an arm.
### How was this patch tested?
- Offline: `test_collect_of_a_string_that_is_not_utf8_raises_as_pyspark` in
`python/tests/test_dropin_offline.py`, with a crafted Utf8 column whose bytes
pyarrow does not check: a top-level string, an array of strings, and two
columns in which the first column's invalid value is not in row 0. It asserts
the exception type and the message of Python's decoder for the bytes, and a
valid control.
- Rust: `invalid_utf8_names_the_first_column_with_it_and_its_bytes` in
`nested_decode_tests` (`crates/spark-connect/src/dataframe.rs`): a string in a
list of the second column, and a top-level string in the first, with their
bytes.
- Live: `test_collect_of_a_string_that_is_not_utf8_raises_as_pyspark` in
`python/tests/test_dropin_e2e.py` against OSS Spark 4.3.0, with `CAST(X'C3' AS
STRING)` and the valid `CAST(X'61' AS STRING)`.
- Compared with pyspark-client 4.3.0 on the same server for `collect`,
`first`, `head`, `head(1)`, `take(1)` and `toLocalIterator`, on a top-level
string, a string in an array, in a struct, a map key and a map value, a
second-row string, and two columns: the same exception and message for each.
- Offline Python suites (`tests/test_dropin_offline.py
tests/test_ml_offline.py tests/test_arrow_handoff.py`): 2928 passed, 8 skipped.
- Live Python suites against OSS Spark 4.3.0 (`tests/test_dropin_e2e.py
tests/test_arrow_e2e.py tests/test_ml_e2e.py`): 237 passed, 1 skipped.
- Rust: `cargo test -p apache-spark-connect --release --lib`: 529 passed.
`--no-run`, and `--no-run` with `--features wasm-udf`: pass. `cargo fmt --all
--check`: pass. `cargo clippy --workspace --all-targets --release`: no
diagnostic on a changed line (the diagnostics on master in `pyspark-rs` are
about the size of `SparkError`, and are unchanged).
- Fails without the fix: with the UTF-8 branch disabled, the Rust unit test
gets no column (`None`, expected `Some(1)`), and the offline Python test fails
with `PySparkRuntimeError`.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5 and Claude Haiku 5.5
This pull request and its description were written by Isaac.
Closes #448 from tdcmeehan/SPARK-61264-unicode-decode-error.
Authored-by: Timothy Meehan <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/errors.rs | 17 ++-
crates/spark-connect-core/src/error.rs | 49 +++++++
crates/spark-connect/src/dataframe.rs | 231 ++++++++++++++++++++++++++++++++-
python/tests/test_dropin_e2e.py | 12 ++
python/tests/test_dropin_offline.py | 63 +++++++++
5 files changed, 368 insertions(+), 4 deletions(-)
diff --git a/crates/pyspark-rs/src/errors.rs b/crates/pyspark-rs/src/errors.rs
index 2b780b49..42129246 100644
--- a/crates/pyspark-rs/src/errors.rs
+++ b/crates/pyspark-rs/src/errors.rs
@@ -2,7 +2,7 @@
use pyo3::exceptions;
use pyo3::prelude::*;
-use pyo3::types::{PyDict, PyList};
+use pyo3::types::{PyBytes, PyDict, PyList};
use spark_connect_core::error::{ServerErrorInfo, SparkError, SparkErrorKind};
/// Maps a SparkErrorKind to the corresponding pyspark.errors exception class
name.
@@ -17,6 +17,7 @@ fn kind_to_pyspark_class_name(kind: SparkErrorKind) ->
&'static str {
SparkErrorKind::KeyError => "PySparkKeyError",
SparkErrorKind::RuntimeError => "PySparkRuntimeError",
SparkErrorKind::RecursionError => "RecursionError",
+ SparkErrorKind::UnicodeDecode => "UnicodeDecodeError",
SparkErrorKind::NotImplementedError => "PySparkNotImplementedError",
SparkErrorKind::AssertionError => "PySparkAssertionError",
SparkErrorKind::PicklingError => "PySparkPicklingError",
@@ -185,6 +186,17 @@ fn callback_exception(err: &SparkError) -> Option<PyErr> {
.remove(&id)
}
+/// The UnicodeDecodeError of a string of the result that is not valid UTF-8,
as PySpark raises
+/// it: the error of Python's own decoder of its bytes, so that the message is
the same.
+fn unicode_decode_error(value: &[u8], err: &SparkError) -> PyErr {
+ Python::attach(
+ |py| match PyBytes::new(py, value).call_method1("decode", ("utf-8",)) {
+ Err(exception) => exception,
+ Ok(_) => exceptions::PyRuntimeError::new_err(err.message()),
+ },
+ )
+}
+
/// Maps a SparkError to a Python exception, attempting to raise the correct
typed
/// exception based on the error kind. Falls back to PyRuntimeError if import
fails.
pub fn spark_error_to_py_exception(err: SparkError) -> PyErr {
@@ -195,6 +207,9 @@ pub fn spark_error_to_py_exception(err: SparkError) ->
PyErr {
// A builtin, as PySpark's recursion limit raises it.
return pyo3::exceptions::PyRecursionError::new_err(err.message());
}
+ if let Some(value) = err.invalid_utf8_value() {
+ return unicode_decode_error(&value, &err);
+ }
let msg = err.message();
let operation_id = err.operation_id.clone();
let class_name = kind_to_pyspark_class_name(err.kind);
diff --git a/crates/spark-connect-core/src/error.rs
b/crates/spark-connect-core/src/error.rs
index ebf6baa6..afe560e6 100644
--- a/crates/spark-connect-core/src/error.rs
+++ b/crates/spark-connect-core/src/error.rs
@@ -275,6 +275,8 @@ pub enum SparkErrorKind {
Python,
/// ``RecursionError``, a Python builtin: the executions nested in
callbacks are too deep.
RecursionError,
+ /// ``UnicodeDecodeError``, a Python builtin: a string of the result is
not valid UTF-8.
+ UnicodeDecode,
/// ``pyspark.errors.exceptions.base.SparkRuntimeException``
SparkRuntime,
/// ``pyspark.errors.exceptions.base.SparkUpgradeException``
@@ -291,6 +293,18 @@ pub enum SparkErrorKind {
Spark,
}
+/// The bytes as lowercase hex, to keep them in the string parameters of an
error.
+fn hex_encode(bytes: &[u8]) -> String {
+ bytes.iter().map(|b| format!("{b:02x}")).collect()
+}
+
+fn hex_decode(hex: &str) -> Option<Vec<u8>> {
+ hex.as_bytes()
+ .chunks(2)
+ .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).ok()?,
16).ok())
+ .collect()
+}
+
impl SparkError {
/// Create a ValueError-kind error with an error class and parameters.
pub fn value(error_class: &str, params: &[(&str, &str)]) -> Self {
@@ -353,6 +367,41 @@ impl SparkError {
}
}
+ /// Create an UnicodeDecode-kind error for the string `value` of the
result column `column`,
+ /// which is not valid UTF-8. The bytes are kept, so that the Python
client can raise the error
+ /// of Python's own decoder for them.
+ pub fn invalid_utf8(column: usize, value: &[u8]) -> Self {
+ let mut error = Self::classed(
+ SparkErrorKind::UnicodeDecode,
+ "",
+ &[
+ ("column", &column.to_string()),
+ ("value", &hex_encode(value)),
+ ],
+ );
+ let reason = std::str::from_utf8(value)
+ .err()
+ .map_or_else(String::new, |e| e.to_string());
+ error.message = format!("Invalid UTF-8 in column {column} of the
result: {reason}");
+ error
+ }
+
+ /// The result column of the string of an error from `invalid_utf8`.
+ pub fn utf8_column(&self) -> Option<usize> {
+ if self.kind != SparkErrorKind::UnicodeDecode {
+ return None;
+ }
+ self.params.get("column")?.parse().ok()
+ }
+
+ /// The bytes of the string of an error from `invalid_utf8`.
+ pub fn invalid_utf8_value(&self) -> Option<Vec<u8>> {
+ if self.kind != SparkErrorKind::UnicodeDecode {
+ return None;
+ }
+ hex_decode(self.params.get("value")?)
+ }
+
/// Create an error of a specific kind with an error class and parameters.
pub fn classed(kind: SparkErrorKind, error_class: &str, params: &[(&str,
&str)]) -> Self {
Self {
diff --git a/crates/spark-connect/src/dataframe.rs
b/crates/spark-connect/src/dataframe.rs
index 878ab9f3..57311a97 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -927,6 +927,7 @@ impl DataFrame {
let mut rows = vec![];
let mut schema = None;
let mut info = ExecutionInfo::default();
+ let mut invalid_utf8: Option<SparkError> = None;
loop {
let resp = block_on(stream.message())?;
let Some(mut resp) = resp else {
@@ -939,10 +940,25 @@ impl DataFrame {
if let
Some(proto::execute_plan_response::ResponseType::ArrowBatch(batch)) =
resp.response_type
{
- let batch_rows = decode_arrow_batch_of(&batch,
schema.as_ref())?;
- rows.extend(batch_rows);
+ match decode_arrow_batch_of(&batch, schema.as_ref()) {
+ Ok(batch_rows) => rows.extend(batch_rows),
+ // PySpark converts the result column by column, so the
error is that of the
+ // first column with an invalid string: the rest of the
stream is read for it.
+ Err(error) if error.utf8_column().is_some() => {
+ let first = invalid_utf8
+ .as_ref()
+ .is_some_and(|first| first.utf8_column() <=
error.utf8_column());
+ if !first {
+ invalid_utf8 = Some(error);
+ }
+ }
+ Err(error) => return Err(error),
+ }
}
}
+ if let Some(error) = invalid_utf8 {
+ return Err(error);
+ }
self.record_execution(info);
Ok((rows, schema))
@@ -2625,7 +2641,7 @@ pub(crate) fn decode_arrow_batch_of(
while let Some(record_batch) = reader
.next()
.transpose()
- .map_err(|e| SparkError::connect_msg(format!("Failed to decode Arrow
batch: {}", e)))?
+ .map_err(|e| decode_error(&batch.data, e))?
{
let schema = record_batch.schema();
let num_rows = record_batch.num_rows();
@@ -2664,6 +2680,163 @@ pub(crate) fn decode_arrow_batch_of(
Ok(rows)
}
+/// The error of an Arrow IPC stream `data` that arrow-rs fails with `error`.
A string that is not
+/// valid UTF-8 is an error of its own, with its bytes, which the Python
client raises as the
+/// reference client does.
+fn decode_error(data: &[u8], error: arrow::error::ArrowError) -> SparkError {
+ let message = error.to_string();
+ if message.contains("UTF8 sequence") || message.contains("utf-8 byte
sequence") {
+ if let Some((column, value)) = first_invalid_utf8(data) {
+ return SparkError::invalid_utf8(column, &value);
+ }
+ }
+ SparkError::connect_msg(format!("Failed to decode Arrow batch: {}", error))
+}
+
+/// The first string of the Arrow IPC stream `data` that is not valid UTF-8,
with its column and
+/// its bytes, in the order in which PySpark converts a result: column by
column, then row by row.
+fn first_invalid_utf8(data: &[u8]) -> Option<(usize, Vec<u8>)> {
+ let batches = read_strings_as_binary(data)?;
+ let columns = batches.first()?.num_columns();
+ (0..columns).find_map(|column| {
+ batches.iter().find_map(|batch| {
+ (0..batch.num_rows()).find_map(|row| {
+ invalid_utf8_in(batch.column(column).as_ref(),
row).map(|value| (column, value))
+ })
+ })
+ })
+}
+
+/// The record batches of the Arrow IPC stream `data`, with its string types
read as binary types
+/// of the same layout. arrow-rs still checks the offsets and lengths of these
batches, but not
+/// their UTF-8. The messages are split here because arrow-rs's stream reader
cannot take a schema
+/// of its own. None for a stream with a message that is not a schema or a
record batch, such as a
+/// dictionary, or one that does not read.
+fn read_strings_as_binary(data: &[u8]) ->
Option<Vec<arrow::record_batch::RecordBatch>> {
+ use arrow::buffer::Buffer;
+ use arrow::ipc::convert::fb_to_schema;
+ use arrow::ipc::reader::read_record_batch;
+ use arrow::ipc::{root_as_message, MessageHeader};
+ use std::collections::HashMap;
+
+ fn take<'a>(rest: &mut &'a [u8], len: usize) -> Option<&'a [u8]> {
+ let (head, tail) = rest.split_at_checked(len)?;
+ *rest = tail;
+ Some(head)
+ }
+
+ let mut rest = data;
+ let mut schema = None;
+ let mut batches = vec![];
+ loop {
+ let mut prefix = take(&mut rest, 4)?;
+ if prefix == [0xff; 4] {
+ prefix = take(&mut rest, 4)?;
+ }
+ let meta_len = u32::from_le_bytes(prefix.try_into().ok()?) as usize;
+ if meta_len == 0 {
+ break;
+ }
+ let message = root_as_message(take(&mut rest, meta_len)?).ok()?;
+ let body = take(&mut rest,
usize::try_from(message.bodyLength()).ok()?)?;
+ match message.header_type() {
+ MessageHeader::Schema => {
+ let fields = fb_to_schema(message.header_as_schema()?);
+ schema = Some(Arc::new(binary_schema(&fields)));
+ }
+ MessageHeader::RecordBatch => {
+ let batch = read_record_batch(
+ &Buffer::from(body.to_vec()),
+ message.header_as_record_batch()?,
+ schema.clone()?,
+ &HashMap::new(),
+ None,
+ &message.version(),
+ )
+ .ok()?;
+ batches.push(batch);
+ }
+ _ => return None,
+ }
+ }
+ Some(batches)
+}
+
+/// The schema `schema`, with each string type of it, at any depth, as the
binary type of the same
+/// layout: Utf8 as Binary, LargeUtf8 as LargeBinary and Utf8View as
BinaryView.
+fn binary_schema(schema: &arrow::datatypes::Schema) ->
arrow::datatypes::Schema {
+ let fields: Vec<arrow::datatypes::Field> = schema
+ .fields()
+ .iter()
+ .map(|field| binary_field(field))
+ .collect();
+ arrow::datatypes::Schema::new_with_metadata(fields,
schema.metadata().clone())
+}
+
+fn binary_field(field: &arrow::datatypes::Field) -> arrow::datatypes::Field {
+ field.clone().with_data_type(binary_type(field.data_type()))
+}
+
+fn binary_type(data_type: &arrow::datatypes::DataType) ->
arrow::datatypes::DataType {
+ use arrow::datatypes::DataType as ArrowDataType;
+
+ match data_type {
+ ArrowDataType::Utf8 => ArrowDataType::Binary,
+ ArrowDataType::LargeUtf8 => ArrowDataType::LargeBinary,
+ ArrowDataType::Utf8View => ArrowDataType::BinaryView,
+ ArrowDataType::List(field) =>
ArrowDataType::List(Arc::new(binary_field(field))),
+ ArrowDataType::LargeList(field) =>
ArrowDataType::LargeList(Arc::new(binary_field(field))),
+ ArrowDataType::FixedSizeList(field, size) => {
+ ArrowDataType::FixedSizeList(Arc::new(binary_field(field)), *size)
+ }
+ ArrowDataType::Map(field, sorted) => {
+ ArrowDataType::Map(Arc::new(binary_field(field)), *sorted)
+ }
+ ArrowDataType::Struct(fields) => ArrowDataType::Struct(
+ fields
+ .iter()
+ .map(|field| Arc::new(binary_field(field)))
+ .collect(),
+ ),
+ other => other.clone(),
+ }
+}
+
+/// The bytes of the binary value of `array` at `row`, if they are not valid
UTF-8. A value nested
+/// in the row of a list, struct or map is searched in the order of its
elements, and a null is
+/// valid.
+fn invalid_utf8_in(array: &dyn arrow::array::Array, row: usize) ->
Option<Vec<u8>> {
+ use arrow::array::{Array, AsArray};
+ use arrow::datatypes::DataType as ArrowDataType;
+
+ if array.is_null(row) {
+ return None;
+ }
+ let first_in = |values: &dyn Array| (0..values.len()).find_map(|i|
invalid_utf8_in(values, i));
+ match array.data_type() {
+ ArrowDataType::Binary =>
invalid_bytes(array.as_binary::<i32>().value(row)),
+ ArrowDataType::LargeBinary =>
invalid_bytes(array.as_binary::<i64>().value(row)),
+ ArrowDataType::BinaryView =>
invalid_bytes(array.as_binary_view().value(row)),
+ ArrowDataType::List(_) =>
first_in(array.as_list::<i32>().value(row).as_ref()),
+ ArrowDataType::LargeList(_) =>
first_in(array.as_list::<i64>().value(row).as_ref()),
+ ArrowDataType::FixedSizeList(_, _) => {
+ first_in(array.as_fixed_size_list().value(row).as_ref())
+ }
+ ArrowDataType::Map(_, _) => first_in(&array.as_map().value(row)),
+ ArrowDataType::Struct(_) => array
+ .as_struct()
+ .columns()
+ .iter()
+ .find_map(|column| invalid_utf8_in(column.as_ref(), row)),
+ _ => None,
+ }
+}
+
+/// The bytes, if they are not valid UTF-8.
+fn invalid_bytes(bytes: &[u8]) -> Option<Vec<u8>> {
+ std::str::from_utf8(bytes).is_err().then(|| bytes.to_vec())
+}
+
/// Decode Arrow IPC stream into RecordBatches without converting to Rows.
///
/// Used by `collect_record_batches()` to provide raw Arrow data for
conversions
@@ -3483,6 +3656,58 @@ mod nested_decode_tests {
}
}
+ #[test]
+ fn invalid_utf8_names_the_first_column_with_it_and_its_bytes() {
+ // The marker is one of the encoded strings; its bytes are replaced by
bytes that are not
+ // UTF-8, of the same length, so that the stream is only invalid in
its values.
+ let marker = "\u{1f}\u{1e}";
+ let corrupt = |mut batch: proto::execute_plan_response::ArrowBatch| {
+ let mut data = batch.data.to_vec();
+ let at = data
+ .windows(marker.len())
+ .position(|window| window == marker.as_bytes())
+ .unwrap();
+ data[at..at + 2].copy_from_slice(&[0xc3, 0x28]);
+ batch.data = data.into();
+ batch
+ };
+ let nested = |values: Vec<&str>| {
+ let items = StringArray::from(values);
+ let offsets = OffsetBuffer::from_lengths([1, 1]);
+ let field = Arc::new(Field::new("item", DataType::Utf8, true));
+ Arc::new(ListArray::new(field, offsets, Arc::new(items), None)) as
ArrayRef
+ };
+ let strings = |values: Vec<&str>| Arc::new(StringArray::from(values))
as ArrayRef;
+
+ let nested_batch = corrupt(encoded_batches(
+ vec![
+ ("a", strings(vec!["x", "y"])),
+ ("n", nested(vec!["x", marker])),
+ ],
+ 1,
+ false,
+ ));
+ let Err(error) = decode_arrow_batch_of(&nested_batch, None) else {
+ panic!("the invalid string of the list must not decode");
+ };
+ assert_eq!(error.utf8_column(), Some(1));
+ assert_eq!(error.invalid_utf8_value(), Some(vec![0xc3, 0x28]));
+
+ let top_batch = corrupt(encoded_batches(
+ vec![
+ ("a", strings(vec!["x", marker])),
+ ("n", nested(vec!["x", "y"])),
+ ],
+ 1,
+ false,
+ ));
+ let Err(error) = decode_arrow_batch_of(&top_batch, None) else {
+ panic!("the invalid string of the first column must not decode");
+ };
+ assert_eq!(error.utf8_column(), Some(0));
+ assert_eq!(error.invalid_utf8_value(), Some(vec![0xc3, 0x28]));
+ }
+
#[test]
fn
unsupported_children_remain_lazy_under_nulls_empty_containers_and_variants() {
let null_duration = DurationSecondArray::from(vec![None]);
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index e51173ec..7a5f3b97 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -2134,6 +2134,18 @@ def
test_collected_rows_take_the_names_of_the_schema_of_the_result_as_pyspark(se
assert e.value.getCondition() ==
"UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION"
assert e.value.getMessageParameters() == {"data_type":
"month_day_nano_interval"}
+
+def test_collect_of_a_string_that_is_not_utf8_raises_as_pyspark(session):
+ # As PySpark's: the bytes of the string are not UTF-8, and collect raises
the UnicodeDecodeError
+ # of Python's decoder for them, while a valid string of the same query
collects.
+ with pytest.raises(UnicodeDecodeError) as e:
+ session.sql("SELECT CAST(X'C3' AS STRING) AS s").collect()
+ assert type(e.value) is UnicodeDecodeError
+ assert str(e.value) == (
+ "'utf-8' codec can't decode byte 0xc3 in position 0: unexpected end of
data")
+ assert session.sql("SELECT CAST(X'61' AS STRING) AS s").collect() ==
[Row(s="a")]
+
+
def test_collect_reads_a_result_across_stream_ends(session):
# Takes several response streams when the server's senderMaxStreamSize is
small.
n = 300_000
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 7285dd48..eba47053 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -1070,6 +1070,69 @@ def
test_collected_rows_take_the_names_of_the_schema_of_the_result_as_pyspark(mo
spark.range(1).collect()
assert e.value.getCondition() ==
"UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION"
assert e.value.getMessageParameters() == {"data_type":
"month_day_nano_interval"}
+
+
+def test_collect_of_a_string_that_is_not_utf8_raises_as_pyspark(mock_connect):
+ # As PySpark's: a result is converted column by column, so the first
invalid string of the
+ # first column raises the UnicodeDecodeError of Python's decoder, whether
it is a top-level
+ # string or nested in an array.
+ import pyarrow as pa
+ from _mock_connect_server import data_type_proto
+
+ spark, service = mock_connect
+
+ def strings(*values):
+ # The bytes of the values as a string array: pyarrow does not check
that they are UTF-8.
+ offsets, total = [0], 0
+ for value in values:
+ total += len(value)
+ offsets.append(total)
+ return pa.Array.from_buffers(pa.string(), len(values), [
+ None, pa.array(offsets, pa.int32()).buffers()[1],
+ pa.py_buffer(b"".join(values))])
+
+ def respond(schema, table):
+ sink = pa.BufferOutputStream()
+ with pa.ipc.new_stream(sink, table.schema) as writer:
+ writer.write_table(table)
+ # ExecutePlanResponse.schema=7 and arrow_batch=2:
ArrowBatch.row_count=1, data=2.
+ service.execute_payload = message_field(7, schema) + message_field(
+ 2, varint_field(1, table.num_rows) + message_field(2,
sink.getvalue().to_pybytes()))
+
+ def python_error(value):
+ with pytest.raises(UnicodeDecodeError) as e:
+ value.decode("utf-8")
+ return e.value
+
+ def string_field(name):
+ return {"name": name, "type": "string", "nullable": True, "metadata":
{}}
+
+ respond(data_type_proto({"type": "struct", "fields": [string_field("s")]}),
+ pa.table({"s": strings(b"a", b"\xc3")}))
+ with pytest.raises(UnicodeDecodeError) as e:
+ spark.range(1).collect()
+ assert type(e.value) is UnicodeDecodeError
+ assert str(e.value) == str(python_error(b"\xc3"))
+
+ respond(data_type_proto({"type": "struct", "fields": [{
+ "name": "a", "type": {"type": "array", "elementType": "string",
"containsNull": True},
+ "nullable": True, "metadata": {}}]}),
+ pa.table({"a": pa.ListArray.from_arrays([0, 1, 2], strings(b"a",
b"\xc3"))}))
+ with pytest.raises(UnicodeDecodeError) as e:
+ spark.range(1).collect()
+ assert str(e.value) == str(python_error(b"\xc3"))
+
+ # Row 0 of column b is invalid too, but PySpark raises for the first
column, at its row 1.
+ respond(data_type_proto({"type": "struct", "fields": [
+ string_field("a"), string_field("b")]}),
+ pa.table({"a": strings(b"a", b"\xc3"), "b": strings(b"\xc4", b"b")}))
+ with pytest.raises(UnicodeDecodeError) as e:
+ spark.range(1).collect()
+ assert str(e.value) == str(python_error(b"\xc3"))
+
+ respond(data_type_proto({"type": "struct", "fields": [string_field("s")]}),
+ pa.table({"s": strings(b"a")}))
+ assert spark.range(1).collect() == [Row(s="a")]
assert len(list(spark.range(1).toLocalIterator())) == 1
def test_tags_are_those_of_each_thread_as_pyspark(mock_connect):
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]