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 55febda9 [SPARK-61483][CONNECT][PYTHON] Send the bytes of binary 
literal subclasses, corr and cov without a limit, and check the Arrow schema of 
createDataFrame depth first, in the Python client as PySpark does
55febda9 is described below

commit 55febda906a233cdb7229b6c45c0352217d184fa
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 12:20:29 2026 +0900

    [SPARK-61483][CONNECT][PYTHON] Send the bytes of binary literal subclasses, 
corr and cov without a limit, and check the Arrow schema of createDataFrame 
depth first, in the Python client as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61483](https://issues.apache.org/jira/browse/SPARK-61483): a 
follow-up of [SPARK-61410](https://issues.apache.org/jira/browse/SPARK-61410) 
(#517), [SPARK-61414](https://issues.apache.org/jira/browse/SPARK-61414) 
(#518), [SPARK-61434](https://issues.apache.org/jira/browse/SPARK-61434) (#520) 
and [SPARK-61435](https://issues.apache.org/jira/browse/SPARK-61435) (#521). It 
fixes the siblings that their reviews found, so that these paths also match 
PySpark 4.3.0:
    
    1. **Binary literals (sibling of SPARK-61435).** A binary literal of the 
Python client now holds `bytes(value)` of a subclass of `bytes` or `bytearray`, 
as PySpark's `LiteralExpression.to_plan` sends it (`expr.literal.binary = 
bytes(self._value)`, pyspark/sql/connect/expressions.py:476). This covers 
`lit()`, the values that the functions and the Column methods take (`isin`, 
`when`, `otherwise`, `getItem`, ...), the elements of a typed array literal, 
and the arguments of `sql()`. `scal [...]
    2. **No Config through a closed client while raising (sibling of 
SPARK-61410).** `SparkConnectClient::conf_while_raising` 
(`crates/spark-connect-core/src/client.rs`) sends nothing once the client is 
closed and returns no value. `display_server_stacktrace` takes that as true. 
PySpark's `_display_server_stack_trace` reads the setting through 
`RuntimeConf.get` -> `client.config` -> `_stub`. `_stub` raises 
NO_ACTIVE_SESSION once the client is closed, and the method's `except 
Exception` re [...]
    3. **`corr` and `cov` without a limit (sibling of SPARK-61414).** 
`DataFrame::first_value` (`crates/spark-connect/src/dataframe.rs`) collects the 
relation as it is, instead of `limit(1).collect()`. Its only callers are 
`StatFunctions::corr` and `cov`. PySpark's `cov` and `corr` take 
`_to_table()[0][0]` of the bare `StatCov`/`StatCorr` relation 
(pyspark/sql/connect/dataframe.py:1619-1674). The Python client's `df.corr`, 
`df.cov`, `df.stat.corr` and `df.stat.cov` call the core, so they  [...]
    4. **`isEmpty` reads `binaryAsBytes` (sibling of SPARK-61414).** The Python 
client's `isEmpty` reads `spark.sql.execution.pyspark.binaryAsBytes` after its 
execution. PySpark's `isEmpty` is `select().take(1)`, that is 
`limit(1).collect()`, and `collect` calls `_get_binary_as_bytes()` 
(pyspark/sql/connect/dataframe.py:285-287, 706-707, 1961-1978). `isEmpty` is 
still asked once per DataFrame, as PySpark's `functools.cache` keeps it.
    5. **The Arrow schema checks of createDataFrame of local rows run depth 
first (from the review of SPARK-61434; older than it).** 
`infer::arrow_schema_error` replaces `has_non_nullable_null_type` and 
`unsupported_arrow_type`, which ran as two passes over all the fields. It walks 
the fields once, depth first, in the order in which PySpark's `to_arrow_schema` 
and `to_arrow_type` build them (pyspark/sql/pandas/types.py:94-294). For each 
field, the type is built first, so an unsupported ty [...]
    6. **"Not a sequence" as PyArrow checks it (from the review of SPARK-61434; 
older than it).** This applies to an array column whose elements need no 
converter, so PySpark passes the value to PyArrow as it is. 
`infer::is_arrow_list` mirrors PyArrow's list converter. It takes a sequence by 
`PySequence_Check`, such as a tuple, a range or a NumPy array, but never a 
dict. It also takes a `set` and a `dict_values`. Every other value gets 
PyArrow's deferred `ArrowTypeError`. Before, any iter [...]
    
    ### Why are the changes needed?
    
    To match PySpark 4.3.0. The probes below ran the Connect client of official 
PySpark 4.3.0 and this client against a local Spark 4.3.0 Connect server.
    
    - Binary literals, with `class Bytes(bytes)` and `class 
ByteArray(bytearray)` whose `__bytes__` returns `b"other"`. The collected 
values, as PySpark 4.3.0 gives them and as this client gave them before; after 
the change, this client gives PySpark's in each case:
    
      ```
                                              PySpark 4.3.0                
before
      lit(Bytes(b"orig")), lit(ByteArray(..)) b'other'                     
b'orig'
      lit([Bytes(b"orig"), Bytes(b"orig2")])  [b'other', b'other']         
[b'orig', b'orig2']
      isin(Bytes(b"orig")) on a b"other" row  1 row                        0 
rows
      when(.., Bytes), otherwise(Bytes)       b'other'                     
b'orig'
      otherwise([b"b", Bytes, ByteArray])     [b'b', b'other', b'other']   
[b'b', b'orig', b'orig']
      create_map(lit("k"), lit(Bytes))        {'k': b'other'}              
{'k': b'orig'}
      sql(.., args={"x": Bytes} or [Bytes])   b'other'                     
b'orig'
      lit of a __bytes__ that returns a str   TypeError: __bytes__ returned 
non-bytes   b'a'
      lit of a bytearray subclass whose __index__ is 2, of b"abc"   b'\x00\x00' 
       b'abc'
      ```
    
      The data differs silently, which is the bug that SPARK-61435 fixed for 
createDataFrame. PySpark raises an error of `__bytes__` when it sends the plan. 
This client builds a literal at once, so it raises the error at `lit()`.
    - The stack-trace setting: a probe of PySpark sets 
`spark.sql.connect.enrichError.enabled=false`, so that the error has no 
`errorId`, and then changes the server-side session ID. The call that hits the 
session change sends `['ExecutePlan', 'ReleaseExecute']`, with no Config. This 
client also sent a Config for `spark.sql.connect.serverStacktrace.enabled` 
through the closed client.
    - `corr`/`cov` and `isEmpty`, from a record of the RPCs of official PySpark:
    
      ```
      df.corr("id", "b"), df.stat.corr  ExecutePlan root: corr { ... }   (no 
Limit, no Config)
      df.cov("id", "b"), df.stat.cov    ExecutePlan root: cov { ... }    (no 
Limit, no Config)
      range(3).isEmpty()               ExecutePlan root: limit { project { 
range } }, then
                                       Config get_with_default 
spark.sql.execution.pyspark.binaryAsBytes
      ```
    
      Before, this client sent `limit { corr { ... } }` and `limit { cov { ... 
} }`, and its `isEmpty` read no Config. The results are unchanged: 1.0, 2.0, 
NaN for an empty relation, and False/True for `isEmpty`.
    - The Arrow schema order: 8 of 20 probed schemas raised a different error 
than PySpark. Some of them:
    
      ```
                                                       PySpark 4.3.0      before
      a interval year to month, b void NOT NULL        PySparkTypeError   
ValueError
      a struct<x: interval year to month, y: void NOT NULL>  PySparkTypeError  
ValueError
      a map<interval year to month, void> (no nulls)   PySparkTypeError   
ValueError
      a calendar interval / char(3), b void NOT NULL   PySparkTypeError   
ValueError
      a UDT of sqlType interval year to month          PySparkTypeError   no 
error
      a UDT of sqlType struct<x: void NOT NULL>, b interval year to month  
ValueError  PySparkTypeError
      ```
    
      The `PySparkTypeError` is `[UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION]`, 
of the type (e.g. `YearMonthIntervalType(0, 1)`). After the change, all 20 
match.
    - "Not a sequence", for `createDataFrame([(value,)], "a array<int>")`:
    
      ```
                                  PySpark 4.3.0                                 
 before
      generator, list_iterator    ArrowTypeError ... was not a sequence ...     
 [1, 2]
      dict_keys, mappingproxy     ArrowTypeError ... was not a sequence ...     
 [1]
      frozenset                   ArrowTypeError ... was not a sequence ...     
 [1, 2]
      dict_items                  ArrowTypeError ... was not a sequence ...     
 ArrowInvalid: Could not convert (1, 2) ...
      range, set, dict_values, tuple, deque, array.array, bytes   accepted      
accepted
      ```
    
      PyArrow 22.0.0 itself gives the same answers for these values in a 
`list<int32>` column. After the change, all of them match PySpark, and the 
error still waits for the converters of the other columns, as in SPARK-61434.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, as PySpark behaves:
    
    - A binary literal of a subclass of `bytes` or `bytearray` holds 
`bytes(value)` (the result of its `__bytes__`), and an error of `__bytes__` is 
raised.
    - `corr` and `cov`, in Rust and in the Python client, send their statistic 
without a `Limit` over it.
    - The Python client's `isEmpty` reads 
`spark.sql.execution.pyspark.binaryAsBytes` after its execution.
    - After a session change whose error has no `errorId`, the client sends no 
Config for the stack-trace setting.
    - createDataFrame of local rows raises the first error of the Arrow schema 
in PySpark's order, including inside a user-defined type. It raises PyArrow's 
`ArrowTypeError` for the iterables that PyArrow does not take as a list, in an 
array column whose elements need no converter.
    
    Values that converted before still convert the same way, except for these 
cases.
    
    ### How was this patch tested?
    
    New tests, each named after its behavior and placed next to the tests of 
the PR that it follows:
    
    - `python/tests/test_dropin_offline.py`:
      - `test_binary_literals_of_subclasses_are_sent_as_the_bytes_of_pyspark`, 
after SPARK-61435's `test_binary_subclasses_are_sent_as_the_bytes_of_pyspark`. 
It covers `lit`, `isin`, `when`, `create_map`, typed arrays with the subclass 
first and not first, an error of `__bytes__`, and the named and positional 
arguments of `sql()`.
      - `test_is_empty_reads_the_binary_setting_after_its_execution_as_pyspark` 
and `test_corr_and_cov_send_their_statistic_as_it_is_as_pyspark`, after 
SPARK-61414's 
`test_is_empty_sends_a_limit_of_one_row_over_an_empty_projection_as_pyspark`.
      - 
`test_local_rows_raise_the_first_error_of_the_arrow_schema_depth_first_as_pyspark`
 and 
`test_an_array_of_no_converter_takes_the_values_that_pyarrow_takes_as_pyspark`, 
after SPARK-61434's 
`test_local_rows_raise_the_error_of_a_converter_before_that_of_pyarrow`.
    - `crates/spark-connect-core/tests/server_session.rs`: 
`a_session_changed_error_reads_no_stack_trace_setting_as_pyspark`, after 
SPARK-61410's 
`a_session_changed_error_that_has_details_raises_no_active_session`. It checks 
that the Config that failed is the only request.
    - `crates/spark-connect/src/group.rs` (unit tests): 
`corr_and_cov_send_their_statistic_as_it_is_as_pyspark`. On a session without a 
server and without retries, an execute-plan hook records the root of each 
request and fails it.
    
    Each new test fails without the change. With the source changes reverted, 
the tests kept and the extension rebuilt, they fail with:
    
    - `test_is_empty_reads_...`: `assert ['execute'] == ['execute', 'config']`
    - `test_corr_and_cov_...` (Python): `assert ['limit', 'limit', 'limit', 
'limit'] == ['corr', 'cov', 'corr', 'cov']`
    - `test_binary_literals_...`: `assert b'orig' == b'other'`
    - `test_local_rows_raise_the_first_error_...`: `ValueError` where 
`PySparkTypeError` is expected, for `a interval year to month, b void not null`
    - `test_an_array_of_no_converter_...`: `DID NOT RAISE <class 
'pyarrow.lib.ArrowTypeError'>`
    - `a_session_changed_error_reads_no_stack_trace_setting_as_pyspark`: `left: 
["Config", "Config"]`, `right: ["Config"]`
    - `corr_and_cov_send_their_statistic_as_it_is_as_pyspark` (Rust): the 
recorded roots are `[Limit(.. Corr ..), Limit(.. Cov ..)]`
    
    The cases of the two new createDataFrame tests and the expectations of the 
new literal test also ran against official PySpark 4.3.0, and they hold there.
    
    Commands, all passing:
    
    - `cargo test -p apache-spark-connect-core --release --test server_session` 
(8 passed) and `--lib` (197 passed)
    - `cargo test -p apache-spark-connect --release --lib` (605 passed, 
including the 22 of `group::tests`)
    - `cargo test -p apache-spark-connect --release --no-run` and `cargo test 
-p apache-spark-connect --release --features wasm-udf --no-run`: no warnings
    - `cargo fmt --all --check`, and `ruff check` (0.14.0, as CI runs it)
    - `cargo clippy --release --all-targets` of `pyspark-rs`, 
`apache-spark-connect` and `apache-spark-connect-core` reports nothing in the 
changed lines
    - `python -m pytest python/tests/test_dropin_offline.py`, the whole file: 
1855 passed, 8 skipped
    - Against a local Spark 4.3.0 Connect server (`SPARK_REMOTE` set):
      - `python -m pytest python/tests/test_dropin_e2e.py -k "(binary or bytes 
or lit or corr or cov or stat or empty or create or server_session or error or 
schema or array or sql) and not stream and not Stream"`: 95 passed. This 
includes SPARK-61410's session-change test and SPARK-61435's binary test.
      - `-k "answers_that_pyspark_keeps or column_list_values_are_typed_array 
or numpy_scalar_literals or decimal_literals or datetime_literals or 
try_cast_and_isin or lists_and_numpy_arrays"`: 8 passed
      - `cargo test -p apache-spark-connect --release` with `--test 
e2e_new_methods stat_corr_cov_sample_by`, `--test e2e_dataframe is_empty` and 
`--test e2e_coverage agg_na_stat_reshape_surface`: passed
    
    ### 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 #538 from HyukjinKwon/SPARK-61483-tim-review-followups.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/dataframe.rs                |   8 +-
 crates/pyspark-rs/src/functions.rs                |  19 +--
 crates/pyspark-rs/src/infer.rs                    | 147 ++++++++++++--------
 crates/pyspark-rs/src/session.rs                  |  16 +--
 crates/spark-connect-core/src/client.rs           |   5 +
 crates/spark-connect-core/tests/server_session.rs |  36 +++++
 crates/spark-connect/src/dataframe.rs             |   6 +-
 crates/spark-connect/src/group.rs                 |  35 +++++
 python/tests/test_dropin_offline.py               | 162 ++++++++++++++++++++++
 9 files changed, 346 insertions(+), 88 deletions(-)

diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index 0760f3fb..136696f3 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -2624,9 +2624,13 @@ impl PyDataFrame {
     /// Check if the DataFrame is empty, asked once, as PySpark's.
     fn isEmpty(&self, py: Python<'_>) -> PyResult<bool> {
         cached(&self.is_empty, || {
-            interruptible(py, &self.dataframe.spark_session(), || {
+            let empty = interruptible(py, &self.dataframe.spark_session(), || {
                 self.dataframe.is_empty().map_err(Box::new)
-            })
+            })?;
+            // As PySpark's `select().take(1)`, whose `collect` reads the 
binary setting once the
+            // rows are fetched, though they have no columns.
+            read_binary_as_bytes(py, &self.dataframe)?;
+            Ok(empty)
         })
     }
 
diff --git a/crates/pyspark-rs/src/functions.rs 
b/crates/pyspark-rs/src/functions.rs
index a3b31967..0931d2b9 100644
--- a/crates/pyspark-rs/src/functions.rs
+++ b/crates/pyspark-rs/src/functions.rs
@@ -544,14 +544,11 @@ fn literal_as(
                 Err(_) => return Err(not_utf8_string(obj)),
             }
         }
-        DataType::Binary => {
-            if !(obj.is_instance_of::<pyo3::types::PyBytes>()
-                || obj.is_instance_of::<pyo3::types::PyByteArray>())
-            {
-                return Err(assertion());
-            }
-            LiteralExpression::Binary(obj.extract::<Vec<u8>>()?)
-        }
+        // As PySpark's `to_plan`, which sends `bytes(value)`.
+        DataType::Binary => match crate::infer::bytes_of(obj)? {
+            Some(bytes) => LiteralExpression::Binary(bytes),
+            None => return Err(assertion()),
+        },
         DataType::Date => {
             // A datetime is a date too, and its date is the one of the 
literal.
             if !is_instance_of_class(obj, "datetime", "date")? {
@@ -849,10 +846,8 @@ fn scalar_literal(obj: &Bound<'_, PyAny>) -> 
PyResult<Option<LiteralExpression>>
     }
 
     // bytes / bytearray -> Binary. Checked explicitly so it is not mistaken 
for anything else.
-    if obj.is_instance_of::<pyo3::types::PyBytes>()
-        || obj.is_instance_of::<pyo3::types::PyByteArray>()
-    {
-        let bytes: Vec<u8> = obj.extract()?;
+    // PySpark's `to_plan` sends `bytes(value)`, which honors the `__bytes__` 
of a subclass.
+    if let Some(bytes) = crate::infer::bytes_of(obj)? {
         return Ok(Some(LiteralExpression::Binary(bytes)));
     }
 
diff --git a/crates/pyspark-rs/src/infer.rs b/crates/pyspark-rs/src/infer.rs
index ad635f05..2cb66078 100644
--- a/crates/pyspark-rs/src/infer.rs
+++ b/crates/pyspark-rs/src/infer.rs
@@ -14,8 +14,8 @@ use pyo3::intern;
 use pyo3::prelude::*;
 use pyo3::sync::PyOnceLock;
 use pyo3::types::{
-    IntoPyDict, PyBool, PyByteArray, PyBytes, PyDict, PyFloat, PyInt, PyList, 
PyMemoryView,
-    PyString, PyTuple, PyType,
+    IntoPyDict, PyBool, PyByteArray, PyBytes, PyDict, PyDictValues, PyFloat, 
PyInt, PyList,
+    PyMemoryView, PySet, PyString, PyTuple, PyType,
 };
 use spark_connect::row::{StructValue, Value};
 use spark_connect::session::SparkSession;
@@ -1182,6 +1182,35 @@ fn utf8_text(text: &Bound<'_, PyString>) -> 
PyResult<Value> {
     Ok(Value::String(text.to_cow()?.into_owned()))
 }
 
+/// The bytes of a bytes or a bytearray, as PySpark sends `bytes(value)` of 
one, in a binary
+/// column of createDataFrame and in a binary literal: an exact one is read as 
it is, and of a
+/// subclass, `bytes()` honors its `__bytes__`, which its buffer does not. 
`None` for another
+/// value.
+pub(crate) fn bytes_of(obj: &Bound<'_, PyAny>) -> PyResult<Option<Vec<u8>>> {
+    if let Ok(bytes) = obj.cast_exact::<PyBytes>() {
+        Ok(Some(bytes.as_bytes().to_vec()))
+    } else if let Ok(bytes) = obj.cast_exact::<PyByteArray>() {
+        Ok(Some(bytes.to_vec()))
+    } else if obj.is_instance_of::<PyBytes>() || 
obj.is_instance_of::<PyByteArray>() {
+        let bytes = obj.py().get_type::<PyBytes>().call1((obj,))?;
+        Ok(Some(bytes.cast::<PyBytes>()?.as_bytes().to_vec()))
+    } else {
+        Ok(None)
+    }
+}
+
+/// 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 {
+    // 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>()
+}
+
 /// A field value of `dt` from `obj`, as PySpark's converters and then PyArrow 
convert it.
 pub(crate) fn convert(
     obj: &Bound<'_, PyAny>,
@@ -1213,15 +1242,16 @@ 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 any
-            // sequence, such as a tuple or a NumPy array of numbers or bools.
+            // 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 obj.is_instance_of::<PyDict>() || 
obj.try_iter().is_err() {
+            } else if !is_arrow_list(obj) || obj.try_iter().is_err() {
                 return Ok(late.defer(|| {
                     Err(pyarrow_error(
                         py,
@@ -1256,19 +1286,10 @@ pub(crate) fn convert(
             }
             Ok(Value::Map(entries))
         }
-        DataType::Binary => {
-            if let Ok(bytes) = obj.cast_exact::<PyBytes>() {
-                Ok(Value::Binary(bytes.as_bytes().to_vec()))
-            } else if let Ok(bytes) = obj.cast_exact::<PyByteArray>() {
-                Ok(Value::Binary(bytes.to_vec()))
-            } else if obj.is_instance_of::<PyBytes>() || 
obj.is_instance_of::<PyByteArray>() {
-                // bytes(obj) honors a __bytes__ of the subclass, which its 
buffer does not.
-                let bytes = py.get_type::<PyBytes>().call1((obj,))?;
-                Ok(Value::Binary(bytes.cast::<PyBytes>()?.as_bytes().to_vec()))
-            } else {
-                Err(assertion())
-            }
-        }
+        DataType::Binary => match bytes_of(obj)? {
+            Some(bytes) => Ok(Value::Binary(bytes)),
+            None => Err(assertion()),
+        },
         DataType::Timestamp | DataType::TimestampLtzNanos { .. } => {
             if !obj.is_instance(DATETIME.import(py, "datetime", 
"datetime")?.as_any())? {
                 return Err(assertion());
@@ -1325,7 +1346,7 @@ pub(crate) fn convert(
             Ok(late.defer(|| utf8_text(&text)))
         }
         // As PySpark, which has no converter of these types: the value goes 
as it is to
-        // `to_arrow_schema`, which raises for the type 
(`unsupported_arrow_type`).
+        // `to_arrow_schema`, which raises for the type (`arrow_schema_error`).
         DataType::Char { .. }
         | DataType::Varchar { .. }
         | DataType::YearMonthInterval { .. }
@@ -1478,67 +1499,71 @@ fn date_days(obj: &Bound<'_, PyAny>) -> PyResult<i32> {
     Ok(c_int_from_python(obj, 32, Some("Integer too large for date32"))? as 
i32)
 }
 
-/// Whether a field of `fields`, or a type in one, is a null type that is not 
nullable. PyArrow
-/// rejects such a field when it builds it, `pa.field(name, pa.null(), 
nullable=False)`, which
-/// PySpark's `to_arrow_schema` does. A map key is never nullable.
-pub(crate) fn has_non_nullable_null_type(fields: &[StructField]) -> bool {
-    fn in_type(dt: &DataType) -> bool {
+/// The first error of PySpark's `to_arrow_schema` of the schema of local 
rows, which builds the
+/// Arrow fields one at a time, depth first, each once its type is built: a 
char, varchar,
+/// year-month or calendar interval type, of which Arrow has no type, is
+/// `UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION`, and a field of the null type 
that is not
+/// nullable, as a map key never is, is the `ValueError` of PyArrow's
+/// `pa.field(name, pa.null(), nullable=False)`. A user-defined type is built 
as its SQL type.
+pub(crate) fn arrow_schema_error(
+    py: Python<'_>,
+    fields: &[StructField],
+) -> PyResult<Option<PyErr>> {
+    enum Error<'a> {
+        Unsupported(&'a DataType),
+        NonNullableNull,
+    }
+    fn of_type(dt: &DataType) -> Option<Error<'_>> {
         match dt {
-            DataType::Struct { fields } => has_non_nullable_null_type(fields),
+            DataType::Char { .. }
+            | DataType::Varchar { .. }
+            | DataType::YearMonthInterval { .. }
+            | DataType::CalendarInterval => Some(Error::Unsupported(dt)),
+            DataType::Struct { fields } => fields
+                .iter()
+                .find_map(|f| of_field(&f.data_type, f.nullable)),
             DataType::Array {
                 element_type,
                 contains_null,
-            } => {
-                (!contains_null && matches!(**element_type, DataType::Null))
-                    || in_type(element_type)
-            }
+            } => of_field(element_type, *contains_null),
             DataType::Map {
                 key_type,
                 value_type,
                 value_contains_null,
-            } => {
-                matches!(**key_type, DataType::Null)
-                    || (!value_contains_null && matches!(**value_type, 
DataType::Null))
-                    || in_type(key_type)
-                    || in_type(value_type)
-            }
-            _ => false,
+            } => of_field(key_type, false).or_else(|| of_field(value_type, 
*value_contains_null)),
+            DataType::Udt {
+                sql_type: Some(sql_type),
+                ..
+            } => of_type(sql_type),
+            _ => None,
         }
     }
-    fields
-        .iter()
-        .any(|f| (!f.nullable && matches!(f.data_type, DataType::Null)) || 
in_type(&f.data_type))
-}
-
-/// The `UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION` of the first char, 
varchar, year-month or
-/// calendar interval type of `dt`, depth first, which PySpark's 
`to_arrow_schema` raises when it
-/// converts the schema of local rows to Arrow: it has no Arrow type of these 
types.
-pub(crate) fn unsupported_arrow_type(py: Python<'_>, dt: &DataType) -> 
PyResult<Option<PyErr>> {
-    fn first_unsupported(dt: &DataType) -> Option<&DataType> {
+    fn is_null(dt: &DataType) -> bool {
         match dt {
-            DataType::Char { .. }
-            | DataType::Varchar { .. }
-            | DataType::YearMonthInterval { .. }
-            | DataType::CalendarInterval => Some(dt),
-            DataType::Struct { fields } => {
-                fields.iter().find_map(|f| first_unsupported(&f.data_type))
-            }
-            DataType::Array { element_type, .. } => 
first_unsupported(element_type),
-            DataType::Map {
-                key_type,
-                value_type,
+            DataType::Null => true,
+            DataType::Udt {
+                sql_type: Some(sql_type),
                 ..
-            } => first_unsupported(key_type).or_else(|| 
first_unsupported(value_type)),
-            _ => None,
+            } => is_null(sql_type),
+            _ => false,
         }
     }
-    Ok(match first_unsupported(dt) {
-        Some(unsupported) => Some(raise_pyspark(
+    fn of_field(dt: &DataType, nullable: bool) -> Option<Error<'_>> {
+        of_type(dt).or_else(|| (!nullable && 
is_null(dt)).then_some(Error::NonNullableNull))
+    }
+    let first = fields
+        .iter()
+        .find_map(|f| of_field(&f.data_type, f.nullable));
+    Ok(match first {
+        Some(Error::Unsupported(unsupported)) => Some(raise_pyspark(
             py,
             "PySparkTypeError",
             "UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION",
             &[("data_type", &data_type_str(py, unsupported)?)],
         )),
+        Some(Error::NonNullableNull) => Some(PyValueError::new_err(
+            "A null type field may not be non-nullable",
+        )),
         None => None,
     })
 }
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index 7c1f15ca..effcb265 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -1014,17 +1014,11 @@ impl PySparkSession {
                 }
             }
         }
-        // Then, as PySpark, the schema converts to Arrow, which rejects a 
null type that is not
-        // nullable, and has no char, varchar, year-month or calendar interval 
type.
-        if infer::has_non_nullable_null_type(&fields) {
-            return Err(pyo3::exceptions::PyValueError::new_err(
-                "A null type field may not be non-nullable",
-            ));
-        }
-        for field in &fields {
-            if let Some(err) = infer::unsupported_arrow_type(py, 
&field.data_type)? {
-                return Err(err);
-            }
+        // Then, as PySpark, the schema converts to Arrow, a field at a time 
and depth first,
+        // which rejects a null type that is not nullable, and has no char, 
varchar, year-month
+        // or calendar interval type.
+        if let Some(err) = infer::arrow_schema_error(py, &fields)? {
+            return Err(err);
         }
         // Then the columns are built, which rejects the values that no 
converter of PySpark does.
         late.finish()?;
diff --git a/crates/spark-connect-core/src/client.rs 
b/crates/spark-connect-core/src/client.rs
index 6892c423..c20e0d63 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -1542,6 +1542,11 @@ impl SparkConnectClient {
     /// raised, so that a failure is neither retried nor raised.
     async fn conf_while_raising(&self, key: &str) -> Option<String> {
         use spark_connect_proto::config_request::{operation::OpType, Get, 
Operation};
+        // PySpark reads the config through `_stub`, which raises 
NO_ACTIVE_SESSION once the
+        // client is closed, as a session change closes it, so it sends 
nothing then.
+        if self.is_closed() {
+            return None;
+        }
         let request = ConfigRequest {
             session_id: self.session_id.clone(),
             user_context: Some(UserContext {
diff --git a/crates/spark-connect-core/tests/server_session.rs 
b/crates/spark-connect-core/tests/server_session.rs
index 98b10cd8..dd772057 100644
--- a/crates/spark-connect-core/tests/server_session.rs
+++ b/crates/spark-connect-core/tests/server_session.rs
@@ -511,6 +511,42 @@ async fn 
a_session_changed_error_that_has_details_raises_no_active_session() {
         .is_empty());
 }
 
+#[tokio::test]
+async fn a_session_changed_error_reads_no_stack_trace_setting_as_pyspark() {
+    // PySpark's `_display_server_stack_trace` reads its settings through 
`_stub`, which raises
+    // NO_ACTIVE_SESSION once the session change has closed the client: 
nothing is sent, and the
+    // stack trace is shown, as when the settings cannot be read.
+    let fixture = Fixture::start().await;
+    let client = fixture.client().await;
+    fixture.state.failures.lock().unwrap().push_back((
+        "Config".to_string(),
+        error_with_class(
+            "The existing Spark server driver instance has restarted. Please 
reconnect.",
+            "INVALID_HANDLE.SESSION_CHANGED",
+        ),
+    ));
+
+    let error = client
+        .config(config_request(&client))
+        .await
+        .expect_err("a session change must raise");
+    assert_eq!(
+        error.get_condition().as_deref(),
+        Some("INVALID_HANDLE.SESSION_CHANGED")
+    );
+    assert!(client.is_closed());
+    // The Config that failed, and nothing after it.
+    let methods: Vec<String> = fixture
+        .state
+        .requests
+        .lock()
+        .unwrap()
+        .iter()
+        .map(|(method, _)| method.clone())
+        .collect();
+    assert_eq!(methods, ["Config"]);
+}
+
 #[tokio::test]
 async fn 
a_client_without_session_tracking_passes_the_ids_of_its_requests_through() {
     // The transport-injection stub sends the requests of the reference 
client's session, which
diff --git a/crates/spark-connect/src/dataframe.rs 
b/crates/spark-connect/src/dataframe.rs
index 8672bcb0..72ca0e3f 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -2680,9 +2680,11 @@ impl DataFrame {
         Column::new(ExpressionNode::Subquery(Box::new(subquery)).into())
     }
 
-    /// The first value of the first row, if any.
+    /// The first value of the first row, if any, of the whole result, as 
PySpark's `cov` and
+    /// `corr` take `_to_table()[0][0]` of their statistic: the relation is 
sent as it is, with
+    /// no limit over it.
     pub(crate) fn first_value(&self) -> Result<Option<Value>> {
-        let rows = self.limit(1).collect()?;
+        let rows = self.collect()?;
         Ok(rows.first().and_then(|row| row.get(0).cloned()))
     }
 
diff --git a/crates/spark-connect/src/group.rs 
b/crates/spark-connect/src/group.rs
index 10e11ee2..6dea5421 100644
--- a/crates/spark-connect/src/group.rs
+++ b/crates/spark-connect/src/group.rs
@@ -1424,6 +1424,41 @@ mod tests {
         }
     }
 
+    /// As PySpark's `corr` and `cov`, which take the first value of 
`_to_table()` of their
+    /// statistic: the relation of the statistic is the root of the plan, with 
no limit over it.
+    #[test]
+    fn corr_and_cov_send_their_statistic_as_it_is_as_pyspark() {
+        use spark_connect_proto::{plan::OpType, relation::RelType};
+        // A session of a dead port whose requests are not retried, so that 
the plan compression
+        // lookup fails at once; the hook records the request of the execution 
and fails it.
+        let builder = 
spark_connect_core::channel::ChannelBuilder::parse("sc://127.0.0.1:1")
+            .expect("valid URL");
+        let mut client = spark_connect_core::runtime::block_on(
+            spark_connect_core::client::SparkConnectClient::connect(&builder),
+        )
+        .expect("failed to build client");
+        
client.set_retry_policy(spark_connect_core::retries::RetryPolicy::no_retries());
+        let spark = SparkSession::new(client);
+        let roots: Arc<std::sync::Mutex<Vec<RelType>>> = Arc::default();
+        let seen = Arc::clone(&roots);
+        let hook: spark_connect_core::client::ExecutePlanHook =
+            Arc::new(move |request: spark_connect_proto::ExecutePlanRequest| {
+                if let Some(OpType::Root(root)) = request.plan.and_then(|plan| 
plan.op_type) {
+                    seen.lock().unwrap().extend(root.rel_type);
+                }
+                Err(SparkError::value_msg("not sent"))
+            });
+        spark.set_execute_plan_hook(Some(hook));
+        let stat = spark.range(3).unwrap().stat();
+        assert!(stat.corr("id", "id").is_err());
+        assert!(stat.cov("id", "id").is_err());
+        let roots = roots.lock().unwrap();
+        assert!(
+            matches!(roots.as_slice(), [RelType::Corr(_), RelType::Cov(_)]),
+            "{roots:?}"
+        );
+    }
+
     #[test]
     fn stat_sample_by_plan() {
         let spark = session();
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index ca459079..165017e7 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -1454,6 +1454,34 @@ def 
test_is_empty_sends_a_limit_of_one_row_over_an_empty_projection_as_pyspark(m
     assert 15 in parse_message(project[1][0])
 
 
+def 
test_is_empty_reads_the_binary_setting_after_its_execution_as_pyspark(mock_connect):
+    # As PySpark's isEmpty, select().take(1), whose collect reads
+    # spark.sql.execution.pyspark.binaryAsBytes once the rows are fetched; it 
is asked once.
+    spark, service = mock_connect
+    df = spark.range(3)
+    before = len(service.rpc_events)
+    df.isEmpty()
+    df.isEmpty()
+    assert service.rpc_events[before:] == ["execute", "config"]
+    assert service.read_confs == ["spark.sql.execution.pyspark.binaryAsBytes"]
+
+
+def test_corr_and_cov_send_their_statistic_as_it_is_as_pyspark(mock_connect):
+    # As PySpark's corr and cov, which take the first value of _to_table() of 
their statistic:
+    # the root of the plan is the statistic, with no limit over it, and no 
setting is read.
+    import pyspark.sql.connect.proto as pb2
+
+    spark, service = mock_connect
+    df = spark.range(3)
+    before = len(service.rpc_events)
+    for stat in (df.corr, df.cov, df.stat.corr, df.stat.cov):
+        stat("id", "id")
+    roots = 
[pb2.ExecutePlanRequest.FromString(request).plan.root.WhichOneof("rel_type")
+             for request in service.execute_requests]
+    assert roots == ["corr", "cov", "corr", "cov"]
+    assert service.rpc_events[before:] == ["execute"] * 4
+
+
 def 
test_session_id_of_any_uuid_version_and_the_user_id_of_the_requests(monkeypatch,
 mock_connect):
     # A session_id is any UUID, as uuid.UUID(session_id, version=4) takes it, 
and is sent as
     # given. The user ID of each request is SPARK_USER, else USER, as PySpark 
sets it.
@@ -3001,6 +3029,58 @@ def 
test_binary_subclasses_are_sent_as_the_bytes_of_pyspark(mock_connect):
     assert table.column(0).to_pylist() == [[b"other", None]]
 
 
+def 
test_binary_literals_of_subclasses_are_sent_as_the_bytes_of_pyspark(mock_connect):
+    # As PySpark's LiteralExpression.to_plan, which sends bytes(value): the 
__bytes__ of a
+    # subclass of bytes or bytearray, not its buffer, in lit, in the values of 
the functions and
+    # of the Column methods, in the elements of a typed array, and in the 
arguments of sql.
+    import pyspark.sql.connect.proto as pb2
+    from pyspark.sql import functions as F
+
+    class Bytes(bytes):
+        def __bytes__(self):
+            return b"other"
+
+    class ByteArray(bytearray):
+        def __bytes__(self):
+            return b"other"
+
+    class NotBytes(bytes):
+        def __bytes__(self):
+            return "x"
+
+    def sent(column):
+        return column._expr.to_plan(None)
+
+    assert sent(F.lit(Bytes(b"orig"))).literal.binary == b"other"
+    assert sent(F.lit(ByteArray(b"orig"))).literal.binary == b"other"
+    assert sent(F.lit(bytearray(b"ba"))).literal.binary == b"ba"
+    isin = sent(F.col("b").isin(Bytes(b"orig"))).unresolved_function
+    assert isin.arguments[1].literal.binary == b"other"
+    when = sent(F.when(F.lit(True), ByteArray(b"orig"))).unresolved_function
+    assert when.arguments[1].literal.binary == b"other"
+    entry = sent(F.create_map(F.lit("k"), 
F.lit(Bytes(b"orig")))).unresolved_function
+    assert entry.arguments[1].literal.binary == b"other"
+    # The first element of a typed array is the literal of its value, and the 
others are
+    # literals of its type.
+    for values in ([Bytes(b"orig"), b"b", ByteArray(b"orig")], [b"b", 
Bytes(b"orig")]):
+        array = sent(F.when(F.lit(False), 
F.lit(None)).otherwise(values)).unresolved_function
+        elements = array.arguments[2].literal.array.elements
+        assert [e.binary for e in elements] == [bytes(value) for value in 
values]
+    # The error of bytes(); PySpark raises it once it sends the plan, and this 
client once it
+    # builds the literal.
+    with pytest.raises(TypeError, match="__bytes__ returned non-bytes"):
+        F.lit(NotBytes(b"a"))
+
+    spark, service = mock_connect
+    spark.sql("SELECT :x", args={"x": Bytes(b"orig")})
+    request = pb2.ExecutePlanRequest.FromString(service.execute_requests[-1])
+    named = request.plan.command.sql_command.input.sql.named_arguments
+    assert named["x"].literal.binary == b"other"
+    spark.sql("SELECT ?", args=[ByteArray(b"orig")])
+    request = pb2.ExecutePlanRequest.FromString(service.execute_requests[-1])
+    assert 
request.plan.command.sql_command.input.sql.pos_arguments[0].literal.binary == 
b"other"
+
+
 def test_time_values_are_sent_as_pyspark(mock_connect):
     # As PySpark: a datetime.time is of TimeType(), and createDataFrame sends 
it as PyArrow's
     # time64[ns] of the value, which takes the nanoseconds of an int too, and 
lit() of it is
@@ -15556,6 +15636,88 @@ def 
test_local_rows_raise_the_error_of_a_converter_before_that_of_pyarrow(
     assert message in str(e.value)
 
 
+def 
test_local_rows_raise_the_first_error_of_the_arrow_schema_depth_first_as_pyspark(
+    mock_connect,
+):
+    # As PySpark's to_arrow_schema, which builds the Arrow fields one at a 
time, depth first, each
+    # once its type is built: the first of a type that Arrow has no type of 
and of a null type
+    # field that is not nullable, as a map key never is, raises. A 
user-defined type is built as
+    # its SQL type.
+    from pyspark.errors import PySparkTypeError
+
+    class YearMonthUDT(T.UserDefinedType):
+        @classmethod
+        def sqlType(cls):
+            return T.YearMonthIntervalType()
+
+        @classmethod
+        def module(cls):
+            return __name__
+
+        def serialize(self, obj):
+            return obj
+
+        def deserialize(self, datum):
+            return datum
+
+    def struct(*fields):
+        return T.StructType([T.StructField(name, data_type) for name, 
data_type in fields])
+
+    ym, void = T.YearMonthIntervalType(), T.NullType()
+    spark, _ = mock_connect
+    for rows, schema, error in [
+        ([(None, None)], "a interval year to month, b void not null", 
"YearMonthIntervalType(0, 1)"),
+        ([(None, None)], "a void not null, b interval year to month", 
ValueError),
+        ([(None,)], "a struct<x: interval year to month, y: void not null>",
+         "YearMonthIntervalType(0, 1)"),
+        ([(None, None)], "a struct<x: void not null>, b interval year to 
month", ValueError),
+        ([(None, None)], struct(("a", T.ArrayType(void, False)), ("b", 
T.CharType(3))), ValueError),
+        ([(None,)], struct(("a", T.ArrayType(T.ArrayType(ym), False))),
+         "YearMonthIntervalType(0, 1)"),
+        ([(None,)], struct(("a", T.MapType(void, ym))), ValueError),
+        ([(None,)], struct(("a", T.MapType(ym, void, False))), 
"YearMonthIntervalType(0, 1)"),
+        ([(None, None)], T.StructType([T.StructField("a", YearMonthUDT()),
+                                       T.StructField("b", void, False)]),
+         "YearMonthIntervalType(0, 1)"),
+    ]:
+        with pytest.raises((PySparkTypeError, ValueError)) as e:
+            spark.createDataFrame(rows, schema)
+        if error is ValueError:
+            assert type(e.value) is ValueError, schema
+            assert str(e.value) == "A null type field may not be non-nullable"
+        else:
+            assert type(e.value) is PySparkTypeError, schema
+            assert e.value.getCondition() == 
"UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION"
+            assert e.value.getMessageParameters() == {"data_type": error}
+
+
+def 
test_an_array_of_no_converter_takes_the_values_that_pyarrow_takes_as_pyspark(mock_connect):
+    # As PyArrow's list conversion of a value that PySpark passes as it is: a 
sequence, a set or
+    # a dict_values is a list, and another iterable, such as a generator, an 
iterator, a
+    # frozenset, a dict_keys or a dict_items, is not a sequence, an error that 
waits for the
+    # converters of the other columns.
+    import pyarrow as pa
+
+    spark, service = mock_connect
+    d = {1: 2}
+    for value in (lambda: (i for i in [1]), lambda: iter([1]), d.keys, d.items,
+                  lambda: frozenset([1])):
+        with pytest.raises(pa.ArrowTypeError) as e:
+            spark.createDataFrame([(value(),)], "a array<int>")
+        assert str(e.value).endswith(
+            f"with type {type(value()).__name__}: was not a sequence or 
recognized null for "
+            "conversion to list type"
+        )
+        with pytest.raises(AssertionError):
+            spark.createDataFrame([(value(), 0)], "a array<int>, b timestamp")
+
+    df = spark.createDataFrame([(range(2),), ({1, 2},), (d.values(),), 
((3,),)], "a array<int>")
+    df.columns
+    relation = _sent_relation(service.analyze_requests[-1], 11)
+    table = pa.ipc.open_stream(relation[1][0]).read_all()
+    assert table.column(0).to_pylist() == [[0, 1], [1, 2], [2], [3]]
+
+
 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]

Reply via email to