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 c1c09e73 [SPARK-61523][CONNECT][PYTHON] Send a NumPy NaT in a day-time 
interval field of createDataFrame as null, and check for a NumPy array only 
after a list and a tuple, in the Python client as PySpark does
c1c09e73 is described below

commit c1c09e734123244be0aca6e6269c20de5a5d3cf8
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 19:26:05 2026 +0900

    [SPARK-61523][CONNECT][PYTHON] Send a NumPy NaT in a day-time interval 
field of createDataFrame as null, and check for a NumPy array only after a list 
and a tuple, in the Python client as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61523](https://issues.apache.org/jira/browse/SPARK-61523): 
follow-ups of a post-hoc review of the SPARK-61483 follow-up #546, checked 
against PySpark 4.3.0. PySpark passes the values of these fields to PyArrow as 
they are. Both changes are in `crates/pyspark-rs/src/infer.rs`.
    
    - **A NumPy NaT in a day-time interval field.** `duration_micros` returns 
`None` for a NaT of `timedelta64[us]`, which NumPy holds as the least int64, 
and `arrow_scalar` sends it as null, as PyArrow makes it. This applies wherever 
the value is: a scalar, an element of a NumPy array of an array field, or a 
value of a struct or a map.
    - **The NumPy check of an array value.** `arrow_list` reads a list and a 
tuple first, since neither can be a NumPy array. Only other values go through 
`numpy_array_dimensions`, which now reads `sys` from a cache instead of 
importing it for every value.
    
    ### Why are the changes needed?
    
    - **A wrong value.**
      - `createDataFrame([(np.timedelta64("NaT", "us"),)], "v interval day to 
second").collect()` gave `[Row(v=timedelta(days=-106751992, seconds=71945, 
microseconds=224192))]`. That is -9223372036854775808 microseconds.
      - PySpark gives `[Row(v=None)]`, and its pandas path, as ours, gives None 
too.
      - The same held for `np.array([1, "NaT"], dtype="timedelta64[us]")` in an 
array field, and for a NaT in a list, a struct, a map or a dict row.
      - The defect predates #546: it has been there since SPARK-61106. #546's 
array path reaches it as well.
    - **A slowdown.**
      - #546 made every array value check for a NumPy array first, through an 
import of `sys`.
      - `createDataFrame` of 100,000 rows of `([1, 2, 3],)` in an `array<int>` 
field (the path without a converter) took 75 ms before this change and takes 37 
ms now. That is the time of the converter path (non-nullable fields), which did 
not change (39 ms). Measured under the same Python 3.11 (x86_64), best of 5.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes:
    - A NumPy NaT in a nullable day-time interval field is null, as in PySpark.
    - In a non-nullable field, it now raises the error of a null in a 
non-nullable column ("Column 'v' is declared as non-nullable but contains 
null"). Before, it sent the least int64. PySpark sends PyArrow's null slot 
there, which collects as `timedelta(0)`, a value the data did not have, so ours 
raises instead, as for the NaT of a date.
    
    ### How was this patch tested?
    
    - Offline (`python/tests/test_dropin_offline.py`): new 
`test_a_numpy_nat_of_a_day_time_interval_field_is_null_as_pyarrow`, placed 
after `test_values_of_local_rows_convert_and_raise_as_pyarrow`.
      - It checks the nulls in the Arrow table sent for a scalar, a NumPy array 
element, a struct field and a map value.
      - Without the change, it fails with `datetime.timedelta(days=-106751992, 
...) != None`.
    - Against PySpark 4.3.0 and a local Spark 4.3.0 server, the review's probe 
of 9 NaT cases (scalars, arrays, lists, structs, maps, dict rows and pandas) 
gives the same `collect()` results as PySpark. A NaT of another unit raises 
PySpark's `ArrowNotImplementedError` as before.
    - The array conversions are unchanged: the tests of #546 and of the 
local-rows conversions pass (103 tests selected by `-k "local_rows or 
no_converter or arrow_list or interval or numpy"`).
    - Checks:
      - the lib tests of both crates (840 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 #557 from HyukjinKwon/s21-numpy-nat-and-list-checks.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/infer.rs      | 52 +++++++++++++++++++++++--------------
 python/tests/test_dropin_offline.py | 17 ++++++++++++
 2 files changed, 49 insertions(+), 20 deletions(-)

diff --git a/crates/pyspark-rs/src/infer.rs b/crates/pyspark-rs/src/infer.rs
index 1b2b0bbd..b98171cc 100644
--- a/crates/pyspark-rs/src/infer.rs
+++ b/crates/pyspark-rs/src/infer.rs
@@ -32,6 +32,7 @@ static TIME: PyOnceLock<Py<PyType>> = PyOnceLock::new();
 static TIMEDELTA: PyOnceLock<Py<PyType>> = PyOnceLock::new();
 static ARRAY: PyOnceLock<Py<PyType>> = PyOnceLock::new();
 static SORTED: PyOnceLock<Py<PyAny>> = PyOnceLock::new();
+static SYS: PyOnceLock<Py<PyModule>> = PyOnceLock::new();
 
 /// Cache the accelerator class, including its absence, independently of the 
public alias.
 pub(crate) fn c_decimal_type(py: Python<'_>) -> PyResult<Option<&Bound<'_, 
PyType>>> {
@@ -1245,6 +1246,19 @@ fn arrow_list(
 ) -> PyResult<Value> {
     let py = obj.py();
     let mut items = Vec::new();
+    // A list and a tuple, the values of most rows, are read first: neither is 
a NumPy array.
+    if let Ok(list) = obj.cast::<PyList>() {
+        for item in list.iter() {
+            items.push(convert(&item, element_type, contains_null, late)?);
+        }
+        return Ok(Value::List(items));
+    }
+    if let Ok(tuple) = obj.cast::<PyTuple>() {
+        for item in tuple.iter() {
+            items.push(convert(&item, element_type, contains_null, late)?);
+        }
+        return Ok(Value::List(items));
+    }
     if numpy_array_dimensions(obj)?.is_some_and(|dimensions| dimensions != 1) {
         let message = match arrow_type_text(dt) {
             Some(list) => format!(
@@ -1258,15 +1272,7 @@ fn arrow_list(
     // SAFETY: `obj` is a live object, and PySequence_Check always succeeds 
without calling
     // into Python.
     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 {
+    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()) };
@@ -1312,8 +1318,9 @@ fn arrow_list(
 /// 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"))?
+    let modules = SYS
+        .get_or_try_init(py, || py.import("sys").map(Bound::unbind))?
+        .bind(py)
         .getattr(intern!(py, "modules"))?;
     match modules.cast::<PyDict>()?.get_item(intern!(py, "numpy"))? {
         Some(numpy) if !numpy.is_none() => {
@@ -1597,7 +1604,9 @@ fn arrow_scalar(obj: &Bound<'_, PyAny>, dt: &DataType) -> 
PyResult<Value> {
                 _ => Value::Double(value),
             })
         }
-        DataType::DayTimeInterval { .. } => 
Ok(Value::DayTimeInterval(duration_micros(obj)?)),
+        DataType::DayTimeInterval { .. } => {
+            Ok(duration_micros(obj)?.map_or(Value::Null, 
Value::DayTimeInterval))
+        }
         DataType::Date => Ok(Value::Date(date_days(obj)?)),
         // As PyArrow's `time64[ns]`, to which PySpark passes the value as it 
is: a time, else
         // the nanoseconds of the value as `CIntFromPython` takes it.
@@ -1839,12 +1848,13 @@ fn udt_of<'py>(
 }
 
 /// The microseconds of a value of a day-time interval column, as PyArrow 
converts it to
-/// `duration[us]`: a timedelta; a NumPy scalar of `timedelta64[us]`, as 
another NumPy scalar
-/// raises `ArrowNotImplementedError`; else the value as `CIntFromPython` 
takes it.
-fn duration_micros(obj: &Bound<'_, PyAny>) -> PyResult<i64> {
+/// `duration[us]`: a timedelta; a NumPy scalar of `timedelta64[us]`, or None 
for its NaT, which
+/// PyArrow makes null, as another NumPy scalar raises 
`ArrowNotImplementedError`; else the value
+/// as `CIntFromPython` takes it.
+fn duration_micros(obj: &Bound<'_, PyAny>) -> PyResult<Option<i64>> {
     let py = obj.py();
     if obj.is_instance(TIMEDELTA.import(py, "datetime", 
"timedelta")?.as_any())? {
-        return timedelta_micros(obj);
+        return timedelta_micros(obj).map(Some);
     }
     if numpy_generic(obj)? {
         let arrow_type = py.import(intern!(py, "pyarrow"))?.call_method1(
@@ -1853,10 +1863,12 @@ fn duration_micros(obj: &Bound<'_, PyAny>) -> 
PyResult<i64> {
         )?;
         let arrow_type = arrow_type.str()?.to_cow()?.into_owned();
         if arrow_type == "duration[us]" {
-            // The microseconds that the scalar holds, as PyArrow reads them.
-            return obj
+            // The microseconds that the scalar holds, as PyArrow reads them. 
A NaT, which NumPy
+            // holds as the least int64, is null, as PyArrow makes it.
+            let micros: i64 = obj
                 .call_method1(intern!(py, "astype"), (intern!(py, "int64"),))?
-                .extract();
+                .extract()?;
+            return Ok((micros != i64::MIN).then_some(micros));
         }
         return Err(pyarrow_error(
             py,
@@ -1864,7 +1876,7 @@ fn duration_micros(obj: &Bound<'_, PyAny>) -> 
PyResult<i64> {
             format!("Expected np.timedelta64 but got: {arrow_type}"),
         )?);
     }
-    c_int_from_python(obj, 64, None)
+    c_int_from_python(obj, 64, None).map(Some)
 }
 
 /// The microseconds of a `datetime.timedelta`, as 
`DayTimeIntervalType.toInternal`:/// The microseconds of a 
`datetime.timedelta`, as `DayTimeIntervalType.toInternal`:
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index b1e556e3..bee87ee0 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -15706,6 +15706,23 @@ def 
test_values_of_local_rows_convert_and_raise_as_pyarrow(mock_connect):
         assert e.value.getCondition() == 
"UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION"
         assert e.value.getMessageParameters() == {"data_type": data_type}
 
+
+def 
test_a_numpy_nat_of_a_day_time_interval_field_is_null_as_pyarrow(mock_connect):
+    # As PyArrow, to which PySpark passes the values of a day-time interval 
field as they are: a
+    # NaT of NumPy is null, as a scalar and in an array, also within a struct 
or a map.
+    np = pytest.importorskip("numpy")
+    spark, service = mock_connect
+    nat = np.timedelta64("NaT", "us")
+    table, _ = _local_rows_relation_of(service, spark.createDataFrame(
+        [(nat, np.array([1, "NaT"], dtype="timedelta64[us]"), (nat,), {"k": 
nat})],
+        "v interval day to second, a array<interval day to second>, "
+        "s struct<x: interval day to second>, m map<string, interval day to 
second>"))
+    assert table.column("v").to_pylist() == [None]
+    assert table.column("a").to_pylist() == 
[[datetime.timedelta(microseconds=1), None]]
+    assert table.column("s").to_pylist() == [{"x": None}]
+    assert table.column("m").to_pylist() == [[("k", None)]]
+
+
 @pytest.mark.parametrize(
     "rows,ddl,error,message",
     [


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to