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 5bf85a60 [SPARK-61483][CONNECT][PYTHON][FOLLOWUP] Read the value of an
array, and take an int, as PyArrow does in createDataFrame in the Python client
5bf85a60 is described below
commit 5bf85a60f6cd5b0a2512f193516d3c574b8a76f3
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 15:47:25 2026 +0900
[SPARK-61483][CONNECT][PYTHON][FOLLOWUP] Read the value of an array, and
take an int, as PyArrow does in createDataFrame in the Python client
### What changes were proposed in this pull request?
A follow-up of #538 (SPARK-61483), from a review of it. Both changes are in
`crates/pyspark-rs/src/infer.rs`, the conversion of the local rows of
`createDataFrame` in the Python client.
1. **The value of an array, as PyArrow reads it.** This is about an array
column whose elements need no converter (an array of numbers, bools, dates,
times or day-time intervals). PySpark passes such a value to PyArrow as it is.
#538 added `is_arrow_list`, which took a value as PyArrow's list converter
does, but then iterated it. PyArrow does not iterate a sequence: it reads it by
its length and its items. The new `arrow_list` reads the value as PyArrow does:
- A NumPy array that is not one-dimensional raises PyArrow's
`ArrowInvalid` "Can only convert 1-dimensional array values of list<element:
int32> to a variable-sized list", with the Arrow type of the column.
- A list or a tuple is read as it is stored, also when it is of a
subclass that overrides `__iter__` or `__getitem__`.
- Another sequence (`PySequence_Check`), such as a range or a NumPy
array, is read with `PySequence_Size`, then `PySequence_GetItem` of each index.
Their errors are raised as PyArrow raises them: "object of type 'X' has no
len()" for a `__getitem__` without a `__len__`, and the `IndexError` of the
first index past the items for a `__len__` that is longer than them. A shorter
`__len__` ends the list there.
- A set and a `dict_values` are still iterated. Any other value is still
"not a sequence".
As before, these errors wait for the converters of the other columns,
and the first one in the order of the columns, then of the rows, is raised.
2. **An int by the `nb_int` slot, as PyArrow takes it.** `py_int`, which
takes an int for an int, date, time or day-time interval value that PySpark
passes to PyArrow, checked for an `__int__` attribute on the type. PyArrow's
`PyObjectToPyInt` calls the type's `nb_int` slot. A NumPy `str_` or `bytes_`
has no `nb_int`, but its type has the `__int__` of `numpy.generic`. So
`np.str_("1")` was taken as the int 1, where PyArrow raises. `py_int` now reads
the slot with `PyType_GetSlot`. Pyt [...]
### Why are the changes needed?
To match PySpark 4.3.0. Probes with the Connect client of official PySpark
4.3.0 and with this client, against a local Spark 4.3.0 server.
`GetOnly` has only a `__getitem__`. `LongLen` and `ShortLen` add a
`__len__` that is 3 longer than the items, and one that is 1. `OwnIter` has a
`__len__`, and an `__iter__` that gives 9s. The `list` and `tuple` subclasses
also override `__iter__` (9s) and `__getitem__` (8):
| Value in an `array<int>` column | PySpark 4.3.0 | Before |
|---|---|---|
| `GetOnly([1, 2])` | `TypeError: object of type 'GetOnly' has no len()` |
`[1, 2]` |
| `LongLen([1, 2])` | `IndexError: list index out of range` | `[1, 2]` |
| `ShortLen([1, 2])` | `[1]` | `[1, 2]` |
| `OwnIter([1, 2])` | `[1, 2]` | `[9, 9]` |
| a `list` subclass of `[1, 2]` | `[1, 2]` | `[9, 9]` |
| a `tuple` subclass of `(1, 2)` | `[1, 2]` | `[9, 9]` |
| `np.array([[1, 2], [3, 4]])` | `ArrowInvalid: Can only convert
1-dimensional array values of list<element: int32> to a variable-sized list` |
`ArrowInvalid: Could not convert array([1, 2]) with type numpy.ndarray: tried
to convert to int32` |
| `np.zeros((0, 2))` | the same `ArrowInvalid` | `[]` |
| `np.array(5)` | the same `ArrowInvalid` | `ArrowTypeError: ... was not a
sequence or recognized null for conversion to list type` |
| `np.array([[1, 2]])` in an `array<array<int>>` column | `ArrowInvalid` of
`list<element: list<element: int32>>` | `[[1, 2]]` |
| `GetOnly([1])`, then `["x"]` in the next row | `TypeError: object of type
'GetOnly' has no len()` | `ArrowInvalid: Could not convert 'x' with type str:
tried to convert to int32` |
| `np.array(["1", "2"])` | `ArrowInvalid: Could not convert np.str_('1')
with type numpy.str_: tried to convert to int32` | `[1, 2]` |
| Value, column | PySpark 4.3.0 | Before |
|---|---|---|
| `np.str_("1")`, `int` | `ArrowInvalid: Could not convert np.str_('1')
with type numpy.str_: tried to convert to int32` | `1` |
| `np.bytes_(b"1")`, `bigint` | `ArrowInvalid: ... tried to convert to
int64` | `1` |
| `np.str_("1")`, `date` | `ArrowTypeError: object of type <class
'numpy.str_'> cannot be converted to int` | `1970-01-02` |
| `np.bytes_(b"1")`, `time` | `ArrowTypeError: object of type <class
'numpy.bytes_'> cannot be converted to int` | sent to the server |
After the change, this client gives PySpark's result in each of these
cases. One difference remains, for a `__len__` that raises: PyArrow 26 loses
that error, and PySpark raises `SystemError: <class 'ValueError'> returned a
result with an exception set`. This client raises the error of `__len__`.
### Does this PR introduce _any_ user-facing change?
Yes, on unreleased changes. In the Python client's `createDataFrame` of
local rows, an array value is read as PyArrow reads it, and a NumPy `str_` or
`bytes_` in an int, date or time column raises PyArrow's error. The table above
shows each case.
### How was this patch tested?
-
`test_an_array_of_no_converter_reads_a_sequence_by_its_length_and_items_as_pyarrow`
in `python/tests/test_dropin_offline.py`, new. It covers the read values of
the sequences above and their errors, the order of these errors against a
converter's error and against an element's error, and the NumPy arrays that are
not one-dimensional, for several element types and a nested array.
- `test_values_of_local_rows_convert_and_raise_as_pyarrow`, which now has
the NumPy `str_` and `bytes_` cases.
- Both fail on an extension built from master and pass with the change.
Every expected value and message was checked with official PySpark 4.3.0.
- The offline drop-in and ML suites (`tests/test_dropin_offline.py
tests/test_ml_offline.py`), `cargo build -p pyspark-rs --release`, `cargo fmt
--all -- --check`, `ruff check` and `ruff format --check`, and
`scripts/audit_no_stubs.sh`.
### 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 #546 from HyukjinKwon/SPARK-61483-followup-arrow-list.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/infer.rs | 190 +++++++++++++++++++++++++++++-------
python/tests/test_dropin_offline.py | 96 +++++++++++++++++-
2 files changed, 249 insertions(+), 37 deletions(-)
diff --git a/crates/pyspark-rs/src/infer.rs b/crates/pyspark-rs/src/infer.rs
index 2cb66078..5923f979 100644
--- a/crates/pyspark-rs/src/infer.rs
+++ b/crates/pyspark-rs/src/infer.rs
@@ -982,9 +982,10 @@ fn arrow_invalid(obj: &Bound<'_, PyAny>, arrow_type: &str)
-> PyResult<PyErr> {
}
/// `obj` as an int, as PyArrow's `PyObjectToPyInt` takes it: by `__index__`,
else by the
-/// `__int__` of its type, which may raise, such as for a NaN; else the
`ArrowTypeError` "object
-/// of type <class 'T'> cannot be converted to int". A float, a `Decimal` and
a NumPy number or
-/// bool are taken by their `__int__`.
+/// `nb_int` slot of its type, which may raise, such as for a NaN; else the
`ArrowTypeError`
+/// "object of type <class 'T'> cannot be converted to int". A float, a
`Decimal` and a NumPy
+/// number or bool are taken by their `nb_int`. A NumPy `str_` or `bytes_` has
none, although
+/// its type has the `__int__` of `numpy.generic`.
fn py_int<'py>(obj: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> {
let py = obj.py();
// SAFETY: PyNumber_Index returns a new reference, or NULL with an
exception set.
@@ -994,7 +995,20 @@ fn py_int<'py>(obj: &Bound<'py, PyAny>) ->
PyResult<Bound<'py, PyAny>> {
return Ok(index);
}
let ty = obj.get_type();
- if ty.hasattr(intern!(py, "__int__"))? {
+ // SAFETY: `ty` is a live type object. PyType_GetSlot gives NULL for a
slot that is not set,
+ // and, before Python 3.10, which reads the slots of heap types only, also
with an exception
+ // set for a static type.
+ let slot = unsafe { pyo3::ffi::PyType_GetSlot(ty.as_type_ptr(),
pyo3::ffi::Py_nb_int) };
+ if !slot.is_null() {
+ // SAFETY: the nb_int slot is a unaryfunc, which returns a new
reference, or NULL with
+ // an exception set.
+ return unsafe {
+ let nb_int = std::mem::transmute::<*mut std::ffi::c_void,
pyo3::ffi::unaryfunc>(slot);
+ Bound::from_owned_ptr_or_err(py, nb_int(obj.as_ptr()))
+ };
+ }
+ // On Python 3.9, the `__int__` of a static type, which wraps its nb_int,
stands for it.
+ if PyErr::take(py).is_some() && ty.hasattr(intern!(py, "__int__"))? {
return ty.getattr(intern!(py, "__int__"))?.call1((obj,));
}
Err(pyarrow_error(
@@ -1199,16 +1213,137 @@ pub(crate) fn bytes_of(obj: &Bound<'_, PyAny>) ->
PyResult<Option<Vec<u8>>> {
}
}
-/// Whether PyArrow's list converter takes `obj` as the value of a list: a
sequence by
-/// `PySequence_Check`, such as a tuple, a range or a NumPy array, which a
dict is not, a set or
-/// a `dict_values`. Another iterable, such as an iterator, a generator, a
frozenset, a
-/// `dict_keys` or a `dict_items`, is "not a sequence" to it.
-fn is_arrow_list(obj: &Bound<'_, PyAny>) -> bool {
+/// A value of an array whose elements need no converter, which PySpark passes
to PyArrow as
+/// it is, as PyArrow's list converter reads it:
+/// - A NumPy array that is not one-dimensional is the `ArrowInvalid` "Can
only convert
+/// 1-dimensional array values".
+/// - A list or a tuple is read as it is stored, also of a subclass that
overrides `__iter__`
+/// or `__getitem__`.
+/// - Another sequence by `PySequence_Check`, such as a range or a NumPy
array, is read by
+/// `PySequence_Size` and then `PySequence_GetItem` of each index, whose
errors PyArrow raises:
+/// a `__getitem__` without a `__len__` "has no len()", and a `__len__`
longer than the items
+/// gives the `IndexError` of the first index past them. A shorter one ends
the list there.
+/// - A set and a `dict_values` are iterated.
+/// - Any other value, a dict too, is "not a sequence": an iterator, a
generator, a frozenset,
+/// a `dict_keys` or a `dict_items`.
+///
+/// Its errors, as those of its elements, wait for the converters of the other
columns.
+fn arrow_list(
+ obj: &Bound<'_, PyAny>,
+ dt: &DataType,
+ element_type: &DataType,
+ contains_null: bool,
+ late: &mut Late,
+) -> PyResult<Value> {
+ let py = obj.py();
+ let mut items = Vec::new();
+ if numpy_array_dimensions(obj)?.is_some_and(|dimensions| dimensions != 1) {
+ let message = match arrow_type_text(dt) {
+ Some(list) => format!(
+ "Can only convert 1-dimensional array values of {list} to a
variable-sized list"
+ ),
+ // A type that PyArrow has none of, which `arrow_schema_error`
raises first.
+ None => "Can only convert 1-dimensional array values".to_string(),
+ };
+ return Ok(late.defer(|| Err(pyarrow_error(py, "ArrowInvalid",
message)?)));
+ }
// SAFETY: `obj` is a live object, and PySequence_Check always succeeds
without calling
// into Python.
- (unsafe { pyo3::ffi::PySequence_Check(obj.as_ptr()) } == 1)
- || obj.is_instance_of::<PySet>()
- || obj.is_instance_of::<PyDictValues>()
+ let is_sequence = unsafe { pyo3::ffi::PySequence_Check(obj.as_ptr()) } ==
1;
+ if let Ok(list) = obj.cast::<PyList>() {
+ for item in list.iter() {
+ items.push(convert(&item, element_type, contains_null, late)?);
+ }
+ } else if let Ok(tuple) = obj.cast::<PyTuple>() {
+ for item in tuple.iter() {
+ items.push(convert(&item, element_type, contains_null, late)?);
+ }
+ } else if is_sequence {
+ // SAFETY: `obj` is a live object. PySequence_Size returns -1 with an
exception set
+ // when it fails.
+ let len = unsafe { pyo3::ffi::PySequence_Size(obj.as_ptr()) };
+ if len < 0 {
+ let err = PyErr::fetch(py);
+ return Ok(late.defer(|| Err(err)));
+ }
+ // The length is the object's own, so it reserves nothing: a wrong one
is read up to
+ // the first index that fails.
+ for index in 0..len {
+ // SAFETY: PySequence_GetItem returns a new reference, or NULL
with an exception
+ // set.
+ let item = unsafe {
+ Bound::from_owned_ptr_or_err(py,
pyo3::ffi::PySequence_GetItem(obj.as_ptr(), index))
+ };
+ match item {
+ Ok(item) => items.push(convert(&item, element_type,
contains_null, late)?),
+ Err(err) => return Ok(late.defer(|| Err(err))),
+ }
+ }
+ } else if obj.is_instance_of::<PySet>() ||
obj.is_instance_of::<PyDictValues>() {
+ for item in obj.try_iter()? {
+ items.push(convert(&item?, element_type, contains_null, late)?);
+ }
+ } else {
+ return Ok(late.defer(|| {
+ Err(pyarrow_error(
+ py,
+ "ArrowTypeError",
+ format!(
+ "Could not convert {} with type {}: was not a sequence or
recognized null \
+ for conversion to list type",
+ obj.repr()?,
+ arrow_type_name(obj)?
+ ),
+ )?)
+ }));
+ }
+ Ok(Value::List(items))
+}
+
+/// The number of dimensions of `obj` if it is a NumPy array. NumPy is not
imported when it is
+/// not loaded, as such a value can only exist once it was.
+fn numpy_array_dimensions(obj: &Bound<'_, PyAny>) -> PyResult<Option<usize>> {
+ let py = obj.py();
+ let modules = py
+ .import(intern!(py, "sys"))?
+ .getattr(intern!(py, "modules"))?;
+ match modules.cast::<PyDict>()?.get_item(intern!(py, "numpy"))? {
+ Some(numpy) if !numpy.is_none() => {
+ if obj.is_instance(&numpy.getattr(intern!(py, "ndarray"))?)? {
+ Ok(Some(obj.getattr(intern!(py, "ndim"))?.extract()?))
+ } else {
+ Ok(None)
+ }
+ }
+ _ => Ok(None),
+ }
+}
+
+/// The Arrow type of `dt` as PyArrow writes it, for the types that PySpark
has no converter
+/// of, whose values PyArrow takes as they are (`arrow_list`). `None` for a
type that PySpark's
+/// `to_arrow_type` has no Arrow type of, such as a char or a year-month
interval.
+fn arrow_type_text(dt: &DataType) -> Option<String> {
+ Some(match dt {
+ DataType::Boolean => "bool".to_string(),
+ DataType::Byte => "int8".to_string(),
+ DataType::Short => "int16".to_string(),
+ DataType::Integer => "int32".to_string(),
+ DataType::Long => "int64".to_string(),
+ DataType::Float => "float".to_string(),
+ DataType::Double => "double".to_string(),
+ DataType::Date => "date32[day]".to_string(),
+ DataType::DayTimeInterval { .. } => "duration[us]".to_string(),
+ DataType::Time { .. } => "time64[ns]".to_string(),
+ DataType::Array {
+ element_type,
+ contains_null,
+ } => format!(
+ "list<element: {}{}>",
+ arrow_type_text(element_type)?,
+ if *contains_null { "" } else { " not null" }
+ ),
+ _ => return None,
+ })
}
/// A field value of `dt` from `obj`, as PySpark's converters and then PyArrow
convert it.
@@ -1242,28 +1377,15 @@ pub(crate) fn convert(
contains_null,
} => {
// As PySpark: an array whose elements need a converter takes a
list or an
- // array.array, and another array is taken as it is, by PyArrow,
which takes a
- // sequence, such as a tuple or a NumPy array of numbers or bools,
a set or a
- // dict_values (`is_arrow_list`).
- if needs_converter(dt, nullable) {
- if !obj.is_instance_of::<PyList>()
- && !obj.is_instance(ARRAY.import(py, "array",
"array")?.as_any())?
- {
- return Err(assertion());
- }
- } else if !is_arrow_list(obj) || obj.try_iter().is_err() {
- return Ok(late.defer(|| {
- Err(pyarrow_error(
- py,
- "ArrowTypeError",
- format!(
- "Could not convert {} with type {}: was not a
sequence or \
- recognized null for conversion to list type",
- obj.repr()?,
- arrow_type_name(obj)?
- ),
- )?)
- }));
+ // array.array, which the converter iterates, and another array is
taken as it is,
+ // by PyArrow (`arrow_list`).
+ if !needs_converter(dt, nullable) {
+ return arrow_list(obj, dt, element_type, *contains_null, late);
+ }
+ if !obj.is_instance_of::<PyList>()
+ && !obj.is_instance(ARRAY.import(py, "array",
"array")?.as_any())?
+ {
+ return Err(assertion());
}
let mut items = Vec::with_capacity(obj.len().unwrap_or(0));
for item in obj.try_iter()? {
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 3cf52d6d..d85e08a4 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -15586,9 +15586,10 @@ def
test_ints_of_date_fields_convert_as_pyarrow(mock_connect):
def test_values_of_local_rows_convert_and_raise_as_pyarrow(mock_connect):
# As PySpark Connect's, which passes these values to PyArrow as they are:
an int, date,
- # day-time interval and time field takes the __index__, else the __int__,
of a value, such
- # as a Decimal, and the errors are PyArrow's. A char or varchar field
raises the error of
- # PySpark's to_arrow_schema.
+ # day-time interval and time field takes the __index__, else the nb_int
slot of the type, of
+ # a value, such as a Decimal, and the errors are PyArrow's. A NumPy str_
or bytes_ has no
+ # nb_int, although its type has the __int__ of numpy.generic. A char or
varchar field
+ # raises the error of PySpark's to_arrow_schema.
import re
import pyarrow as pa
@@ -15622,6 +15623,15 @@ def
test_values_of_local_rows_convert_and_raise_as_pyarrow(mock_connect):
"Expected np.timedelta64 but got: duration[ns]"),
("x", "boolean", pa.ArrowInvalid,
"Could not convert 'x' with type str: tried to convert to boolean"),
+ (np.str_("1"), "int", pa.ArrowInvalid,
+ f"Could not convert {np.str_('1')!r} with type numpy.str_: tried to
convert to int32"),
+ (np.bytes_(b"1"), "bigint", pa.ArrowInvalid,
+ f"Could not convert {np.bytes_(b'1')!r} with type numpy.bytes_: tried
to convert to "
+ "int64"),
+ (np.str_("1"), "date", pa.ArrowTypeError,
+ "object of type <class 'numpy.str_'> cannot be converted to int"),
+ (np.bytes_(b"1"), "time", pa.ArrowTypeError,
+ "object of type <class 'numpy.bytes_'> cannot be converted to int"),
]:
with pytest.raises(error, match="^" + re.escape(message) + "$") as e:
spark.createDataFrame([(value,)], f"v {ddl}")
@@ -15763,6 +15773,86 @@ def
test_an_array_of_no_converter_takes_the_values_that_pyarrow_takes_as_pyspark
assert table.column(0).to_pylist() == [[0, 1], [1, 2], [2], [3]]
+def
test_an_array_of_no_converter_reads_a_sequence_by_its_length_and_items_as_pyarrow(
+ mock_connect,
+):
+ # As PyArrow's list conversion of a value that PySpark passes as it is: a
list or a tuple
+ # is read as it is stored, another sequence by its length and the item at
each index, and
+ # a NumPy array has to be one-dimensional. Its errors wait for the
converters of the other
+ # columns, and the first one in the order of the columns and then the rows
is raised.
+ import pyarrow as pa
+
+ spark, service = mock_connect
+
+ class GetOnly:
+ def __init__(self, values):
+ self.values = values
+
+ def __getitem__(self, index):
+ return self.values[index]
+
+ class LongLen(GetOnly):
+ def __len__(self):
+ return len(self.values) + 3
+
+ class ShortLen(GetOnly):
+ def __len__(self):
+ return 1
+
+ class OwnIter(GetOnly):
+ def __len__(self):
+ return len(self.values)
+
+ def __iter__(self):
+ return iter([9] * len(self.values))
+
+ class List(list):
+ def __iter__(self):
+ return iter([9] * len(self))
+
+ def __getitem__(self, index):
+ return 8
+
+ class Tuple(tuple):
+ def __iter__(self):
+ return iter([9] * len(self))
+
+ def __getitem__(self, index):
+ return 8
+
+ table, _ = _local_rows_relation_of(service, spark.createDataFrame(
+ [(ShortLen([5, 6]),), (OwnIter([1, 2]),), (List([3, 4]),),
(Tuple((5,)),),
+ (np.array([6, 7]),)], "a array<int>"))
+ assert table.column(0).to_pylist() == [[5], [1, 2], [3, 4], [5], [6, 7]]
+
+ with pytest.raises(TypeError, match=r"^object of type 'GetOnly' has no
len\(\)$"):
+ spark.createDataFrame([(GetOnly([1, 2]),)], "a array<int>")
+ with pytest.raises(IndexError, match="^list index out of range$"):
+ spark.createDataFrame([(LongLen([1, 2]),)], "a array<int>")
+ for value in (GetOnly([1]), LongLen([1])):
+ with pytest.raises(AssertionError):
+ spark.createDataFrame([(value, 0)], "a array<int>, b timestamp")
+ with pytest.raises(TypeError, match="has no len"):
+ spark.createDataFrame([(GetOnly([1]),), (["x"],)], "a array<int>")
+ for rows in ([(["x"],), (GetOnly([1]),)], [(LongLen(["x", 2]),)]):
+ with pytest.raises(pa.ArrowInvalid, match="^Could not convert 'x' with
type str"):
+ spark.createDataFrame(rows, "a array<int>")
+
+ for value, schema, arrow_type in [
+ (np.array([[1, 2], [3, 4]]), "a array<int>", "list<element: int32>"),
+ (np.array(5), "a array<double>", "list<element: double>"),
+ (np.zeros((0, 2)), "a array<date>", "list<element: date32[day]>"),
+ (np.array([[1, 2]]), "a array<array<bigint>>", "list<element:
list<element: int64>>"),
+ ([np.array([[1, 2]])], "a array<array<smallint>>", "list<element:
int16>"),
+ ]:
+ with pytest.raises(pa.ArrowInvalid) as e:
+ spark.createDataFrame([(value,)], schema)
+ assert str(e.value) == (
+ f"Can only convert 1-dimensional array values of {arrow_type} to a
variable-sized "
+ "list"
+ )
+
+
def
test_nested_duplicate_field_names_are_deduplicated_in_the_arrow_schema(mock_connect):
# As PySpark's _deduplicate_field_names: the Arrow schema of nested struct
fields numbers
# duplicate names, which the server cannot read, while the schema of the
relation keeps
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]