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 ed2c61ff [SPARK-61367][CONNECT] Match PySpark and the server in the 
Rust API's pivot literals, year-month intervals, range repartitions, sample_by 
strata, DDL, Arrow batch checks, release_session, listener panics and handler 
threads
ed2c61ff is described below

commit ed2c61ff59ff5415a9964d8f75a38c8acb1ae21a
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 06:51:27 2026 +0900

    [SPARK-61367][CONNECT] Match PySpark and the server in the Rust API's pivot 
literals, year-month intervals, range repartitions, sample_by strata, DDL, 
Arrow batch checks, release_session, listener panics and handler threads
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61367](https://issues.apache.org/jira/browse/SPARK-61367): 
low-priority findings of a review of the Rust API (`crates/spark-connect`), 
each checked against official PySpark 4.3.0, the server or the Scala client 
with probes.
    
    - **pivot** (`group.rs`):
      - Float, Byte and Short values are sent as literals of their own types. 
Their columns are then named as by the pivot without values: `1.1`, not 
`1.100000023841858`.
      - Its `NOT_EXPECTED_TYPE` names the types that the Rust API takes.
    - **Year-month intervals:** `Value::YearMonthInterval(i32)` and 
`LiteralExpression::YearMonthInterval(i32)`, of months, as `DayTimeInterval` 
for day-time intervals. This covers Arrow decoding, literals, rendering, 
Display, pivot, NA fills and `create_dataframe`.
      - A pivot on collected values names the column `INTERVAL '1-0' YEAR TO 
MONTH`, as the server does.
      - The drop-in raises `NOT_IMPLEMENTED` for one as PySpark does 
(`crates/pyspark-rs/src/row.rs`).
    - **`repartition_by_range`, `repartition_by_range_opt`** and 
**`StatFunctions::sample_by`** return a `Result`:
      - the first two raise `VALUE_NOT_POSITIVE`, then `CANNOT_BE_EMPTY`, as 
PySpark;
      - `sample_by` raises `DISALLOWED_TYPE_FOR_CONTAINER` for a stratum that 
is not a literal.
    - **`DataType::from_ddl`** takes whitespace around angle brackets (`array 
<int>`, `STRUCT <a:int>`), as the server's parser does. Its doc says that 
`timestamp` is TIMESTAMP_LTZ.
    - **Arrow batches** (`arrow_chunks.rs`):
      - Each batch of a result is checked for its `start_offset` and its row 
count, with PySpark's messages.
      - The buffer of a chunked batch is reserved once.
    - **`SparkSession::release_session`** after `stop()` or `close()` raises 
`NO_ACTIVE_SESSION` and sends nothing, as PySpark's `_stub`.
    - **Streaming listeners** (`streaming.rs`): a native listener's panic on an 
event of the bus is reported, and the other listeners still get the event, as 
PySpark's `post_to_all` isolates each listener. A returned error, or a panic of 
an adapter, still ends the subscription.
    - **Progress handlers** (`progress.rs`): the synchronous loops await each 
response and then call the handlers on the calling thread 
(`ExecutionStream::next_message`), as PySpark calls them on the iterating 
thread. Before, in a `current_thread` runtime, they ran on a helper thread.
    - **Invalid UTF-8** of a struct or map column is found field by field, keys 
before values, as PySpark's conversion reports it.
    - **Plan depth** (`plan.rs`):
      - A `Raw` relation (a plan of `pyspark.ml`) counts its levels for the 
depth bound (`LogicalPlan::Raw { depth }`).
      - Cloning one clones on a grown stack: at the bound, it overflowed a 
small stack.
      - `LogicalPlan::try_to_proto` serializes within the bound. `to_proto` 
stays infallible, and its doc says so.
    - **Docs** (`docs/compatibility.md`, `DataFrame::is_local`):
      - `impl Drop for LogicalPlan` makes moving a field out of an owned plan a 
compile error (E0509).
      - `is_local()` is a client-side guess; `is_local_on_server()` asks the 
server.
    
    ### Why are the changes needed?
    
    Each was a difference from PySpark 4.3.0 or the server:
    - **Silent wrong results:**
      - the pivot names;
      - a server round-robin split for `repartition_by_range` with no columns;
      - an unset stratum for `sample_by`;
      - a `String` for a collected year-month interval.
    - **Errors where PySpark's client accepts or checks:**
      - `from_ddl` rejected whitespace before `<`;
      - no check of the batches;
      - a ReleaseSession sent after `stop()`.
    - **Behavior:** one listener's panic ended the subscription of all of them; 
the handlers ran on another thread.
    - **A crash and a gap:** cloning a `Raw` relation at the bound crashed with 
a stack overflow, and its levels were not counted.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, all of the above. Public Rust API changes, with migration paragraphs 
in `docs/compatibility.md`:
    - **New enum variants:** `Value::YearMonthInterval` and 
`LiteralExpression::YearMonthInterval`.
    - **New field and method:** the field `LogicalPlan::Raw { depth }`; 
`LogicalPlan::try_to_proto`.
    - **Now return `Result`:** `repartition_by_range`, 
`repartition_by_range_opt` and `StatFunctions::sample_by`.
    
    ### How was this patch tested?
    
    Each new test fails without its change.
    
    - Rust unit tests:
      - `group.rs`: 
`pivot_floats_bytes_shorts_and_year_month_intervals_keep_their_types` and 
`sample_by_rejects_a_stratum_that_is_not_a_literal_as_pyspark`.
      - `dataframe.rs`: `year_month_interval_is_the_signed_months_of_it`, 
`repartition_by_range_rejects_no_columns_and_a_count_that_is_not_positive_as_pyspark`
 and `invalid_utf8_of_a_nested_column_is_found_field_by_field_as_pyspark`.
      - `types.rs`: 
`from_ddl_takes_whitespace_around_angle_brackets_as_the_server`. Its 14 
spellings were checked against the server's parser.
      - `session.rs`: 
`release_session_of_a_stopped_session_raises_no_active_session_as_pyspark`.
      - `arrow_chunks.rs`: offset, row count and reserve.
      - `streaming.rs`: 
`a_panicking_native_listener_on_an_event_of_the_bus_is_isolated_as_pyspark` and 
`a_panicking_adapter_fails_the_subscription_like_an_error`.
      - `plan.rs`: the levels of a `Raw` relation, a `Raw` at the bound on a 
small stack, and `try_to_proto`.
    - Live Rust (`crates/spark-connect/tests/e2e_dataframe.rs`), against a 
local Spark 4.3.0 server:
      - 
`pivot_values_of_floats_and_year_month_intervals_match_discovered_pivots`
      - `year_month_interval_values_roundtrip`
      - `progress_handlers_run_on_the_calling_thread_inside_a_tokio_runtime`
    - Offline Python (`python/tests/test_dropin_offline.py`, placed before 
`test_row_iteration`):
      - 
`test_collect_checks_the_rows_and_the_offset_of_each_arrow_batch_as_pyspark`
      - 
`test_invalid_utf8_of_a_struct_column_is_raised_field_by_field_as_pyspark`
      - 
`test_client_release_session_after_stop_raises_no_active_session_as_pyspark`
    - The probes (official PySpark 4.3.0 against ours) now agree:
      - 25 year-month interval cases of the drop-in;
      - `VectorAssembler.transform` of deep DataFrames at and past the bound;
      - every invalid UTF-8 action but `toArrow` and `toPandas`, a documented 
difference.
    - Checks:
      - the lib tests of both crates (745 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;
      - the live `e2e_dataframe`, `e2e_ops_breadth`, `e2e_session_catalog`, 
`e2e_streaming` and `e2e_reattach_drop`;
      - targeted offline and live Python selections, and 
`test_arrow_handoff.py` and the ML suites. The full Python suites run in the 
trial 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 #472 from HyukjinKwon/p3-rust.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/dataframe.rs            |  14 +-
 crates/pyspark-rs/src/functions.rs            |   5 +
 crates/pyspark-rs/src/row.rs                  |  13 ++
 crates/pyspark-rs/src/session.rs              |   5 +
 crates/pyspark-rs/src/stat.rs                 |   9 +-
 crates/spark-connect/src/arrow_chunks.rs      | 226 ++++++++++++++++++-
 crates/spark-connect/src/catalog.rs           |   3 +-
 crates/spark-connect/src/dataframe.rs         | 307 ++++++++++++++++++--------
 crates/spark-connect/src/expression.rs        |   8 +
 crates/spark-connect/src/group.rs             | 124 ++++++++++-
 crates/spark-connect/src/pipelines.rs         |   3 +-
 crates/spark-connect/src/plan.rs              | 287 +++++++++++++++++++++---
 crates/spark-connect/src/progress.rs          |  28 ++-
 crates/spark-connect/src/row.rs               |  11 +
 crates/spark-connect/src/session.rs           |  49 +++-
 crates/spark-connect/src/streaming.rs         | 121 +++++++---
 crates/spark-connect/src/types.rs             | 107 ++++++---
 crates/spark-connect/tests/e2e_dataframe.rs   | 205 +++++++++++++++++
 crates/spark-connect/tests/e2e_new_methods.rs |   1 +
 crates/spark-connect/tests/e2e_ops_breadth.rs |   1 +
 docs/compatibility.md                         |  39 ++++
 python/tests/test_dropin_offline.py           |  85 +++++++
 22 files changed, 1435 insertions(+), 216 deletions(-)

diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index 6cd6f1f3..87ffa1e6 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -1247,7 +1247,8 @@ impl PyDataFrame {
             .collect();
         Ok(PyDataFrame::new(
             self.dataframe
-                .repartition_by_range_opt(num_partitions, exprs),
+                .repartition_by_range_opt(num_partitions, exprs)
+                .to_pyerr()?,
         ))
     }
 
@@ -1918,11 +1919,12 @@ impl PyDataFrame {
             Some(seed) => seed,
             None => python_random_seed(py)?,
         };
-        Ok(PyDataFrame::new(self.dataframe.stat().sample_by(
-            col,
-            fractions,
-            Some(seed),
-        )))
+        Ok(PyDataFrame::new(
+            self.dataframe
+                .stat()
+                .sample_by(col, fractions, Some(seed))
+                .to_pyerr()?,
+        ))
     }
 
     /// Replace values, as PySpark's `DataFrame.replace`: `to_replace` is a 
{old: new} dict, or
diff --git a/crates/pyspark-rs/src/functions.rs 
b/crates/pyspark-rs/src/functions.rs
index c903728d..b7a33511 100644
--- a/crates/pyspark-rs/src/functions.rs
+++ b/crates/pyspark-rs/src/functions.rs
@@ -476,6 +476,11 @@ fn literal_data_type(literal: &LiteralExpression) -> 
spark_connect::types::DataT
             start_field: 0,
             end_field: 3,
         },
+        // Not of a Python value, which has no year-month interval type.
+        LiteralExpression::YearMonthInterval(_) => DataType::YearMonthInterval 
{
+            start_field: 0,
+            end_field: 1,
+        },
         LiteralExpression::Time { precision, .. } => DataType::Time {
             precision: *precision,
         },
diff --git a/crates/pyspark-rs/src/row.rs b/crates/pyspark-rs/src/row.rs
index 1c942cc1..07c517d9 100644
--- a/crates/pyspark-rs/src/row.rs
+++ b/crates/pyspark-rs/src/row.rs
@@ -284,6 +284,19 @@ fn value_to_py<'py>(
                 remainder % 1_000_000,
             ))?
         }
+        // As PySpark's conversion of the rows, which cannot collect a 
year-month interval (the
+        // collects raise this already from the schema of the result).
+        Value::YearMonthInterval(_) => {
+            return Err(crate::column::raise_pyspark(
+                py,
+                "PySparkNotImplementedError",
+                "NOT_IMPLEMENTED",
+                &[(
+                    "feature",
+                    "Collecting a year-month interval value in Spark Connect",
+                )],
+            ))
+        }
         Value::Decimal { value, .. } => {
             // Convert to Python decimal.Decimal by instantiating the class
             let decimal_mod = py.import("decimal")?;
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index c10f8bdb..1268dbe4 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -3550,6 +3550,11 @@ fn value_to_datatype(v: &Value) -> DataType {
             start_field: 0,
             end_field: 3,
         },
+        // Not of a Python value, which has no year-month interval type.
+        Value::YearMonthInterval(_) => DataType::YearMonthInterval {
+            start_field: 0,
+            end_field: 1,
+        },
         Value::Decimal {
             precision, scale, ..
         } => DataType::Decimal {
diff --git a/crates/pyspark-rs/src/stat.rs b/crates/pyspark-rs/src/stat.rs
index d64f555c..495b6368 100644
--- a/crates/pyspark-rs/src/stat.rs
+++ b/crates/pyspark-rs/src/stat.rs
@@ -4,6 +4,7 @@ use pyo3::prelude::*;
 use spark_connect::group::StatFunctions;
 
 use crate::dataframe::{python_random_seed, PyDataFrame};
+use crate::errors::ResultExt;
 
 /// Python wrapper for DataFrame statistical functions.
 #[pyclass(
@@ -90,11 +91,9 @@ impl PyStatFunctions {
             Some(seed) => seed,
             None => python_random_seed(py)?,
         };
-        Ok(PyDataFrame::new(self.stat.sample_by(
-            col,
-            fractions,
-            Some(seed),
-        )))
+        Ok(PyDataFrame::new(
+            self.stat.sample_by(col, fractions, Some(seed)).to_pyerr()?,
+        ))
     }
 
     /// Approximate quantiles of a column, or of each of a list or tuple of 
columns, at the
diff --git a/crates/spark-connect/src/arrow_chunks.rs 
b/crates/spark-connect/src/arrow_chunks.rs
index 52795024..7dfb2537 100644
--- a/crates/spark-connect/src/arrow_chunks.rs
+++ b/crates/spark-connect/src/arrow_chunks.rs
@@ -4,6 +4,8 @@
 //! The execution asks for chunking, so the server splits a batch too large 
for one message into
 //! chunks, sent in order, each with its index and the number of chunks of the 
batch. A chunk is
 //! part of the Arrow stream of its batch, so the chunks are joined before the 
batch is decoded.
+//! As PySpark's, each batch must start at the row where the rows before it 
end, and hold the
+//! rows that it counts.
 
 use spark_connect_core::error::{Result, SparkError};
 use spark_connect_proto as proto;
@@ -12,6 +14,8 @@ use spark_connect_proto as proto;
 #[derive(Default)]
 pub(crate) struct ArrowChunkAssembler {
     pending: Option<PendingBatch>,
+    /// The rows of the batches of the execution so far, at which the next 
batch starts.
+    num_records: i64,
 }
 
 struct PendingBatch {
@@ -46,23 +50,41 @@ impl ArrowChunkAssembler {
         let index = batch.chunk_index.unwrap_or(0);
         let mut pending = match self.pending.take() {
             None => {
+                // As PySpark's: the offset of the next batch, then its first 
chunk.
+                if let Some(offset) = batch.start_offset.filter(|&o| o != 
self.num_records) {
+                    return Err(SparkError::connect_msg(format!(
+                        "Expected arrow batch to start at row offset {} in 
results, but received \
+                         arrow batch starting at offset {offset}.",
+                        self.num_records
+                    )));
+                }
                 if index != 0 {
                     return Err(SparkError::connect_msg(format!(
                         "Expected chunk index 0 of the next arrow batch but 
got {index}."
                     )));
                 }
                 if num_chunks == 1 {
+                    self.count_rows(&batch)?;
                     response.response_type = Some(
                         
proto::execute_plan_response::ResponseType::ArrowBatch(batch),
                     );
                     return Ok(());
                 }
+                // The chunks but the last are as large as the first, so this 
holds the batch. A
+                // size that cannot be reserved, of a count that the server 
got wrong, is left to
+                // grow with the chunks instead.
+                let mut data = Vec::new();
+                let _ = data.try_reserve_exact(
+                    usize::try_from(num_chunks)
+                        .unwrap_or(usize::MAX)
+                        .saturating_mul(batch.data.len()),
+                );
                 PendingBatch {
                     row_count: batch.row_count,
                     start_offset: batch.start_offset,
                     num_chunks,
                     received: 0,
-                    data: Vec::new(),
+                    data,
                 }
             }
             Some(pending) => {
@@ -88,18 +110,44 @@ impl ArrowChunkAssembler {
             self.pending = Some(pending);
             return Ok(());
         }
+        let batch = proto::execute_plan_response::ArrowBatch {
+            row_count: pending.row_count,
+            data: pending.data.into(),
+            start_offset: pending.start_offset,
+            chunk_index: None,
+            num_chunks_in_batch: None,
+        };
+        self.count_rows(&batch)?;
         response.response_type = 
Some(proto::execute_plan_response::ResponseType::ArrowBatch(
-            proto::execute_plan_response::ArrowBatch {
-                row_count: pending.row_count,
-                data: pending.data.into(),
-                start_offset: pending.start_offset,
-                chunk_index: None,
-                num_chunks_in_batch: None,
-            },
+            batch,
         ));
         Ok(())
     }
 
+    /// Check the rows of the whole batch `batch` against its row count, with 
PySpark's error, and
+    /// count them for the offset of the next batch. The rows are those of all 
the record batches
+    /// of its Arrow stream, which the row count counts; PySpark compares the 
count after each
+    /// record batch, the same for the one record batch of a batch that the 
server sends. They are
+    /// read from the headers of the messages of the stream; a stream whose 
messages cannot be
+    /// read is left to the decoder of the batch, which reports it.
+    fn count_rows(&mut self, batch: &proto::execute_plan_response::ArrowBatch) 
-> Result<()> {
+        // As PySpark's, which checks as it reads the record batches, a stream 
of none is not.
+        let Some(record_batches) = record_batch_rows(&batch.data).filter(|b| 
!b.is_empty()) else {
+            return Ok(());
+        };
+        let rows = record_batches
+            .into_iter()
+            .fold(0i64, |rows, record_batch| 
rows.saturating_add(record_batch));
+        if rows != batch.row_count {
+            return Err(SparkError::connect_msg(format!(
+                "Expected {} rows in arrow batch but got {rows}.",
+                batch.row_count
+            )));
+        }
+        self.num_records = self.num_records.saturating_add(rows);
+        Ok(())
+    }
+
     /// The next response of an execution as it is returned: `push` of a 
response, and `finish` at
     /// the end of the stream, where `response` is `None`.
     pub(crate) fn join(
@@ -126,6 +174,42 @@ impl ArrowChunkAssembler {
     }
 }
 
+/// The rows of each record batch of the Arrow IPC stream `data`, in order, 
from the headers of
+/// its messages, without reading their buffers; `None` if `data` is not such 
a stream. An empty
+/// `data` has no record batch, as the decoders of a batch read it.
+fn record_batch_rows(data: &[u8]) -> Option<Vec<i64>> {
+    let word = |at: usize| -> Option<i32> {
+        Some(i32::from_le_bytes(
+            data.get(at..at.checked_add(4)?)?.try_into().ok()?,
+        ))
+    };
+    let mut rows = Vec::new();
+    let mut at = 0;
+    // Each message: a continuation marker (absent in the legacy format), the 
length of its
+    // metadata, the metadata, then its body; a length of 0, or the end of the 
data, ends it.
+    while at < data.len() {
+        let mut length = word(at)?;
+        at += 4;
+        if length == -1 {
+            length = word(at)?;
+            at += 4;
+        }
+        if length == 0 {
+            break;
+        }
+        let end = at.checked_add(usize::try_from(length).ok()?)?;
+        let message = arrow::ipc::root_as_message(data.get(at..end)?).ok()?;
+        if let Some(record_batch) = message.header_as_record_batch() {
+            rows.push(record_batch.length());
+        }
+        at = end.checked_add(usize::try_from(message.bodyLength()).ok()?)?;
+        if at > data.len() {
+            return None;
+        }
+    }
+    Some(rows)
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -137,7 +221,8 @@ mod tests {
             response_type: Some(ResponseType::ArrowBatch(ArrowBatch {
                 row_count: rows,
                 data: data.to_vec().into(),
-                start_offset: (index == 0).then_some(5),
+                // The first batch of an execution starts at its first row.
+                start_offset: (index == 0).then_some(0),
                 chunk_index: Some(index),
                 num_chunks_in_batch: Some(total),
             })),
@@ -168,7 +253,7 @@ mod tests {
         let batch = batch_of(&last).expect("the whole batch");
         assert_eq!(&batch.data[..], b"abcdef");
         assert_eq!(batch.row_count, 7);
-        assert_eq!(batch.start_offset, Some(5));
+        assert_eq!(batch.start_offset, Some(0));
         assert_eq!(batch.chunk_index, None);
         assert_eq!(batch.num_chunks_in_batch, None);
     }
@@ -290,4 +375,125 @@ mod tests {
             "The execution ended after 1 of 3 chunks of an arrow batch."
         );
     }
+
+    /// The Arrow IPC stream of a record batch of each of `rows` rows, as the 
server sends a batch.
+    fn ipc(rows: &[i64]) -> Vec<u8> {
+        use arrow::array::{ArrayRef, Int64Array};
+        use arrow::record_batch::RecordBatch;
+        let batches: Vec<RecordBatch> = rows
+            .iter()
+            .map(|&n| {
+                let ids: ArrayRef = 
std::sync::Arc::new(Int64Array::from_iter_values(0..n));
+                RecordBatch::try_from_iter([("id", ids)]).unwrap()
+            })
+            .collect();
+        let mut out = Vec::new();
+        let mut writer =
+            arrow::ipc::writer::StreamWriter::try_new(&mut out, 
&batches[0].schema()).unwrap();
+        for batch in &batches {
+            writer.write(batch).unwrap();
+        }
+        writer.finish().unwrap();
+        drop(writer);
+        out
+    }
+
+    /// A whole batch of `rows` rows in `data`, starting at the row `offset` 
of the result.
+    fn whole(rows: i64, offset: Option<i64>, data: Vec<u8>) -> 
proto::ExecutePlanResponse {
+        proto::ExecutePlanResponse {
+            response_type: Some(ResponseType::ArrowBatch(ArrowBatch {
+                row_count: rows,
+                data: data.into(),
+                start_offset: offset,
+                chunk_index: None,
+                num_chunks_in_batch: None,
+            })),
+            ..Default::default()
+        }
+    }
+
+    /// As PySpark's `handle_response`: a batch starts at the row where the 
rows of the batches
+    /// before it end, if it says where it starts.
+    #[test]
+    fn 
a_batch_that_starts_elsewhere_than_after_the_rows_before_it_is_an_error_as_pyspark()
 {
+        let mut assembler = ArrowChunkAssembler::default();
+        assembler.push(&mut whole(3, Some(0), ipc(&[3]))).unwrap();
+        let error = assembler
+            .push(&mut whole(2, Some(2), ipc(&[2])))
+            .unwrap_err();
+        assert_eq!(
+            error.message(),
+            "Expected arrow batch to start at row offset 3 in results, but 
received arrow batch \
+             starting at offset 2."
+        );
+        // A batch that does not say where it starts is not checked, and its 
rows count.
+        assembler.push(&mut whole(2, None, ipc(&[2]))).unwrap();
+        assembler.push(&mut whole(1, Some(5), ipc(&[1]))).unwrap();
+        // The offset of a chunked batch is that of its first chunk, checked 
before its index.
+        let mut first = chunk(1, 2, 1, b"x");
+        if let Some(ResponseType::ArrowBatch(batch)) = 
first.response_type.as_mut() {
+            batch.start_offset = Some(0);
+        }
+        let error = assembler.push(&mut first).unwrap_err();
+        assert!(
+            error
+                .message()
+                .starts_with("Expected arrow batch to start at row offset 6"),
+            "{error}"
+        );
+    }
+
+    /// As PySpark's: the rows of the record batches of a batch, counted as 
each is read, are the
+    /// row count of the batch, for a whole batch and for the chunks of one.
+    #[test]
+    fn a_batch_of_other_rows_than_it_counts_is_an_error_as_pyspark() {
+        let mut assembler = ArrowChunkAssembler::default();
+        let error = assembler
+            .push(&mut whole(4, Some(0), ipc(&[3])))
+            .unwrap_err();
+        assert_eq!(error.message(), "Expected 4 rows in arrow batch but got 
3.");
+
+        let data = ipc(&[5]);
+        let (head, tail) = data.split_at(data.len() / 2);
+        let mut assembler = ArrowChunkAssembler::default();
+        assembler.push(&mut chunk(0, 2, 6, head)).unwrap();
+        let error = assembler.push(&mut chunk(1, 2, 6, tail)).unwrap_err();
+        assert_eq!(error.message(), "Expected 6 rows in arrow batch but got 
5.");
+
+        // The count is of all the record batches of the stream, of which the 
server sends one.
+        let mut assembler = ArrowChunkAssembler::default();
+        assembler
+            .push(&mut whole(3, Some(0), ipc(&[0, 2, 1])))
+            .unwrap();
+        let error = assembler
+            .push(&mut whole(4, Some(3), ipc(&[2, 1])))
+            .unwrap_err();
+        assert_eq!(error.message(), "Expected 4 rows in arrow batch but got 
3.");
+
+        // Joined, the chunks of a batch of the rows it counts make it up.
+        let mut assembler = ArrowChunkAssembler::default();
+        assembler.push(&mut chunk(0, 2, 5, head)).unwrap();
+        let mut last = chunk(1, 2, 5, tail);
+        assembler.push(&mut last).unwrap();
+        assert_eq!(&batch_of(&last).unwrap().data[..], &data[..]);
+        assembler.push(&mut whole(0, Some(5), ipc(&[0]))).unwrap();
+    }
+
+    #[test]
+    fn the_data_of_the_chunks_of_a_batch_is_reserved_with_the_first_chunk() {
+        let mut assembler = ArrowChunkAssembler::default();
+        assembler.push(&mut chunk(0, 3, 1, &[7; 100])).unwrap();
+        let pending = assembler.pending.as_ref().expect("a pending batch");
+        assert!(
+            pending.data.capacity() >= 300,
+            "{}",
+            pending.data.capacity()
+        );
+        // A number of chunks that cannot be reserved leaves the data to grow 
with them.
+        let mut assembler = ArrowChunkAssembler::default();
+        assembler
+            .push(&mut chunk(0, i64::MAX, 1, &[7; 100]))
+            .unwrap();
+        assert_eq!(assembler.pending.as_ref().unwrap().data.len(), 100);
+    }
 }
diff --git a/crates/spark-connect/src/catalog.rs 
b/crates/spark-connect/src/catalog.rs
index cf9ba5a2..de52b0b8 100644
--- a/crates/spark-connect/src/catalog.rs
+++ b/crates/spark-connect/src/catalog.rs
@@ -5,7 +5,6 @@
 use std::collections::HashMap;
 
 use spark_connect_core::error::{Result, SparkError};
-use spark_connect_core::runtime::block_on;
 use spark_connect_proto as proto;
 
 use crate::dataframe::{decode_arrow_batch, DataFrame};
@@ -1063,7 +1062,7 @@ impl Catalog {
         // error carries the operation id of the request.
         let mut stream = self.session.execute_plan(request)?;
         let mut rows = vec![];
-        while let Some(resp) = block_on(stream.message())? {
+        while let Some(resp) = stream.next_message()? {
             if let 
Some(proto::execute_plan_response::ResponseType::ArrowBatch(batch)) =
                 resp.response_type
             {
diff --git a/crates/spark-connect/src/dataframe.rs 
b/crates/spark-connect/src/dataframe.rs
index 762236bd..c7599102 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -204,7 +204,7 @@ impl LocalRowIterator {
                 execution_info,
                 execution_recorded,
             } => loop {
-                match block_on(stream.message()) {
+                match stream.next_message() {
                     Ok(Some(mut resp)) => {
                         capture_execution(&mut resp, execution_info, session);
                         if let Err(e) = keep_schema(&mut resp, &self.schema) {
@@ -933,7 +933,7 @@ impl DataFrame {
         let mut info = ExecutionInfo::default();
         let mut invalid_utf8: Option<SparkError> = None;
         loop {
-            let resp = block_on(stream.message())?;
+            let resp = stream.next_message()?;
             let Some(mut resp) = resp else {
                 break;
             };
@@ -1024,7 +1024,7 @@ impl DataFrame {
         let mut schema = None;
         let mut info = ExecutionInfo::default();
         loop {
-            let resp = block_on(stream.message())?;
+            let resp = stream.next_message()?;
             let Some(mut resp) = resp else {
                 break;
             };
@@ -1135,8 +1135,10 @@ impl DataFrame {
         mut relation: proto::Relation,
         owner: Option<Arc<dyn std::any::Any + Send + Sync>>,
     ) -> Result<DataFrame> {
-        crate::plan::resolve_relation(&mut relation)?;
-        Ok(DataFrame::from_raw_relation(session, relation, owner))
+        let depth = crate::plan::resolve_relation_levels(&mut relation)?;
+        Ok(DataFrame::from_raw_relation(
+            session, relation, owner, depth,
+        ))
     }
 
     /// The owners of the relations built outside the core (`from_relation`) 
that this DataFrame
@@ -1185,17 +1187,20 @@ impl DataFrame {
         });
     }
 
-    /// The DataFrame of `relation`, as `from_relation`, of a relation without 
placeholders.
+    /// The DataFrame of `relation`, as `from_relation`, of a relation without 
placeholders, of
+    /// `depth` levels.
     fn from_raw_relation(
         session: SparkSession,
         relation: proto::Relation,
         owner: Option<Arc<dyn std::any::Any + Send + Sync>>,
+        depth: usize,
     ) -> DataFrame {
         DataFrame::new(
             session,
             LogicalPlan::Raw {
                 relation: Box::new(relation),
                 owner: owner.map(crate::plan::RelationOwner),
+                depth,
             },
         )
     }
@@ -1207,7 +1212,8 @@ impl DataFrame {
     #[doc(hidden)]
     pub fn from_sent_relation(session: SparkSession, relation: 
proto::Relation) -> DataFrame {
         let plan_id = relation.common.as_ref().and_then(|common| 
common.plan_id);
-        let dataframe = DataFrame::from_raw_relation(session, relation, None);
+        // A relation decoded from bytes is shallow: prost decodes at most 100 
nested messages.
+        let dataframe = DataFrame::from_raw_relation(session, relation, None, 
1);
         if let Some(plan_id) = plan_id {
             dataframe
                 .session
@@ -1638,19 +1644,41 @@ impl DataFrame {
         DataFrame::new(self.session.clone(), plan)
     }
 
-    /// Repartition this DataFrame by range.
-    pub fn repartition_by_range(&self, num_partitions: i32, columns: 
Vec<Expression>) -> DataFrame {
+    /// Repartition this DataFrame by range of `columns` into `num_partitions` 
partitions.
+    /// Mirrors `DataFrame.repartitionByRange(numPartitions, *cols)`: as 
PySpark's, a count that
+    /// is not positive is a `VALUE_NOT_POSITIVE` error, and no columns a 
`CANNOT_BE_EMPTY` one
+    /// (the server would split the rows round-robin instead).
+    pub fn repartition_by_range(
+        &self,
+        num_partitions: i32,
+        columns: Vec<Expression>,
+    ) -> Result<DataFrame> {
         self.repartition_by_range_opt(Some(num_partitions), columns)
     }
 
     /// Repartition by range on the given columns, with the partition count 
optional: `None`
     /// sends no count, so the server picks it. Mirrors 
`DataFrame.repartitionByRange(col)`
     /// and `repartitionByRange(col, *cols)`, which PySpark sends with 
`numPartitions=None`.
+    /// The errors are those of [`DataFrame::repartition_by_range`].
     pub fn repartition_by_range_opt(
         &self,
         num_partitions: Option<i32>,
         columns: Vec<Expression>,
-    ) -> DataFrame {
+    ) -> Result<DataFrame> {
+        if let Some(n) = num_partitions.filter(|n| *n <= 0) {
+            return Err(SparkError::classed(
+                SparkErrorKind::ValueError,
+                "VALUE_NOT_POSITIVE",
+                &[("arg_name", "numPartitions"), ("arg_value", 
&n.to_string())],
+            ));
+        }
+        if columns.is_empty() {
+            return Err(SparkError::classed(
+                SparkErrorKind::ValueError,
+                "CANNOT_BE_EMPTY",
+                &[("item", "cols")],
+            ));
+        }
         // The server range-partitions only on sort orders, so a plain column 
is sorted
         // ascending, nulls first, as PySpark's `repartitionByRange` does.
         let partition_exprs = columns
@@ -1668,7 +1696,7 @@ impl DataFrame {
             num_partitions,
             partition_exprs,
         };
-        self.with_cached_schema(plan)
+        Ok(self.with_cached_schema(plan))
     }
 
     /// Repartition into `num_partitions` by hashing the given column 
expressions.
@@ -2346,12 +2374,16 @@ impl DataFrame {
         self.session.clone()
     }
 
-    /// Check if this DataFrame is local (collected).
+    /// Whether the plan of this DataFrame is a local relation, as the client 
sees it without
+    /// asking the server: a local relation itself, such as of local rows or 
of the result of a
+    /// command run by `SparkSession::sql`, which the server returned. A local 
relation under
+    /// another plan is not, as `toDF`, which Arrow input with inferred or 
listed column names
+    /// applies, and which the server resolves into a `Project`.
     ///
-    /// Mirrors the server's `Dataset.isLocal`: only a local relation itself 
is local. The
-    /// server resolves `toDF`, which Arrow input with inferred or listed 
column names
-    /// applies, into a `Project`, which is not. The result of a command run by
-    /// `SparkSession::sql` is the local relation the server returned.
+    /// This is a guess of the client, which can differ from the server's 
`Dataset.isLocal`:
+    /// the server resolves the plan first, so `spark.sql("VALUES (1)")`, a 
query that the
+    /// server resolves into a local relation, is local there and not here. 
PySpark's
+    /// `DataFrame.isLocal` asks the server, as 
[`DataFrame::is_local_on_server`] does.
     pub fn is_local(&self) -> bool {
         use proto::relation::RelType;
         match self.plan.as_ref() {
@@ -2652,7 +2684,7 @@ fn execute_command_reporting(
     // capturing any metrics/progress emitted along the way.
     let mut info = ExecutionInfo::default();
     let mut responses = Vec::new();
-    while let Some(mut resp) = block_on(stream.message())? {
+    while let Some(mut resp) = stream.next_message()? {
         capture_execution(&mut resp, &mut info, session);
         responses.push(resp);
     }
@@ -2735,6 +2767,8 @@ fn check_fill_value(value: &Value, arg_name: &str, 
expected_type: &str) -> Resul
         Value::Timestamp(_) | Value::TimestampNtz(_) => "datetime",
         Value::Time(_) => "time",
         Value::DayTimeInterval(_) => "timedelta",
+        // Python has no type of a year-month interval: its Spark type names 
it.
+        Value::YearMonthInterval(_) => "YearMonthInterval",
         Value::Decimal { .. } => "Decimal",
         Value::List(_) => "list",
         Value::Map(_) => "dict",
@@ -2852,16 +2886,16 @@ fn decode_error(data: &[u8], error: 
arrow::error::ArrowError) -> SparkError {
 }
 
 /// 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.
+/// its bytes, in the order in which PySpark converts a result: column by 
column, each batch by
+/// batch, in the order of [`first_invalid_utf8_in`].
 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))
-            })
-        })
+        batches
+            .iter()
+            .find_map(|batch| 
first_invalid_utf8_in(batch.column(column).as_ref()))
+            .map(|value| (column, value))
     })
 }
 
@@ -2960,32 +2994,63 @@ fn binary_type(data_type: &arrow::datatypes::DataType) 
-> arrow::datatypes::Data
     }
 }
 
-/// 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>> {
+/// The bytes of the first binary value of `array` that are not valid UTF-8, 
in the order in which
+/// PySpark's `ArrowTableToRowsConversion._to_pylist` converts an array, in 
bulk: a list by the
+/// values of all its rows, a struct field by field, each over all its rows, 
and a map by the keys
+/// of all its rows, then their values. A null is valid.
+fn first_invalid_utf8_in(array: &dyn arrow::array::Array) -> 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));
+    // The values of the rows of a list or a map, which its offsets delimit in 
its child.
+    let rows_of = |child: &dyn Array, start: usize, end: usize| {
+        first_invalid_utf8_in(child.slice(start, end - start).as_ref())
+    };
     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::Binary => array
+            .as_binary::<i32>()
+            .iter()
+            .flatten()
+            .find_map(invalid_bytes),
+        ArrowDataType::LargeBinary => array
+            .as_binary::<i64>()
+            .iter()
+            .flatten()
+            .find_map(invalid_bytes),
+        ArrowDataType::BinaryView => array
+            .as_binary_view()
+            .iter()
+            .flatten()
+            .find_map(invalid_bytes),
+        ArrowDataType::List(_) => {
+            let list = array.as_list::<i32>();
+            let offsets = list.value_offsets();
+            let (start, end) = (offsets[0] as usize, offsets[list.len()] as 
usize);
+            rows_of(list.values().as_ref(), start, end)
+        }
+        ArrowDataType::LargeList(_) => {
+            let list = array.as_list::<i64>();
+            let offsets = list.value_offsets();
+            let (start, end) = (offsets[0] as usize, offsets[list.len()] as 
usize);
+            rows_of(list.values().as_ref(), start, end)
+        }
+        // A slice of a fixed-size list slices its values.
         ArrowDataType::FixedSizeList(_, _) => {
-            first_in(array.as_fixed_size_list().value(row).as_ref())
+            first_invalid_utf8_in(array.as_fixed_size_list().values().as_ref())
         }
-        ArrowDataType::Map(_, _) => first_in(&array.as_map().value(row)),
+        ArrowDataType::Map(_, _) => {
+            let map = array.as_map();
+            let offsets = map.value_offsets();
+            let (start, end) = (offsets[0] as usize, offsets[map.len()] as 
usize);
+            rows_of(map.keys().as_ref(), start, end)
+                .or_else(|| rows_of(map.values().as_ref(), start, end))
+        }
+        // A slice of a struct slices its fields.
         ArrowDataType::Struct(_) => array
             .as_struct()
             .columns()
             .iter()
-            .find_map(|column| invalid_utf8_in(column.as_ref(), row)),
+            .find_map(|column| first_invalid_utf8_in(column.as_ref())),
         _ => None,
     }
 }
@@ -3425,15 +3490,11 @@ impl<'a> ArrowValueLayout<'a> {
             ArrowValueDecoder::Time32Second(arr) => {
                 Ok(Value::Time(arr.value(index) as i64 * 1_000_000_000))
             }
-            // Intervals likewise have no dedicated Value variant, so render 
as strings.
+            // A year-month interval, the months that the server sends of it.
             ArrowValueDecoder::IntervalYearMonth(arr) => {
-                // The sign goes on the years, as Spark's 
`toYearMonthIntervalString`
-                // does, so -1 month is "-0-1" and not "0-1".
-                let months = arr.value(index) as i64;
-                let sign = if months < 0 { "-" } else { "" };
-                let abs = months.abs();
-                Ok(Value::String(format!("{sign}{}-{}", abs / 12, abs % 12)))
+                Ok(Value::YearMonthInterval(arr.value(index)))
             }
+            // These intervals have no dedicated Value variant, so render as 
strings.
             ArrowValueDecoder::IntervalDayTime(arr) => {
                 let v = arr.value(index);
                 Ok(Value::String(format!(
@@ -3866,6 +3927,66 @@ mod nested_decode_tests {
         assert_eq!(error.invalid_utf8_value(), Some(vec![0xc3, 0x28]));
     }
 
+    /// As PySpark's `_to_pylist` converts a column in bulk: the first invalid 
string of a struct
+    /// is that of its first field with one, over all the rows, and that of a 
map is of its keys
+    /// before its values; a list of structs is a struct of all its values. 
Rows of a slice only.
+    #[test]
+    fn invalid_utf8_of_a_nested_column_is_found_field_by_field_as_pyspark() {
+        let binary = |values: Vec<Option<&[u8]>>| 
Arc::new(BinaryArray::from(values)) as ArrayRef;
+        let ok: &[u8] = b"ok";
+        let two_rows = || {
+            StructArray::from(vec![
+                (
+                    Arc::new(Field::new("x", DataType::Binary, true)),
+                    binary(vec![Some(ok), Some(&[0xc3][..])]),
+                ),
+                (
+                    Arc::new(Field::new("y", DataType::Binary, true)),
+                    binary(vec![Some(&[0x80][..]), Some(ok)]),
+                ),
+            ])
+        };
+        // Row 0 has the invalid y, row 1 the invalid x: x is converted first.
+        assert_eq!(first_invalid_utf8_in(&two_rows()), Some(vec![0xc3]));
+        assert_eq!(
+            first_invalid_utf8_in(&two_rows().slice(0, 1)),
+            Some(vec![0x80])
+        );
+
+        let structs = Arc::new(two_rows()) as ArrayRef;
+        let item = Arc::new(Field::new("item", structs.data_type().clone(), 
true));
+        let lists = ListArray::new(item, OffsetBuffer::from_lengths([1, 1]), 
structs, None);
+        assert_eq!(first_invalid_utf8_in(&lists), Some(vec![0xc3]));
+        assert_eq!(first_invalid_utf8_in(&lists.slice(0, 1)), 
Some(vec![0x80]));
+
+        // Row 0 maps "k" to an invalid value, row 1 has an invalid key: the 
keys come first.
+        let entries = StructArray::from(vec![
+            (
+                Arc::new(Field::new("key", DataType::Binary, false)),
+                binary(vec![Some(&b"k"[..]), Some(&[0xc3][..])]),
+            ),
+            (
+                Arc::new(Field::new("value", DataType::Binary, true)),
+                binary(vec![Some(&[0xfe][..]), Some(&b"v"[..])]),
+            ),
+        ]);
+        let entry = Arc::new(Field::new("entries", 
entries.data_type().clone(), false));
+        let maps = MapArray::new(
+            entry,
+            OffsetBuffer::from_lengths([1, 1]),
+            entries,
+            None,
+            false,
+        );
+        assert_eq!(first_invalid_utf8_in(&maps), Some(vec![0xc3]));
+        assert_eq!(first_invalid_utf8_in(&maps.slice(0, 1)), Some(vec![0xfe]));
+        // A null is valid.
+        assert_eq!(
+            first_invalid_utf8_in(&BinaryArray::from(vec![None, Some(ok)])),
+            None
+        );
+    }
+
     #[test]
     fn 
unsupported_children_remain_lazy_under_nulls_empty_containers_and_variants() {
         let null_duration = DurationSecondArray::from(vec![None]);
@@ -5465,8 +5586,8 @@ mod plan_construction_tests {
             col("id").asc_nulls_last().expression().clone(),
         ];
         let outputs = [
-            df.repartition_by_range(3, inputs.clone()),
-            df.repartition_by_range_opt(None, inputs),
+            df.repartition_by_range(3, inputs.clone()).unwrap(),
+            df.repartition_by_range_opt(None, inputs).unwrap(),
         ];
         for out in &outputs {
             match out.plan.as_ref() {
@@ -5480,6 +5601,46 @@ mod plan_construction_tests {
         }
     }
 
+    /// As PySpark's `repartitionByRange(numPartitions, *cols)`: a count that 
is not positive,
+    /// then no columns, are errors, where the server would split the rows 
round-robin.
+    #[test]
+    fn 
repartition_by_range_rejects_no_columns_and_a_count_that_is_not_positive_as_pyspark()
 {
+        use crate::functions::col;
+
+        let df = session().range(5).unwrap();
+        let id = || vec![col("id").expression().clone()];
+        let error = |result: Result<DataFrame>| result.err().expect("an 
error");
+        for empty in [
+            error(df.repartition_by_range(2, vec![])),
+            error(df.repartition_by_range_opt(None, vec![])),
+        ] {
+            assert_eq!(empty.kind, SparkErrorKind::ValueError);
+            assert_eq!(empty.get_condition().as_deref(), 
Some("CANNOT_BE_EMPTY"));
+            assert_eq!(
+                empty.message(),
+                "[CANNOT_BE_EMPTY] At least one cols must be specified."
+            );
+        }
+        for n in [0, -1] {
+            for result in [
+                df.repartition_by_range(n, id()),
+                df.repartition_by_range(n, vec![]),
+            ] {
+                let not_positive = error(result);
+                assert_eq!(
+                    not_positive.get_condition().as_deref(),
+                    Some("VALUE_NOT_POSITIVE")
+                );
+                assert_eq!(
+                    not_positive.message(),
+                    format!(
+                        "[VALUE_NOT_POSITIVE] Value for `numPartitions` must 
be positive, got '{n}'."
+                    )
+                );
+            }
+        }
+    }
+
     /// Exercise every plan-building builder AND its `plan.to_proto()` arm 
offline
     /// (the gRPC channel connects lazily, so no server is contacted). This 
pins the
     /// large builder set in dataframe.rs and the matching to_proto arms in 
plan.rs.
@@ -5519,7 +5680,7 @@ mod plan_construction_tests {
         ser(&df.except_all(&df2));
         ser(&df.repartition(4));
         ser(&df.coalesce(2));
-        ser(&df.repartition_by_range(3, vec![e()]));
+        ser(&df.repartition_by_range(3, vec![e()]).unwrap());
         ser(&df.hint("broadcast", Vec::<String>::new()));
         ser(&df.to_df(vec!["a"]));
         ser(&df.alias("t"));
@@ -6153,54 +6314,22 @@ mod arrow_value_tests {
     }
 
     #[test]
-    fn interval_types_render_as_string() {
-        assert!(matches!(
-            arrow_value_at(&IntervalYearMonthArray::from(vec![13i32]), 
0).unwrap(),
-            Value::String(_)
-        ));
+    fn interval_types_without_a_value_variant_render_as_string() {
         let dt = IntervalDayTimeArray::from(vec![IntervalDayTime::new(1, 
100)]);
         assert!(matches!(arrow_value_at(&dt, 0).unwrap(), Value::String(_)));
         let mdn = 
IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNano::new(1, 2, 3)]);
         assert!(matches!(arrow_value_at(&mdn, 0).unwrap(), Value::String(_)));
     }
 
+    /// A year-month interval is the months of it, which a pivot sends back as 
the literal of the
+    /// interval, so that the column of the value is named as the pivot 
without values names it.
     #[test]
-    fn year_month_interval_keeps_sign() {
-        let months = [
-            0,
-            1,
-            -1,
-            11,
-            -11,
-            12,
-            -12,
-            13,
-            -13,
-            24,
-            -24,
-            i32::MAX,
-            i32::MIN,
-        ];
-        let expected = [
-            "0-0",
-            "0-1",
-            "-0-1",
-            "0-11",
-            "-0-11",
-            "1-0",
-            "-1-0",
-            "1-1",
-            "-1-1",
-            "2-0",
-            "-2-0",
-            "178956970-7",
-            "-178956970-8",
-        ];
-        for (m, want) in months.into_iter().zip(expected) {
+    fn year_month_interval_is_the_signed_months_of_it() {
+        for months in [0, 1, -1, 12, -13, i32::MAX, i32::MIN] {
             assert_eq!(
-                arrow_value_at(&IntervalYearMonthArray::from(vec![m]), 
0).unwrap(),
-                Value::String(want.to_string()),
-                "months = {m}"
+                arrow_value_at(&IntervalYearMonthArray::from(vec![months]), 
0).unwrap(),
+                Value::YearMonthInterval(months),
+                "months = {months}"
             );
         }
     }
diff --git a/crates/spark-connect/src/expression.rs 
b/crates/spark-connect/src/expression.rs
index 884ae215..a2fdf832 100644
--- a/crates/spark-connect/src/expression.rs
+++ b/crates/spark-connect/src/expression.rs
@@ -674,6 +674,9 @@ pub enum LiteralExpression {
     TimestampNtz(i64),
     /// Signed microseconds in a Spark day-time interval.
     DayTimeInterval(i64),
+    /// Signed months in a Spark year-month interval, which the server reads 
as an interval of
+    /// `YearMonthIntervalType()`, of years to months, as the Scala client 
sends a `Period`.
+    YearMonthInterval(i32),
     Time {
         nano: i64,
         precision: i32,
@@ -725,6 +728,9 @@ impl LiteralExpression {
             LiteralExpression::DayTimeInterval(v) => {
                 proto::expression::literal::LiteralType::DayTimeInterval(*v)
             }
+            LiteralExpression::YearMonthInterval(months) => {
+                
proto::expression::literal::LiteralType::YearMonthInterval(*months)
+            }
             LiteralExpression::Time { nano, precision } => {
                 let mut time = proto::expression::literal::Time::default();
                 time.nano = *nano;
@@ -787,6 +793,8 @@ impl LiteralExpression {
             LiteralExpression::Timestamp(v) => timestamp_repr(*v, true),
             LiteralExpression::TimestampNtz(v) => timestamp_repr(*v, false),
             LiteralExpression::DayTimeInterval(v) => iso_duration(*v),
+            // The value, as `f"{value}"` shows a value of a type that has no 
format of its own.
+            LiteralExpression::YearMonthInterval(months) => months.to_string(),
             LiteralExpression::Time { nano, .. } => time_repr(*nano),
             // A Python list, as `str(list)` shows its elements.
             LiteralExpression::Array { elements, .. } => {
diff --git a/crates/spark-connect/src/group.rs 
b/crates/spark-connect/src/group.rs
index 0043630f..e914f86f 100644
--- a/crates/spark-connect/src/group.rs
+++ b/crates/spark-connect/src/group.rs
@@ -14,19 +14,20 @@ use crate::types::DataType;
 use crate::udf::CommonInlineUserDefinedFunctionExpression;
 
 /// Convert a [`crate::row::Value`] into a literal [`Expression`] of a pivot 
value. Each value
-/// keeps its own type, as the literal of Spark's pivot, and a NULL is an 
error, as PySpark's
-/// `GroupedData.pivot` rejects a None.
+/// keeps its own type, as the literal of Spark's pivot (and of the Scala 
client's `lit`), so a
+/// float is named as the pivot without values names it ("1.1", not the text 
of its double), and
+/// a NULL is an error, as PySpark's `GroupedData.pivot` rejects a None.
 fn value_to_lit_expr(v: crate::row::Value) -> Result<Expression> {
     use crate::expression::LiteralExpression as L;
     use crate::row::Value;
     let lit = match v {
         Value::Null => return Err(not_a_pivot_value("NoneType")),
         Value::Bool(b) => L::boolean(b),
-        Value::Byte(x) => L::int(x as i32),
-        Value::Short(x) => L::int(x as i32),
+        Value::Byte(x) => L::Byte(i32::from(x)),
+        Value::Short(x) => L::Short(i32::from(x)),
         Value::Integer(x) => L::int(x),
         Value::Long(x) => L::long(x),
-        Value::Float(x) => L::double(x as f64),
+        Value::Float(x) => L::Float(x),
         Value::Double(x) => L::double(x),
         Value::String(s) => L::string(s),
         Value::Binary(b) => L::binary(b),
@@ -36,6 +37,7 @@ fn value_to_lit_expr(v: crate::row::Value) -> 
Result<Expression> {
         // `TimeType()` of PySpark has a precision of 6.
         Value::Time(nano) => L::Time { nano, precision: 6 },
         Value::DayTimeInterval(v) => L::DayTimeInterval(v),
+        Value::YearMonthInterval(months) => L::YearMonthInterval(months),
         Value::Decimal {
             value,
             precision,
@@ -60,20 +62,25 @@ fn value_to_lit_expr(v: crate::row::Value) -> 
Result<Expression> {
     Ok(Expression::literal(lit))
 }
 
-/// The `NOT_EXPECTED_TYPE` error of a pivot value of the type `arg_type`, 
which PySpark's
-/// `GroupedData.pivot` rejects (its values are bools, floats, ints and strs), 
named as Python names it.
+/// The `NOT_EXPECTED_TYPE` error of a pivot value of the type `arg_type`, 
named as Python names
+/// it, as PySpark's `GroupedData.pivot` raises it. The expected types are 
those of the values
+/// that the Rust API takes, which are more than PySpark's bools, floats, ints 
and strs.
 fn not_a_pivot_value(arg_type: &str) -> SparkError {
     SparkError::classed(
         SparkErrorKind::TypeError,
         "NOT_EXPECTED_TYPE",
         &[
             ("arg_name", "value"),
-            ("expected_type", "bool, float, int or str"),
+            ("expected_type", PIVOT_VALUE_TYPES),
             ("arg_type", arg_type),
         ],
     )
 }
 
+/// The kinds of the pivot values of the Rust API, as `NOT_EXPECTED_TYPE` 
names them.
+const PIVOT_VALUE_TYPES: &str =
+    "a bool, a number, a string, bytes, a date, a timestamp, a time or an 
interval";
+
 /// The precision and scale of a decimal text, such as `"1.50"` (3 and 2) or 
`"1E+3"` (1 and -3),
 /// as Java's `BigDecimal` of the text has them. Text that is not a decimal 
gives `(10, 0)`, and
 /// the server rejects it.
@@ -685,20 +692,40 @@ impl StatFunctions {
             .unwrap_or(f64::NAN))
     }
 
-    /// Sample by values in a column.
+    /// Sample by values in a column, mirroring 
`DataFrameStatFunctions.sampleBy(col, fractions,
+    /// seed)`: each stratum of `fractions` is a literal, of any type, with 
its fraction. A
+    /// stratum that is not a literal, which the server cannot read, is a
+    /// `DISALLOWED_TYPE_FOR_CONTAINER` error, as PySpark raises for a key of 
another type.
     pub fn sample_by(
         &self,
         col: impl Into<Column>,
         fractions: Vec<(Expression, f64)>,
         seed: Option<i64>,
-    ) -> DataFrame {
+    ) -> Result<DataFrame> {
+        if fractions.iter().any(|(stratum, _)| {
+            !matches!(
+                stratum.node(),
+                crate::expression::ExpressionNode::Literal(_)
+            )
+        }) {
+            return Err(SparkError::classed(
+                SparkErrorKind::TypeError,
+                "DISALLOWED_TYPE_FOR_CONTAINER",
+                &[
+                    ("arg_name", "fractions"),
+                    ("arg_type", "dict"),
+                    ("allowed_types", "literal"),
+                    ("item_type", "Column"),
+                ],
+            ));
+        }
         let plan = LogicalPlan::StatSampleBy {
             input: Arc::clone(&self.dataframe.plan),
             col: col.into().expression().clone(),
             fractions,
             seed,
         };
-        DataFrame::new(self.dataframe.session.clone(), plan)
+        Ok(DataFrame::new(self.dataframe.session.clone(), plan))
     }
 }
 
@@ -1120,6 +1147,48 @@ mod tests {
         }
     }
 
+    /// As the literals of the Scala client's `lit` and of the pivot without 
values: a float, a
+    /// byte, a short and a year-month interval are sent in their own types, 
so that a float is
+    /// named "1.1" and not by the text of its double, and an interval by its 
SQL.
+    #[test]
+    fn pivot_floats_bytes_shorts_and_year_month_intervals_keep_their_types() {
+        use crate::row::Value;
+        use spark_connect_proto::{expression::literal::LiteralType, 
relation::RelType};
+        let frame = session().range(1).unwrap();
+        let pivot = frame
+            .group_by(vec![] as Vec<Column>)
+            .pivot(
+                crate::column::col("value"),
+                Some(vec![
+                    Value::Float(1.1),
+                    Value::Byte(-3),
+                    Value::Short(4),
+                    Value::YearMonthInterval(-13),
+                ]),
+            )
+            .unwrap()
+            .count();
+        let Some(RelType::Aggregate(aggregate)) = 
pivot.plan.to_proto().rel_type else {
+            panic!("expected Aggregate");
+        };
+        let literals: Vec<_> = aggregate
+            .pivot
+            .unwrap()
+            .values
+            .into_iter()
+            .map(|literal| literal.literal_type)
+            .collect();
+        assert_eq!(
+            literals,
+            vec![
+                Some(LiteralType::Float(1.1)),
+                Some(LiteralType::Byte(-3)),
+                Some(LiteralType::Short(4)),
+                Some(LiteralType::YearMonthInterval(-13)),
+            ]
+        );
+    }
+
     #[test]
     fn pivot_values_keep_their_types_as_literals() {
         use crate::row::Value;
@@ -1210,6 +1279,14 @@ mod tests {
             let parameters = err.get_message_parameters().unwrap();
             assert_eq!(parameters["arg_name"], "value");
             assert_eq!(parameters["arg_type"], arg_type);
+            // The types that the Rust API takes, which are more than those of 
PySpark's.
+            assert_eq!(
+                err.message(),
+                format!(
+                    "[NOT_EXPECTED_TYPE] Argument `value` should be a bool, a 
number, a string, \
+                     bytes, a date, a timestamp, a time or an interval, got 
{arg_type}."
+                )
+            );
         }
     }
 
@@ -1280,7 +1357,7 @@ mod tests {
                 0.3,
             ),
         ];
-        let result = stats.sample_by("category", fractions, Some(42));
+        let result = stats.sample_by("category", fractions, Some(42)).unwrap();
         match result.plan.as_ref() {
             LogicalPlan::StatSampleBy {
                 col,
@@ -1295,4 +1372,27 @@ mod tests {
             _ => panic!("expected StatSampleBy plan"),
         }
     }
+
+    /// As PySpark's `sampleBy` rejects a key that is not a float, an int or a 
str: a stratum
+    /// that is not a literal, which the server cannot read, is 
`DISALLOWED_TYPE_FOR_CONTAINER`.
+    #[test]
+    fn sample_by_rejects_a_stratum_that_is_not_a_literal_as_pyspark() {
+        let df = session().range(10).unwrap();
+        let literal = 
Expression::literal(crate::expression::LiteralExpression::Long(1));
+        let error = df
+            .stat()
+            .sample_by(
+                "id",
+                vec![(literal, 0.5), (Expression::column("id"), 0.5)],
+                Some(1),
+            )
+            .err()
+            .expect("an error");
+        assert_eq!(error.kind, SparkErrorKind::TypeError);
+        assert_eq!(
+            error.message(),
+            "[DISALLOWED_TYPE_FOR_CONTAINER] Argument `fractions`(type: dict) 
should only contain \
+             a type in [literal], got Column"
+        );
+    }
 }
diff --git a/crates/spark-connect/src/pipelines.rs 
b/crates/spark-connect/src/pipelines.rs
index c27f4472..f49c58cf 100644
--- a/crates/spark-connect/src/pipelines.rs
+++ b/crates/spark-connect/src/pipelines.rs
@@ -9,7 +9,6 @@
 use std::collections::HashMap;
 
 use spark_connect_core::error::{Result, SparkError};
-use spark_connect_core::runtime::block_on;
 use spark_connect_proto as proto;
 
 use crate::dataframe::{execute_command_collect, DataFrame};
@@ -244,7 +243,7 @@ impl PipelineRunStream {
             // `Progress`: the progress of the run does not reach the progress 
handlers.
             self.stream = Some(self.session.execute_plan_unreported(request)?);
         }
-        block_on(self.stream.as_mut().unwrap().message())
+        self.stream.as_mut().unwrap().next_message()
     }
 }
 
diff --git a/crates/spark-connect/src/plan.rs b/crates/spark-connect/src/plan.rs
index d838bb11..df0e4680 100644
--- a/crates/spark-connect/src/plan.rs
+++ b/crates/spark-connect/src/plan.rs
@@ -131,10 +131,13 @@ pub enum LogicalPlan {
     },
     /// A relation built outside the core, as the plans of `pyspark.ml` build 
theirs
     /// (`pyspark.ml.connect.proto.TransformerRelation`), sent as it is, with 
the plan ID of the
-    /// core, and the owner of the relation, if any, which the plan keeps 
alive.
+    /// core, and the owner of the relation, if any, which the plan keeps 
alive. `depth` is the
+    /// number of levels of the relation as a plan, with those of the plans of 
DataFrames that it
+    /// holds (1 for a relation without them), which count for 
[`MAX_PLAN_DEPTH`].
     Raw {
         relation: Box<proto::Relation>,
         owner: Option<RelationOwner>,
+        depth: usize,
     },
     /// Deduplicate: `df.distinct()` or `df.dropDuplicates()`.
     Deduplicate {
@@ -689,6 +692,20 @@ pub(crate) fn placeholder_relation(node: 
&Arc<LogicalPlan>, ids: &Arc<PlanIds>)
 /// and fetched arguments). Each replacement is the relation of a DataFrame of 
the core, which has
 /// no placeholder.
 pub(crate) fn resolve_relation(relation: &mut proto::Relation) -> Result<()> {
+    resolve_relation_at(relation, 1).map(|_| ())
+}
+
+/// As [`resolve_relation`], and the levels of the relation as a plan of them, 
as PySpark's
+/// serializer counts the levels of a plan of `pyspark.ml`, which serializes 
the plans of its
+/// inputs within its own: one for the relation, one more for each relation 
that holds an input,
+/// and those of the plan of the DataFrame of each placeholder under them.
+pub(crate) fn resolve_relation_levels(relation: &mut proto::Relation) -> 
Result<usize> {
+    resolve_relation_at(relation, 1)
+}
+
+/// Resolve `relation`, which is at the level `level` of the relation being 
resolved, and the
+/// deepest level of its resolved relation.
+fn resolve_relation_at(relation: &mut proto::Relation, level: usize) -> 
Result<usize> {
     if let Some(proto::relation::RelType::Extension(any)) = &relation.rel_type 
{
         if any.type_url == PLACEHOLDER_TYPE_URL {
             let marker = i64::from_le_bytes(
@@ -700,36 +717,45 @@ pub(crate) fn resolve_relation(relation: &mut 
proto::Relation) -> Result<()> {
             let (node, ids) = placeholder_target(marker).ok_or_else(|| {
                 SparkError::value_msg("a placeholder of a DataFrame that no 
longer exists")
             })?;
-            *relation = relation_with_ids(&node, &ids)?;
-            return Ok(());
+            let (resolved, levels) = relation_with_ids_and_levels(&node, 
&ids)?;
+            *relation = resolved;
+            // The relation of the DataFrame takes the place of the 
placeholder, at its level.
+            return Ok(level - 1 + levels);
         }
     }
+    let mut deepest = level;
+    let mut below = |relation: &mut proto::Relation| -> Result<()> {
+        deepest = deepest.max(resolve_relation_at(relation, level + 1)?);
+        Ok(())
+    };
     match relation.rel_type.as_mut() {
         Some(proto::relation::RelType::MlRelation(ml)) => {
             if let Some(summary) = ml.model_summary_dataset.as_mut() {
-                resolve_relation(summary)?;
+                below(summary)?;
             }
             match ml.ml_type.as_mut() {
                 Some(proto::ml_relation::MlType::Transform(transform)) => {
                     if let Some(input) = transform.input.as_mut() {
-                        resolve_relation(input)?;
+                        below(input)?;
                     }
                 }
-                Some(proto::ml_relation::MlType::Fetch(fetch)) => 
resolve_fetch(fetch)?,
+                Some(proto::ml_relation::MlType::Fetch(fetch)) => {
+                    deepest = deepest.max(resolve_fetch_at(fetch, level + 1)?);
+                }
                 None => {}
             }
         }
         Some(proto::relation::RelType::WithRelations(with)) => {
             if let Some(root) = with.root.as_mut() {
-                resolve_relation(root)?;
+                below(root)?;
             }
             for reference in with.references.iter_mut() {
-                resolve_relation(reference)?;
+                below(reference)?;
             }
         }
         _ => {}
     }
-    Ok(())
+    Ok(deepest)
 }
 
 /// Replace the placeholders of the relations of the ML command `command`, as 
`resolve_relation`.
@@ -741,7 +767,9 @@ pub(crate) fn resolve_command(command: &mut proto::Command) 
-> Result<()> {
         Some(proto::ml_command::Command::Fit(fit)) => fit.dataset.as_mut(),
         Some(proto::ml_command::Command::Evaluate(evaluate)) => 
evaluate.dataset.as_mut(),
         Some(proto::ml_command::Command::CreateSummary(summary)) => 
summary.dataset.as_mut(),
-        Some(proto::ml_command::Command::Fetch(fetch)) => return 
resolve_fetch(fetch),
+        Some(proto::ml_command::Command::Fetch(fetch)) => {
+            return resolve_fetch_at(fetch, 1).map(|_| ())
+        }
         _ => None,
     };
     match dataset {
@@ -750,18 +778,20 @@ pub(crate) fn resolve_command(command: &mut 
proto::Command) -> Result<()> {
     }
 }
 
-/// Replace the placeholders of the relations that a fetch of `fetch` takes as 
arguments.
-fn resolve_fetch(fetch: &mut proto::Fetch) -> Result<()> {
+/// Replace the placeholders of the relations that a fetch of `fetch` takes as 
arguments, each at
+/// the level `level`, and the deepest level of them.
+fn resolve_fetch_at(fetch: &mut proto::Fetch, level: usize) -> Result<usize> {
+    let mut deepest = 0;
     for method in fetch.methods.iter_mut() {
         for args in method.args.iter_mut() {
             if let Some(proto::fetch::method::args::ArgsType::Input(input)) =
                 args.args_type.as_mut()
             {
-                resolve_relation(input)?;
+                deepest = deepest.max(resolve_relation_at(input, level)?);
             }
         }
     }
-    Ok(())
+    Ok(deepest)
 }
 
 /// Replace the placeholders of the relation or of the command of `request`, a 
request that a
@@ -784,6 +814,15 @@ pub fn resolve_request(request: &mut 
proto::ExecutePlanRequest) -> Result<()> {
 /// between the two fail there, as they do for PySpark.
 pub const MAX_PLAN_DEPTH: usize = 746;
 
+/// The stack that the clone of a [`LogicalPlan::Raw`] relation takes for each 
of its levels:
+/// prost's `Clone` recurses for each, with frames of about 1 KiB in a release 
build and 4 KiB in a
+/// debug one, and this leaves as much again.
+const RAW_CLONE_STACK_PER_LEVEL: usize = if cfg!(debug_assertions) {
+    8 << 10
+} else {
+    2 << 10
+};
+
 thread_local! {
     /// The level of the plan that this thread serializes now, the plans of 
subqueries
     /// included, and the deepest one since the start of the innermost 
`with_plan_depth_bound`.
@@ -817,8 +856,8 @@ impl Drop for PlanLevel {
 /// Run `serialize`, which serializes plans for a request, and fail as 
PySpark's serializer does
 /// if one of them, with the plans of its subqueries, is deeper than 
[`MAX_PLAN_DEPTH`]. Within
 /// it, a plan is serialized down to the bound only: its proto is dropped and 
encoded by
-/// recursing too, so it must not be deeper.
-fn with_plan_depth_bound<T>(serialize: impl FnOnce() -> T) -> Result<T> {
+/// recursing too, so it must not be deeper. Returns the levels that the plans 
reach.
+fn with_plan_depth_bound<T>(serialize: impl FnOnce() -> T) -> Result<(T, 
usize)> {
     struct Scope {
         outer_bounded: bool,
         outer_deepest: usize,
@@ -833,14 +872,24 @@ fn with_plan_depth_bound<T>(serialize: impl FnOnce() -> 
T) -> Result<T> {
         outer_bounded: PLAN_DEPTH_BOUNDED.with(|bounded| 
bounded.replace(true)),
         outer_deepest: DEEPEST_PLAN_LEVEL.with(|deepest| deepest.replace(0)),
     };
+    let base = PLAN_LEVEL.with(std::cell::Cell::get);
     let value = serialize();
-    if DEEPEST_PLAN_LEVEL.with(std::cell::Cell::get) > MAX_PLAN_DEPTH {
+    let deepest = DEEPEST_PLAN_LEVEL.with(std::cell::Cell::get);
+    if deepest > MAX_PLAN_DEPTH {
         return Err(SparkError::recursion_msg(format!(
             "maximum recursion depth exceeded while serializing a plan and the 
plans of its \
              subqueries; a plan may be at most {MAX_PLAN_DEPTH} levels deep"
         )));
     }
-    Ok(value)
+    Ok((value, deepest.saturating_sub(base)))
+}
+
+/// The `RecursionError` of a plan of `depth` levels, deeper than 
[`MAX_PLAN_DEPTH`].
+fn too_deep_a_plan(depth: usize) -> SparkError {
+    SparkError::recursion_msg(format!(
+        "maximum recursion depth exceeded while serializing a plan of {depth} 
levels; \
+         a plan may be at most {MAX_PLAN_DEPTH} levels deep"
+    ))
 }
 
 /// Serialize a shared plan node for a request: the node and every node below 
it carry
@@ -849,18 +898,25 @@ fn with_plan_depth_bound<T>(serialize: impl FnOnce() -> 
T) -> Result<T> {
 /// a `RecursionError`, as in PySpark. The plan is serialized on the calling 
thread, whose stack
 /// grows on demand for its levels.
 pub(crate) fn relation_with_ids(node: &Arc<LogicalPlan>, ids: &PlanIds) -> 
Result<proto::Relation> {
+    relation_with_ids_and_levels(node, ids).map(|(relation, _)| relation)
+}
+
+/// As [`relation_with_ids`], and the levels of the relation, those of the 
plans of its
+/// subqueries included.
+fn relation_with_ids_and_levels(
+    node: &Arc<LogicalPlan>,
+    ids: &PlanIds,
+) -> Result<(proto::Relation, usize)> {
     // The levels of the plan itself are known before it is serialized; those 
of the plans of
     // its subqueries are counted as they are serialized.
     let depth = node.depth();
     if depth > MAX_PLAN_DEPTH {
-        return Err(SparkError::recursion_msg(format!(
-            "maximum recursion depth exceeded while serializing a plan of 
{depth} levels; \
-             a plan may be at most {MAX_PLAN_DEPTH} levels deep"
-        )));
+        return Err(too_deep_a_plan(depth));
     }
-    with_plan_depth_bound(|| {
+    let (relation, levels) = with_plan_depth_bound(|| {
         crate::expression::with_expression_depth_bound(|| relation_of(node, 
Some(ids)))
-    })?
+    })?;
+    Ok((relation?, levels))
 }
 
 /// Serialize a child node, with its stable plan ID when `ids` is given.
@@ -930,7 +986,10 @@ fn relation_with_references(
     // a plan of many levels, and count them for `with_plan_depth_bound`.
     crate::expression::with_stack_for_a_level(|| {
         let level = PlanLevel::enter();
-        if level.0 > MAX_PLAN_DEPTH && 
PLAN_DEPTH_BOUNDED.with(std::cell::Cell::get) {
+        // A relation built outside the core counts its own levels below this 
one.
+        let deepest = level.0 + node.own_levels() - 1;
+        DEEPEST_PLAN_LEVEL.with(|levels| 
levels.set(levels.get().max(deepest)));
+        if deepest > MAX_PLAN_DEPTH && 
PLAN_DEPTH_BOUNDED.with(std::cell::Cell::get) {
             // The request fails with a `RecursionError`: stop here, so that 
the proto of the
             // plan is no deeper than the bound.
             return proto::Relation::default();
@@ -1101,8 +1160,18 @@ impl LogicalPlan {
         inputs_of!(self)
     }
 
-    /// The number of levels of this plan: one for a leaf, and one more than 
its deepest input
-    /// otherwise. Computed without recursing, and once for each node that 
several plans share.
+    /// The levels of this node itself, under which its inputs are: one, or 
those of the relation
+    /// of a [`LogicalPlan::Raw`], which holds the plans of its inputs.
+    fn own_levels(&self) -> usize {
+        match self {
+            LogicalPlan::Raw { depth, .. } => (*depth).max(1),
+            _ => 1,
+        }
+    }
+
+    /// The number of levels of this plan: one for a leaf (the levels of its 
relation for a
+    /// [`LogicalPlan::Raw`]), and one more than its deepest input otherwise. 
Computed without
+    /// recursing, and once for each node that several plans share.
     pub fn depth(&self) -> usize {
         let mut depths: HashMap<*const LogicalPlan, usize> = HashMap::new();
         let mut pending: Vec<(&LogicalPlan, bool)> = vec![(self, false)];
@@ -1118,7 +1187,7 @@ impl LogicalPlan {
                     .map(|input| depths[&Arc::as_ptr(input)])
                     .max()
                     .unwrap_or(0);
-                depths.insert(key, deepest + 1);
+                depths.insert(key, deepest + plan.own_levels());
             } else {
                 pending.push((plan, true));
                 pending.extend(
@@ -1133,10 +1202,29 @@ impl LogicalPlan {
     }
 
     /// Convert this logical plan to a `spark.connect.Relation` protobuf, 
without plan IDs.
+    ///
+    /// Any depth is serialized, on a stack that grows for its levels; but 
prost encodes and drops
+    /// a protobuf by recursing, so the proto of a plan of many thousands of 
levels can overflow a
+    /// small stack there (a request is bounded, see 
[`LogicalPlan::try_to_proto`]).
     pub fn to_proto(&self) -> proto::Relation {
         relation_with_references(self, None, None)
     }
 
+    /// Convert this logical plan to a `spark.connect.Relation` protobuf, 
without plan IDs, as
+    /// a request serializes it: a plan deeper than [`MAX_PLAN_DEPTH`], with 
the plans of its
+    /// subqueries, or with an expression deeper than 
[`crate::expression::MAX_EXPRESSION_DEPTH`],
+    /// is a `RecursionError`, as PySpark's serializer raises it, and its 
proto is not built.
+    pub fn try_to_proto(&self) -> Result<proto::Relation> {
+        let depth = self.depth();
+        if depth > MAX_PLAN_DEPTH {
+            return Err(too_deep_a_plan(depth));
+        }
+        let (relation, _) = with_plan_depth_bound(|| {
+            crate::expression::with_expression_depth_bound(|| self.to_proto())
+        })?;
+        relation
+    }
+
     fn to_proto_with(&self, plan_ids: Option<&PlanIds>) -> proto::Relation {
         let mut relation = proto::Relation::default();
         relation.common = Some(proto::RelationCommon::default());
@@ -1391,8 +1479,16 @@ impl LogicalPlan {
                 relation.rel_type = 
Some(proto::relation::RelType::HtmlString(Box::new(html)));
             }
 
-            LogicalPlan::Raw { relation: raw, .. } => {
-                relation = raw.as_ref().clone();
+            LogicalPlan::Raw {
+                relation: raw,
+                depth,
+                ..
+            } => {
+                // The clone recurses for each level of the relation: grow the 
stack for them all.
+                let stack = depth
+                    .saturating_mul(RAW_CLONE_STACK_PER_LEVEL)
+                    .saturating_add(64 << 10);
+                relation = stacker::maybe_grow(stack, stack, || 
raw.as_ref().clone());
                 relation.common.get_or_insert_with(Default::default);
             }
 
@@ -2563,6 +2659,7 @@ fn value_to_proto_literal(v: &crate::row::Value) -> 
proto::expression::Literal {
         Value::Timestamp(t) => Some(LiteralType::Timestamp(*t)),
         Value::TimestampNtz(t) => Some(LiteralType::TimestampNtz(*t)),
         Value::DayTimeInterval(t) => Some(LiteralType::DayTimeInterval(*t)),
+        Value::YearMonthInterval(months) => 
Some(LiteralType::YearMonthInterval(*months)),
         Value::Decimal {
             value,
             precision,
@@ -3446,4 +3543,134 @@ mod deep_plan_tests {
         let relation = relation_with_ids(&other, &PlanIds::new()).unwrap();
         assert_eq!(nested_limits(&relation), 11);
     }
+
+    /// Run `f` on a thread whose stack takes the comparisons and drops of 
deep protos, which
+    /// recurse, also in a debug build.
+    fn on_a_large_stack<T: Send>(f: impl FnOnce() -> T + Send) -> T {
+        std::thread::scope(|scope| {
+            std::thread::Builder::new()
+                .stack_size(64 << 20)
+                .spawn_scoped(scope, f)
+                .unwrap()
+                .join()
+                .unwrap()
+        })
+    }
+
+    /// A relation built outside the core over a DataFrame of `levels` levels, 
as `pyspark.ml`
+    /// builds a transform over the placeholder of its input, resolved as 
`from_relation` does.
+    fn transform_of_a_plan(levels: usize, ids: &Arc<PlanIds>) -> 
Arc<LogicalPlan> {
+        let input = chain(levels);
+        let mut relation = proto::Relation {
+            common: None,
+            rel_type: Some(proto::relation::RelType::MlRelation(Box::new(
+                proto::MlRelation {
+                    model_summary_dataset: None,
+                    ml_type: 
Some(proto::ml_relation::MlType::Transform(Box::new(
+                        proto::ml_relation::Transform {
+                            input: Some(Box::new(placeholder_relation(&input, 
ids))),
+                            params: None,
+                            operator: None,
+                        },
+                    ))),
+                },
+            ))),
+        };
+        let depth = resolve_relation_levels(&mut relation).unwrap();
+        Arc::new(LogicalPlan::Raw {
+            relation: Box::new(relation),
+            owner: None,
+            depth,
+        })
+    }
+
+    /// As PySpark serializes the plan of its input within that of a plan of 
`pyspark.ml`, the
+    /// levels of the DataFrame under a relation built outside the core count 
for the bound,
+    /// under the levels above that relation.
+    #[test]
+    fn 
the_levels_of_the_input_of_a_relation_built_outside_the_core_count_as_in_pyspark()
 {
+        on_a_large_stack(|| {
+            let ids = Arc::new(PlanIds::new());
+            let transform = transform_of_a_plan(400, &ids);
+            // The transform is a level over the 400 of its input.
+            assert_eq!(transform.depth(), 401);
+            let mut plan = Arc::clone(&transform);
+            for _ in 0..MAX_PLAN_DEPTH - 401 {
+                plan = Arc::new(limit(plan, 1));
+            }
+            assert_eq!(plan.depth(), MAX_PLAN_DEPTH);
+            relation_with_ids(&plan, &ids).unwrap();
+            let past = Arc::new(limit(plan, 1));
+            let error = relation_with_ids(&past, &ids).unwrap_err();
+            assert_eq!(error.kind, SparkErrorKind::RecursionError, "{error}");
+            assert!(
+                error
+                    .message()
+                    .contains(&format!("a plan of {} levels", MAX_PLAN_DEPTH + 
1)),
+                "{error}"
+            );
+            assert!(past.try_to_proto().is_err());
+            // In a subquery, which the levels of the plan do not count, they 
count as serialized.
+            let subquery = crate::expression::SubqueryExpression::new(
+                transform_of_a_plan(MAX_PLAN_DEPTH - 2, &ids),
+                1,
+                crate::expression::SubqueryType::Exists,
+            );
+            let filter = Arc::new(LogicalPlan::Filter {
+                input: Arc::new(range(0, 10, 1)),
+                condition: 
crate::column::Column::new(Expression::new(ExpressionNode::Subquery(
+                    Box::new(subquery),
+                ))),
+            });
+            relation_with_ids(&filter, &ids).unwrap();
+            let error = relation_with_ids(&Arc::new(limit(filter, 1)), 
&ids).unwrap_err();
+            assert!(
+                error.message().contains("the plans of its subqueries"),
+                "{error}"
+            );
+        });
+    }
+
+    /// The relation of a plan of `pyspark.ml` at the bound, over a DataFrame 
of as many levels,
+    /// is copied into the request on a thread with a small stack, which grows 
for its levels.
+    #[test]
+    fn 
a_relation_built_outside_the_core_at_the_bound_is_serialized_on_a_small_stack() 
{
+        on_a_large_stack(|| {
+            let ids = Arc::new(PlanIds::new());
+            let transform = transform_of_a_plan(MAX_PLAN_DEPTH - 1, &ids);
+            assert_eq!(transform.depth(), MAX_PLAN_DEPTH);
+            let relation = on_a_small_stack(|| relation_with_ids(&transform, 
&ids).unwrap());
+            let Some(proto::relation::RelType::MlRelation(ml)) = 
&relation.rel_type else {
+                panic!("an ML relation");
+            };
+            let Some(proto::ml_relation::MlType::Transform(transform)) = 
&ml.ml_type else {
+                panic!("a transform");
+            };
+            assert_eq!(
+                nested_limits(transform.input.as_deref().unwrap()),
+                MAX_PLAN_DEPTH - 1
+            );
+        });
+    }
+
+    /// `try_to_proto` bounds a plan as a request does, and `to_proto` 
serializes one of any
+    /// depth, on a small stack.
+    #[test]
+    fn 
try_to_proto_bounds_the_plan_as_a_request_and_to_proto_serializes_any_depth() {
+        on_a_large_stack(|| {
+            let at_bound = chain(MAX_PLAN_DEPTH);
+            let relation = on_a_small_stack(|| 
at_bound.try_to_proto().unwrap());
+            assert_eq!(nested_limits(&relation), MAX_PLAN_DEPTH);
+            assert!(relation.common.unwrap().plan_id.is_none());
+            for levels in [MAX_PLAN_DEPTH + 1, 100_000] {
+                let plan = chain(levels);
+                let error = on_a_small_stack(|| 
plan.try_to_proto().unwrap_err());
+                assert_eq!(error.kind, SparkErrorKind::RecursionError, 
"{error}");
+                on_a_small_stack(move || std::mem::drop(plan));
+            }
+            let deep = chain(10_000);
+            let relation = on_a_small_stack(|| deep.to_proto());
+            assert_eq!(nested_limits(&relation), 10_000);
+        });
+    }
 }
diff --git a/crates/spark-connect/src/progress.rs 
b/crates/spark-connect/src/progress.rs
index f8c0f0a6..0a8c0750 100644
--- a/crates/spark-connect/src/progress.rs
+++ b/crates/spark-connect/src/progress.rs
@@ -220,8 +220,34 @@ impl ExecutionStream {
     /// last one has no batch.
     /// When the execution ends, of its result or of an error, the handlers 
get their done call,
     /// whose error is the error of the execution, as PySpark's 
`Progress.__exit__` raises it.
+    /// The handlers run on the thread that polls this; a synchronous caller 
uses
+    /// [`ExecutionStream::next_message`], which calls them on its own thread.
     pub(crate) async fn message(&mut self) -> 
Result<Option<proto::ExecutePlanResponse>> {
-        let response = match self.stream.message().await {
+        let response = self.stream.message().await;
+        self.handle(response)
+    }
+
+    /// As [`ExecutionStream::message`], waiting on the calling thread, which 
the handlers are
+    /// called on, as PySpark calls them on the thread that iterates the 
responses: also inside
+    /// a `current_thread` runtime, where the response is awaited on a thread 
of its own.
+    pub(crate) fn next_message(&mut self) -> 
Result<Option<proto::ExecutePlanResponse>> {
+        let response = 
spark_connect_core::runtime::block_on(self.stream.message());
+        // On a worker of a multi-thread runtime, the handlers block in place, 
as the wait did.
+        match tokio::runtime::Handle::try_current() {
+            Ok(handle) if handle.runtime_flavor() == 
tokio::runtime::RuntimeFlavor::MultiThread => {
+                tokio::task::block_in_place(|| self.handle(response))
+            }
+            _ => self.handle(response),
+        }
+    }
+
+    /// The response of the stream, `response`, after its progress has updated 
the handlers and
+    /// its chunk is joined into its batch.
+    fn handle(
+        &mut self,
+        response: Result<Option<proto::ExecutePlanResponse>>,
+    ) -> Result<Option<proto::ExecutePlanResponse>> {
+        let response = match response {
             Ok(response) => response,
             Err(error) => return Err(self.progress.finish_after(error)),
         };
diff --git a/crates/spark-connect/src/row.rs b/crates/spark-connect/src/row.rs
index a1e99985..9b8424f7 100644
--- a/crates/spark-connect/src/row.rs
+++ b/crates/spark-connect/src/row.rs
@@ -44,6 +44,9 @@ pub enum Value {
     /// representable by Python's datetime.timedelta without nanosecond 
conversion.
     /// Display uses raw microseconds, like Date and Timestamp use their raw 
units.
     DayTimeInterval(i64),
+    /// Spark year-month interval, in signed months, as the Scala client's 
`java.time.Period`
+    /// of it has them. Display uses raw months, like DayTimeInterval its raw 
microseconds.
+    YearMonthInterval(i32),
     /// Decimal text in fixed-point or scientific notation, with optional 
precision and scale.
     /// Text passed to `create_dataframe` must fit the declared precision and 
scale exactly.
     /// Callers that rescale, such as Python local-row conversion, do so 
before building
@@ -85,6 +88,7 @@ impl fmt::Debug for Value {
             Self::TimestampNtz(v) => 
f.debug_tuple("TimestampNtz").field(v).finish(),
             Self::Time(v) => f.debug_tuple("Time").field(v).finish(),
             Self::DayTimeInterval(v) => 
f.debug_tuple("DayTimeInterval").field(v).finish(),
+            Self::YearMonthInterval(v) => 
f.debug_tuple("YearMonthInterval").field(v).finish(),
             Self::Decimal {
                 value,
                 precision,
@@ -189,6 +193,7 @@ impl fmt::Display for Value {
             Value::TimestampNtz(t) => write!(f, "{}", t),
             Value::Time(t) => write!(f, "{}", t),
             Value::DayTimeInterval(t) => write!(f, "{}", t),
+            Value::YearMonthInterval(months) => write!(f, "{}", months),
             Value::Decimal {
                 value,
                 precision,
@@ -789,6 +794,12 @@ mod tests {
         assert_eq!(Value::Timestamp(123).to_string(), "123");
         assert_eq!(Value::DayTimeInterval(-1).to_string(), "-1");
         assert_eq!(Value::DayTimeInterval(1).as_i64(), None);
+        assert_eq!(Value::YearMonthInterval(-13).to_string(), "-13");
+        assert_eq!(
+            format!("{:?}", Value::YearMonthInterval(12)),
+            "YearMonthInterval(12)"
+        );
+        assert_eq!(Value::YearMonthInterval(1).as_i64(), None);
         assert_eq!(
             Value::List(vec![Value::Integer(1), 
Value::Integer(2)]).to_string(),
             "[1, 2]"
diff --git a/crates/spark-connect/src/session.rs 
b/crates/spark-connect/src/session.rs
index 3f39fe7d..9b1bb630 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -249,6 +249,11 @@ impl SparkSession {
     /// each progress of the server that has tasks, and once more, as done, 
when the execution
     /// ends, also of an error, as PySpark's `Progress` calls its handlers. 
Returns an id usable
     /// with [`SparkSession::remove_progress_handler`]. Mirrors 
`registerProgressHandler`.
+    ///
+    /// As PySpark's, the handlers are called on the thread that runs the 
execution (that calls
+    /// `collect`, `count`, or `next` of a local iterator), also inside a 
`current_thread` Tokio
+    /// runtime. The prefetching iterator of `to_local_iterator(true)` reads 
ahead on a thread of
+    /// the runtime, which calls them.
     pub fn register_progress_handler(
         &self,
         handler: impl Fn(&ProgressUpdate) + Send + Sync + 'static,
@@ -1304,8 +1309,17 @@ impl SparkSession {
     }
 
     /// Release the session on the server, as 
`SparkConnectClient.release_session`: its state
-    /// there, without stopping this session.
+    /// there, without stopping this session. After [`SparkSession::stop`] or
+    /// [`SparkSession::close`], it sends nothing and is the 
`NO_ACTIVE_SESSION` error, as the
+    /// `_stub` of PySpark's closed client raises it.
     pub fn release_session(&self) -> Result<()> {
+        if self.client.is_closed() {
+            return Err(SparkError::classed(
+                spark_connect_core::error::SparkErrorKind::Connect,
+                "NO_ACTIVE_SESSION",
+                &[],
+            ));
+        }
         block_on(self.client.release_session())
     }
 
@@ -1556,6 +1570,10 @@ fn datatype_to_arrow(dt: &DataType) -> 
Result<arrow::datatypes::DataType> {
         DataType::Time { .. } => A::Time64(TimeUnit::Nanosecond),
         // As Spark's Arrow conversion of DayTimeIntervalType.
         DataType::DayTimeInterval { .. } => A::Duration(TimeUnit::Microsecond),
+        // As Spark's Arrow conversion of YearMonthIntervalType, the months of 
each interval.
+        DataType::YearMonthInterval { .. } => {
+            A::Interval(arrow::datatypes::IntervalUnit::YearMonth)
+        }
         DataType::Decimal { precision, scale } => A::Decimal128(*precision as 
u8, *scale as i8),
         DataType::Array {
             element_type,
@@ -1750,6 +1768,9 @@ fn values_to_arrow(values: &[&Value], dt: &DataType) -> 
Result<Arc<dyn arrow::ar
         // As PySpark's `to_arrow_type`: nanoseconds since midnight, as 
`TimeType.toInternal`.
         DataType::Time { .. } => prim!(Time64NanosecondArray, Value::Time),
         DataType::DayTimeInterval { .. } => prim!(DurationMicrosecondArray, 
Value::DayTimeInterval),
+        DataType::YearMonthInterval { .. } => {
+            prim!(IntervalYearMonthArray, Value::YearMonthInterval)
+        }
         DataType::Timestamp | DataType::TimestampNtz => {
             let vals: Result<Vec<Option<i64>>> = values
                 .iter()
@@ -3041,6 +3062,32 @@ mod tests {
         assert_eq!(err.get_condition().as_deref(), Some("NO_ACTIVE_SESSION"));
     }
 
+    /// As the `_stub` of PySpark's closed client: `release_session` after 
`stop()` or `close()`
+    /// raises `NO_ACTIVE_SESSION` and sends nothing.
+    #[test]
+    fn 
release_session_of_a_stopped_session_raises_no_active_session_as_pyspark() {
+        // No server and no retries: a release that reached the wire would 
fail at once, with
+        // another error.
+        let unreachable = || {
+            let builder = 
ChannelBuilder::parse("sc://127.0.0.1:1").expect("valid URL");
+            let mut client =
+                block_on(SparkConnectClient::connect(&builder)).expect("failed 
to build client");
+            
client.set_retry_policy(spark_connect_core::retries::RetryPolicy::no_retries());
+            SparkSession::new(client)
+        };
+        let closed = unreachable();
+        closed.close();
+        let stopped = unreachable();
+        assert!(
+            stopped.stop().is_err(),
+            "the release of stop() reaches no server"
+        );
+        for spark in [closed, stopped] {
+            let err = spark.release_session().expect_err("a stopped session");
+            assert_eq!(err.get_condition().as_deref(), 
Some("NO_ACTIVE_SESSION"));
+        }
+    }
+
     #[test]
     fn forward_to_fs_artifact_name_is_the_prefix_and_the_absolute_path() {
         // As the reference's `FORWARD_TO_FS_PREFIX + dest_path`, with no 
separator added.
diff --git a/crates/spark-connect/src/streaming.rs 
b/crates/spark-connect/src/streaming.rs
index 4ad742d2..8ae71985 100644
--- a/crates/spark-connect/src/streaming.rs
+++ b/crates/spark-connect/src/streaming.rs
@@ -972,6 +972,9 @@ pub trait StreamingQueryListener: Send + Sync {
     /// Deserialize and dispatch an asynchronous event. An error is any 
failure the adapter
     /// does not isolate, including protocol/deserialization errors and 
adapter-defined
     /// unisolated callback failures. It terminates this subscription and 
clears its registrations.
+    /// A panic is isolated, as PySpark's `post_to_all` isolates the exception 
of a listener: it
+    /// is reported with a warning, and the other listeners still get the 
event, as for the
+    /// started event.
     fn try_on_event(&self, event: &StreamingQueryListenerEvent) -> Result<()> {
         self.on_event(event);
         Ok(())
@@ -1103,15 +1106,21 @@ impl ListenerBus {
             let posted =
                 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| 
listener.on_event(event)));
             if let Err(payload) = posted {
-                eprintln!(
-                    "WARNING: a streaming query listener threw an 
exception\n{}",
-                    panic_message(payload.as_ref())
-                );
+                warn_of_listener_panic(payload.as_ref());
             }
         }
     }
 }
 
+/// Report the panic of a native listener's callback, which is isolated as 
PySpark's
+/// `post_to_all` isolates the exception of a listener, with a warning.
+fn warn_of_listener_panic(payload: &(dyn std::any::Any + Send)) {
+    eprintln!(
+        "WARNING: a streaming query listener threw an exception\n{}",
+        panic_message(payload)
+    );
+}
+
 /// Ends the generation of a worker when its loop returns or unwinds, so the 
registrations
 /// of a worker that is gone never stay on the bus.
 struct FinishGeneration {
@@ -1191,18 +1200,27 @@ fn run_listener_event_loop(
             event_type,
             event_json,
         };
-        // A panic of a callback is a failure of the subscription, as a 
returned error is.
+        // As PySpark's `post_to_all` isolates the exception of a listener, 
the panic of one is
+        // reported, and the others still get the event: the subscription goes 
on. A returned
+        // error, such as of an event that cannot be read, fails the 
subscription, as does a
+        // panic of an adapter that dispatches the event to all of them.
         let dispatched = 
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
             listeners
                 .iter()
                 .find_map(|listener| listener.try_post_to_all(&listeners, 
&event))
-                .unwrap_or_else(|| {
-                    listeners
-                        .iter()
-                        .try_for_each(|listener| listener.try_on_event(&event))
-                })
         }))
-        .unwrap_or_else(|payload| Err(listener_panic_error(payload.as_ref())));
+        .unwrap_or_else(|payload| 
Some(Err(listener_panic_error(payload.as_ref()))))
+        .unwrap_or_else(|| {
+            listeners.iter().try_for_each(|listener| {
+                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+                    listener.try_on_event(&event)
+                }))
+                .unwrap_or_else(|payload| {
+                    warn_of_listener_panic(payload.as_ref());
+                    Ok(())
+                })
+            })
+        });
         if let Err(error) = dispatched {
             failure = Some((listeners, error, dispatch));
             break;
@@ -2226,20 +2244,24 @@ mod tests {
         worker.join().unwrap();
     }
 
-    /// A panic of a native listener's callback fails the subscription as a 
returned error does:
-    /// the listeners are told, the registrations are cleared, and no later 
event is read.
+    /// As PySpark's `post_to_all`, which isolates the exception of a listener 
for every event:
+    /// a panic of a native listener's callback on an event of the bus is 
reported, the listeners
+    /// after it still get the event, and the subscription goes on to the next 
events.
     #[test]
-    fn a_panicking_native_listener_fails_the_subscription_like_an_error() {
+    fn 
a_panicking_native_listener_on_an_event_of_the_bus_is_isolated_as_pyspark() {
         use std::sync::atomic::{AtomicUsize, Ordering};
 
         struct Listener {
+            panics: bool,
             events: AtomicUsize,
             errors: Mutex<Vec<String>>,
         }
         impl StreamingQueryListener for Listener {
             fn on_event(&self, _: &StreamingQueryListenerEvent) {
                 self.events.fetch_add(1, Ordering::SeqCst);
-                panic!("listener panic on event");
+                if self.panics {
+                    panic!("listener panic on event");
+                }
             }
 
             fn on_stream_error(&self, error: &SparkError) -> bool {
@@ -2248,34 +2270,81 @@ mod tests {
             }
         }
         let bus = Arc::new(ListenerBus::default());
-        let listener = Arc::new(Listener {
-            events: AtomicUsize::new(0),
-            errors: Mutex::new(vec![]),
-        });
+        let listener = |panics| {
+            Arc::new(Listener {
+                panics,
+                events: AtomicUsize::new(0),
+                errors: Mutex::new(vec![]),
+            })
+        };
+        let (panicking, after) = (listener(true), listener(false));
         {
             let mut state = bus.state.lock().unwrap();
             state.generation = 3;
             state
                 .listeners
-                .push(("first".to_string(), listener.clone()));
+                .push(("panicking".to_string(), panicking.clone()));
+            state.listeners.push(("after".to_string(), after.clone()));
         }
+        run_listener_event_loop(
+            vec![
+                Ok((QUERY_IDLE_EVENT, "first".to_string())),
+                Ok((QUERY_PROGRESS_EVENT, "second".to_string())),
+            ],
+            Arc::downgrade(&bus),
+            3,
+        );
+        for listener in [&panicking, &after] {
+            assert_eq!(listener.events.load(Ordering::SeqCst), 2);
+            assert!(listener.errors.lock().unwrap().is_empty());
+        }
+        let state = bus.state.lock().unwrap();
+        assert!(state.dispatching.is_none());
+        assert!(!state.server_registration_held);
+    }
+
+    /// An adapter that dispatches an event to all the listeners owns the 
isolation of their
+    /// failures: its panic fails the subscription, as a returned error does.
+    #[test]
+    fn a_panicking_adapter_fails_the_subscription_like_an_error() {
+        struct Adapter(Mutex<Vec<String>>);
+        impl StreamingQueryListener for Adapter {
+            fn on_event(&self, _: &StreamingQueryListenerEvent) {}
+
+            fn try_post_to_all(
+                &self,
+                _: &[Arc<dyn StreamingQueryListener>],
+                _: &StreamingQueryListenerEvent,
+            ) -> Option<Result<()>> {
+                panic!("adapter panic");
+            }
+
+            fn on_stream_error(&self, error: &SparkError) -> bool {
+                self.0.lock().unwrap().push(error.message());
+                true
+            }
+        }
+        let bus = Arc::new(ListenerBus::default());
+        let adapter = Arc::new(Adapter(Mutex::new(vec![])));
+        bus.state
+            .lock()
+            .unwrap()
+            .listeners
+            .push(("adapter".to_string(), adapter.clone()));
         run_listener_event_loop(
             vec![
                 Ok((QUERY_IDLE_EVENT, "panics".to_string())),
                 Ok((QUERY_IDLE_EVENT, "never read".to_string())),
             ],
             Arc::downgrade(&bus),
-            3,
+            0,
         );
-        assert_eq!(listener.events.load(Ordering::SeqCst), 1);
         assert_eq!(
-            *listener.errors.lock().unwrap(),
-            vec!["a streaming query listener panicked: listener panic on 
event".to_string()],
+            *adapter.0.lock().unwrap(),
+            vec!["a streaming query listener panicked: adapter 
panic".to_string()],
         );
         let state = bus.state.lock().unwrap();
         assert!(state.listeners.is_empty());
-        assert!(state.dispatching.is_none());
-        assert!(state.cancel.is_none());
         assert!(state.server_registration_held);
     }
 
diff --git a/crates/spark-connect/src/types.rs 
b/crates/spark-connect/src/types.rs
index 985ef6e4..26b28afd 100644
--- a/crates/spark-connect/src/types.rs
+++ b/crates/spark-connect/src/types.rs
@@ -164,11 +164,17 @@ impl DataType {
     /// This supports:
     /// - Primitive types: int, bigint, string, double, boolean, date, 
timestamp, binary,
     ///   tinyint, smallint, float, decimal(p,s), char(n), varchar(n), interval
-    /// - Complex types: array<...>, map<...,...>, struct<name:type,...>
+    /// - Complex types: array<...>, map<...,...>, struct<name:type,...>, with 
any whitespace
+    ///   between the tokens, as `ARRAY < INT >`, which Spark's parser takes 
too
     /// - Top-level struct can omit the "struct<>" wrapper for backward 
compatibility
     /// - DDL like "a INT, b STRING" is parsed as a struct
     /// - A field may end with `NOT NULL` and `COMMENT 'text'`, as 
`StructType.toDDL` writes them
     ///
+    /// The parse is local, so `timestamp` is always [`DataType::Timestamp`] 
(TIMESTAMP_LTZ),
+    /// while the server's parser makes it TIMESTAMP_NTZ when 
`spark.sql.timestampType` is
+    /// `TIMESTAMP_NTZ`; [`crate::SparkSession::parse_ddl`] parses a DDL 
string as the server
+    /// does.
+    ///
     /// Examples:
     /// ```ignore
     /// DataType::from_ddl("int") // IntegerType
@@ -1874,7 +1880,7 @@ fn parse_datatype_string(input: &str) -> Result<DataType> 
{
     // separating a field name from its type; fall back to single-type parsing 
if the
     // schema interpretation fails (e.g. a bare type that itself contains 
spaces such as
     // "interval day to second"). A top-level colon names a field too, as in 
"a:int".
-    if !trimmed.to_lowercase().starts_with("struct<")
+    if after_complex_keyword(trimmed, "struct").is_none()
         && (contains_top_level_comma(trimmed)
             || contains_top_level_whitespace(trimmed)
             || contains_top_level_colon(trimmed))
@@ -2265,18 +2271,38 @@ fn canonical_type_spelling(s: &str) -> String {
     format!("{head}{args}")
 }
 
+/// The text after the `<` of the complex type `keyword` that `input` starts 
with, in any case and
+/// with any whitespace before the `<`, as Spark's lexer reads `ARRAY <INT>`; 
`None` if `input`
+/// does not start with it.
+fn after_complex_keyword<'a>(input: &'a str, keyword: &str) -> Option<&'a str> 
{
+    let input = input.trim_start();
+    let head = input.get(..keyword.len())?;
+    if !head.eq_ignore_ascii_case(keyword) {
+        return None;
+    }
+    input[keyword.len()..].trim_start().strip_prefix('<')
+}
+
+/// The type parameters of the complex type `keyword` of `input`, the text 
between its angle
+/// brackets, or the `INVALID_DATATYPE_FORMAT` error of `detail`.
+fn complex_type_inner<'a>(input: &'a str, keyword: &str, detail: &str) -> 
Result<&'a str> {
+    after_complex_keyword(input, keyword)
+        .and_then(|rest| rest.trim_end().strip_suffix('>'))
+        .ok_or_else(|| SparkError::value("INVALID_DATATYPE_FORMAT", 
&[("detail", detail)]))
+}
+
 /// Parse a single type (primitive or complex)
 fn parse_single_type(input: &str) -> Result<DataType> {
     let trimmed = canonical_type_spelling(&input.trim().to_lowercase());
 
     // Complex types
-    if trimmed.starts_with("array<") {
+    if after_complex_keyword(input, "array").is_some() {
         return parse_array_type(input);
     }
-    if trimmed.starts_with("map<") {
+    if after_complex_keyword(input, "map").is_some() {
         return parse_map_type(input);
     }
-    if trimmed.starts_with("struct<") {
+    if after_complex_keyword(input, "struct").is_some() {
         return parse_struct_type(input);
     }
 
@@ -2347,15 +2373,7 @@ fn parse_single_type(input: &str) -> Result<DataType> {
 
 /// Parse array<elementType>
 fn parse_array_type(input: &str) -> Result<DataType> {
-    let trimmed = input.trim();
-    if !trimmed.to_lowercase().starts_with("array<") || 
!trimmed.ends_with('>') {
-        return Err(SparkError::value(
-            "INVALID_DATATYPE_FORMAT",
-            &[("detail", "Invalid array type format")],
-        ));
-    }
-
-    let inner = &trimmed[6..trimmed.len() - 1];
+    let inner = complex_type_inner(input, "array", "Invalid array type 
format")?;
     let element_type = parse_single_type(inner)?;
 
     Ok(DataType::Array {
@@ -2366,15 +2384,7 @@ fn parse_array_type(input: &str) -> Result<DataType> {
 
 /// Parse map<keyType,valueType>
 fn parse_map_type(input: &str) -> Result<DataType> {
-    let trimmed = input.trim();
-    if !trimmed.to_lowercase().starts_with("map<") || !trimmed.ends_with('>') {
-        return Err(SparkError::value(
-            "INVALID_DATATYPE_FORMAT",
-            &[("detail", "Invalid map type format")],
-        ));
-    }
-
-    let inner = &trimmed[4..trimmed.len() - 1];
+    let inner = complex_type_inner(input, "map", "Invalid map type format")?;
     let parts = split_map_parts(inner)?;
     if parts.len() != 2 {
         return Err(SparkError::value(
@@ -2403,15 +2413,7 @@ fn split_map_parts(s: &str) -> Result<Vec<&str>> {
 
 /// Parse struct<field1:type1,field2:type2,...>
 fn parse_struct_type(input: &str) -> Result<DataType> {
-    let trimmed = input.trim();
-    if !trimmed.to_lowercase().starts_with("struct<") || 
!trimmed.ends_with('>') {
-        return Err(SparkError::value(
-            "INVALID_DATATYPE_FORMAT",
-            &[("detail", "Invalid struct type format")],
-        ));
-    }
-
-    let inner = &trimmed[7..trimmed.len() - 1];
+    let inner = complex_type_inner(input, "struct", "Invalid struct type 
format")?;
     if inner.trim().is_empty() {
         return Ok(DataType::Struct { fields: vec![] });
     }
@@ -3108,6 +3110,47 @@ mod tests {
         assert_eq!(dt2.simple_string(), "struct<a:int,b:array<string>>");
     }
 
+    /// Whitespace before and inside the angle brackets of a complex type, 
which the server's
+    /// parser takes (each type as the server's `DDLParse` gives it), and the 
malformed spellings
+    /// that it rejects.
+    #[test]
+    fn from_ddl_takes_whitespace_around_angle_brackets_as_the_server() {
+        for (ddl, server) in [
+            ("array <int>", "array<int>"),
+            ("STRUCT <a:int>", "struct<a:int>"),
+            ("map <string, int>", "map<string,int>"),
+            ("a array <int>", "struct<a:array<int>>"),
+            ("a: array <int>", "struct<a:array<int>>"),
+            (
+                "a ARRAY < INT >, b map < string , int >",
+                "struct<a:array<int>,b:map<string,int>>",
+            ),
+            ("array<struct <x: int>>", "array<struct<x:int>>"),
+            (
+                "struct < a : int , b : array < string > >",
+                "struct<a:int,b:array<string>>",
+            ),
+            ("struct <>", "struct<>"),
+            ("a struct <>", "struct<a:struct<>>"),
+        ] {
+            let parsed = DataType::from_ddl(ddl).unwrap_or_else(|e| 
panic!("{ddl}: {e}"));
+            assert_eq!(parsed.simple_string(), server, "{ddl}");
+        }
+        let DataType::Struct { fields } = DataType::from_ddl("a array <int> 
NOT NULL").unwrap()
+        else {
+            panic!("a struct");
+        };
+        assert!(!fields[0].nullable);
+        for rejected in [
+            "array <int> NOT NULL",
+            "array <>",
+            "array <int",
+            "map <int>",
+        ] {
+            assert!(DataType::from_ddl(rejected).is_err(), "{rejected}");
+        }
+    }
+
     #[test]
     fn test_from_ddl_top_level_schema() {
         // Top-level schema without struct<>
diff --git a/crates/spark-connect/tests/e2e_dataframe.rs 
b/crates/spark-connect/tests/e2e_dataframe.rs
index 7abaedc2..fb3bbb30 100644
--- a/crates/spark-connect/tests/e2e_dataframe.rs
+++ b/crates/spark-connect/tests/e2e_dataframe.rs
@@ -74,6 +74,7 @@ fn dataframe_transforms_and_setops() {
     );
     assert_eq!(
         df.repartition_by_range(2, vec![col("id").expression().clone()])
+            .unwrap()
             .count()
             .unwrap(),
         4
@@ -445,6 +446,209 @@ fn 
pivot_values_of_dates_timestamps_and_decimals_match_discovered_pivots() {
     );
 }
 
+/// A pivot on the values collected from a float, tinyint, smallint or 
year-month interval column
+/// names its columns as the pivot without values, which the server computes, 
does: "1.1" for a
+/// float, as the Scala client's `lit` of it, and the SQL of an interval.
+#[test]
+fn pivot_values_of_floats_and_year_month_intervals_match_discovered_pivots() {
+    if !should_run() {
+        return;
+    }
+    use spark_connect::row::Value;
+    let s = session();
+    let df = s
+        .sql(
+            "SELECT * FROM VALUES (CAST(1.1 AS FLOAT), CAST(3 AS TINYINT), 
CAST(4 AS SMALLINT), \
+             INTERVAL '1-0' YEAR TO MONTH, 'a', 1), \
+             (CAST(-2.5 AS FLOAT), CAST(-3 AS TINYINT), CAST(-4 AS SMALLINT), \
+             INTERVAL '-0-1' YEAR TO MONTH, 'b', 2) AS t(f, b, sh, ym, k, v)",
+        )
+        .unwrap();
+    for column in ["f", "b", "sh", "ym"] {
+        // In the order of the pivot without values, which sorts them.
+        let values: Vec<Value> = df
+            .select(vec![col(column)])
+            .order_by(vec![col(column).expression().clone()])
+            .collect()
+            .unwrap()
+            .iter()
+            .map(|row| row.get(0).unwrap().clone())
+            .collect();
+        let pivot = |values: Option<Vec<Value>>| {
+            named_rows(
+                &df.group_by(vec![col("k")])
+                    .pivot(col(column), values)
+                    .unwrap()
+                    .sum(vec!["v"])
+                    .unwrap()
+                    .order_by(vec![col("k").expression().clone()]),
+            )
+        };
+        assert_eq!(pivot(Some(values)), pivot(None), "{column}");
+    }
+    let intervals: Vec<Value> = df
+        .select(vec![col("ym")])
+        .order_by(vec![col("v").expression().clone()])
+        .collect()
+        .unwrap()
+        .iter()
+        .map(|row| row.get(0).unwrap().clone())
+        .collect();
+    assert_eq!(
+        intervals,
+        vec![Value::YearMonthInterval(12), Value::YearMonthInterval(-1)]
+    );
+    let (columns, _) = named_rows(
+        &df.group_by(vec![col("k")])
+            .pivot(col("ym"), Some(intervals))
+            .unwrap()
+            .sum(vec!["v"])
+            .unwrap(),
+    );
+    assert_eq!(
+        columns,
+        vec![
+            "k".to_string(),
+            "INTERVAL '1-0' YEAR TO MONTH".to_string(),
+            "INTERVAL '-0-1' YEAR TO MONTH".to_string(),
+        ]
+    );
+}
+
+/// Year-month intervals are collected as their months, in nested values too, 
and local rows of
+/// them are sent as Spark's Arrow conversion sends them.
+#[test]
+fn year_month_interval_values_roundtrip() {
+    if !should_run() {
+        return;
+    }
+    use spark_connect::row::{Row, Value};
+    use spark_connect::types::{DataType, StructField};
+    let s = session();
+    let rows = s
+        .sql(
+            "SELECT INTERVAL '178956970-7' YEAR TO MONTH AS a, INTERVAL 
'-178956970-8' YEAR TO \
+             MONTH AS b, array(INTERVAL '2' YEAR) AS c, CAST(NULL AS INTERVAL 
MONTH) AS d",
+        )
+        .unwrap()
+        .collect()
+        .unwrap();
+    assert_eq!(rows[0].get(0), Some(&Value::YearMonthInterval(i32::MAX)));
+    assert_eq!(rows[0].get(1), Some(&Value::YearMonthInterval(i32::MIN)));
+    assert_eq!(
+        rows[0].get(2),
+        Some(&Value::List(vec![Value::YearMonthInterval(24)]))
+    );
+    assert_eq!(rows[0].get(3), Some(&Value::Null));
+
+    let interval = DataType::YearMonthInterval {
+        start_field: 0,
+        end_field: 1,
+    };
+    let schema = DataType::Struct {
+        fields: vec![StructField {
+            name: "i".to_string(),
+            data_type: interval,
+            nullable: true,
+            metadata: Default::default(),
+        }],
+    };
+    let input = vec![
+        Row::new(vec!["i".to_string()], vec![Value::YearMonthInterval(-13)]),
+        Row::new(vec!["i".to_string()], vec![Value::Null]),
+    ];
+    let df = s.create_dataframe(input, schema).unwrap();
+    let texts: Vec<Value> = df
+        .select_expr(vec!["CAST(i AS STRING)"])
+        .collect()
+        .unwrap()
+        .iter()
+        .map(|row| row.get(0).unwrap().clone())
+        .collect();
+    assert_eq!(
+        texts,
+        vec![
+            Value::String("INTERVAL '-1-1' YEAR TO MONTH".to_string()),
+            Value::Null
+        ]
+    );
+    let back: Vec<Value> = df
+        .collect()
+        .unwrap()
+        .iter()
+        .map(|row| row.get(0).unwrap().clone())
+        .collect();
+    assert_eq!(back, vec![Value::YearMonthInterval(-13), Value::Null]);
+}
+
+/// Collect a slow query and iterate it on demand, on this thread, which 
`caller` notes: the rows
+/// of each.
+fn run_slow_queries(
+    s: &SparkSession,
+    caller: &std::sync::Mutex<Option<std::thread::ThreadId>>,
+) -> (usize, usize) {
+    *caller.lock().unwrap() = Some(std::thread::current().id());
+    let slow = "SELECT id, reflect('java.lang.Thread', 'sleep', 300L) AS s 
FROM range(0, 4, 1, 4)";
+    let collected = s.sql(slow).unwrap().collect().unwrap().len();
+    let iterated = s
+        .sql(slow)
+        .unwrap()
+        .to_local_iterator(false)
+        .unwrap()
+        .count();
+    (collected, iterated)
+}
+
+/// As PySpark calls the progress handlers on the thread that runs the 
execution: also inside a
+/// `current_thread` runtime, where the responses are awaited on another 
thread, and on a worker
+/// of a multi-thread runtime, each update and the done call run on the 
caller's thread.
+#[test]
+fn progress_handlers_run_on_the_calling_thread_inside_a_tokio_runtime() {
+    if !should_run() {
+        return;
+    }
+    use std::sync::{Arc, Mutex};
+    let s = session().new_session();
+    s.conf()
+        .set("spark.connect.progress.reportInterval", "100ms")
+        .unwrap();
+    let caller: Arc<Mutex<Option<std::thread::ThreadId>>> = Arc::default();
+    let calls: Arc<Mutex<Vec<(bool, bool)>>> = Arc::default();
+    let (expected, seen) = (Arc::clone(&caller), Arc::clone(&calls));
+    let id = s.register_progress_handler(move |update| {
+        let on_caller = *expected.lock().unwrap() == 
Some(std::thread::current().id());
+        seen.lock().unwrap().push((update.done, on_caller));
+    });
+    let current = tokio::runtime::Builder::new_current_thread()
+        .enable_all()
+        .build()
+        .unwrap();
+    assert_eq!(
+        current.block_on(async { run_slow_queries(&s, &caller) }),
+        (4, 4)
+    );
+    let multi = tokio::runtime::Builder::new_multi_thread()
+        .worker_threads(2)
+        .enable_all()
+        .build()
+        .unwrap();
+    let (task_session, task_caller) = (s.clone(), Arc::clone(&caller));
+    let counts = multi.block_on(async move {
+        tokio::spawn(async move { run_slow_queries(&task_session, 
&task_caller) })
+            .await
+            .unwrap()
+    });
+    assert_eq!(counts, (4, 4));
+    s.remove_progress_handler(id);
+    let calls = calls.lock().unwrap();
+    assert!(calls.iter().any(|(done, _)| !done), "{calls:?}");
+    assert!(
+        calls.iter().filter(|(done, _)| *done).count() >= 4,
+        "{calls:?}"
+    );
+    assert!(calls.iter().all(|(_, on_caller)| *on_caller), "{calls:?}");
+}
+
 #[test]
 fn day_time_interval_input_roundtrips() {
     if !should_run() {
@@ -717,6 +921,7 @@ fn repartition_by_range_splits_into_contiguous_ranges() {
         .range(100)
         .unwrap()
         .repartition_by_range(4, vec![col("id").expression().clone()])
+        .unwrap()
         .with_column("p", f::spark_partition_id())
         .group_by(vec![col("p")])
         .agg(vec![
diff --git a/crates/spark-connect/tests/e2e_new_methods.rs 
b/crates/spark-connect/tests/e2e_new_methods.rs
index 4488cc68..d2c9d187 100644
--- a/crates/spark-connect/tests/e2e_new_methods.rs
+++ b/crates/spark-connect/tests/e2e_new_methods.rs
@@ -119,6 +119,7 @@ fn stat_corr_cov_sample_by() {
     let sampled = df
         .stat()
         .sample_by("g", fractions, Some(42))
+        .expect("sample_by")
         .collect()
         .expect("sample_by collect");
     // Non-deterministic count, but the RPC must succeed and return 
rows-or-none.
diff --git a/crates/spark-connect/tests/e2e_ops_breadth.rs 
b/crates/spark-connect/tests/e2e_ops_breadth.rs
index 2bd3dae3..d874972e 100644
--- a/crates/spark-connect/tests/e2e_ops_breadth.rs
+++ b/crates/spark-connect/tests/e2e_ops_breadth.rs
@@ -83,6 +83,7 @@ fn transforms_execute() {
     let _ = df.coalesce(1).collect().unwrap();
     let _ = df
         .repartition_by_range(2, vec![expr(col("id"))])
+        .unwrap()
         .collect()
         .unwrap();
     let _ = df.repartition_by_id(2, col("id")).collect().unwrap();
diff --git a/docs/compatibility.md b/docs/compatibility.md
index fc96ff7d..9d4542a1 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -71,6 +71,45 @@ helpers accept `impl Into<Arc<LogicalPlan>>`, so they accept 
either an owned
 `LogicalPlan` or an existing `Arc<LogicalPlan>`. Serialization still produces 
the
 same protobuf tree; sharing does not deduplicate repeated relations on the 
wire.
 
+`LogicalPlan` implements `Drop`, so that a plan of many levels is dropped 
without
+recursing. A field can therefore not be moved out of an owned `LogicalPlan`:
+destructuring one by value is a compile error (E0509). Match on a reference 
instead
+(`match &plan`, or `match plan.as_ref()` of an `Arc<LogicalPlan>`) and clone 
the
+fields you need; the inputs are `Arc`s, so cloning them shares them.
+
+`LogicalPlan::Raw` adds a `depth` field: the levels of its relation as a plan, 
with
+those of the DataFrames that it holds, as `pyspark.ml` builds a relation over 
its
+input. They count for `MAX_PLAN_DEPTH`, as PySpark's serializer counts the 
plan of the
+input within its own. Code that constructs the variant directly sets it to 1 
for a
+relation without nested plans. `LogicalPlan::try_to_proto` serializes a plan 
as a
+request does: a plan deeper than `MAX_PLAN_DEPTH`, or with an expression 
deeper than
+`MAX_EXPRESSION_DEPTH`, is a `RecursionError`. `to_proto` still serializes a 
plan of
+any depth, but prost encodes and drops a protobuf by recursing, so the proto 
of a plan
+of many thousands of levels can overflow a small stack.
+
+`Value` and `LiteralExpression` add a `YearMonthInterval(i32)` variant for 
signed
+months. Collect gives it for a year-month interval, where it gave the text of 
the
+interval (`Value::String("1-0")`), so that a pivot on collected values names 
its
+columns as the pivot without values does (`INTERVAL '1-0' YEAR TO MONTH`), and
+`create_dataframe` takes it for a year-month interval column. Downstream 
exhaustive
+matches on these enums must handle the new variant. The Python client still 
raises
+`NOT_IMPLEMENTED` when it collects a year-month interval, as PySpark does.
+
+`DataFrame::repartition_by_range` and `repartition_by_range_opt` return a 
`Result`.
+As PySpark's `repartitionByRange`, a partition count that is not positive is
+`VALUE_NOT_POSITIVE` and an empty column list `CANNOT_BE_EMPTY`. Before, the 
server
+split the rows round-robin for an empty column list. `StatFunctions::sample_by`
+returns a `Result` too: a stratum that is not a literal is
+`DISALLOWED_TYPE_FOR_CONTAINER`, as PySpark rejects a key that is not a float, 
an int
+or a str. Before, it was sent as an empty literal, which failed only when the
+DataFrame ran.
+
+A panic of a native `StreamingQueryListener` on an event of the listener bus is
+isolated, as on the started event and as PySpark isolates the exception of a 
listener:
+it is reported, the other listeners still get the event, and the subscription 
goes on.
+Before, it ended the subscription and removed every listener. An error that
+`try_on_event` returns still ends it.
+
 The random functions `rand`, `randn`, `uuid`, `shuffle`, `uniform`, `randstr` 
and
 `count_min_sketch` draw a new seed for each call, as PySpark and the Scala 
client do.
 Before, each sent the same fixed seed, so two `uuid()` columns, or the 
`uuid()` of
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 92a946c5..b93b26a8 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -4944,6 +4944,91 @@ def test_row_construction_and_access():
     assert 1 in Row(1, 2) and 99 not in Row(1, 2)
 
 
[email protected](
+    "rows, start_offset, message",
+    [
+        (4, 0, "Expected 4 rows in arrow batch but got 3."),
+        (
+            3,
+            2,
+            "Expected arrow batch to start at row offset 0 in results, but 
received arrow "
+            "batch starting at offset 2.",
+        ),
+        (3, 0, None),
+        (3, None, None),
+    ],
+)
+def test_collect_checks_the_rows_and_the_offset_of_each_arrow_batch_as_pyspark(
+    mock_connect, rows, start_offset, message
+):
+    # As PySpark's `_execute_and_fetch_as_iterator`: a batch must hold the 
rows that it counts,
+    # and start where the rows before it end, if it says where it starts.
+    pa = pytest.importorskip("pyarrow")
+    from pyspark.errors import PySparkException
+
+    spark, service = mock_connect
+    batch = pa.record_batch([pa.array([1, 2, 3])], names=["id"])
+    sink = pa.BufferOutputStream()
+    with pa.ipc.new_stream(sink, batch.schema) as writer:
+        writer.write_batch(batch)
+    # ExecutePlanResponse.arrow_batch=2: row_count=1, data=2, start_offset=3.
+    fields = varint_field(1, rows) + message_field(2, 
sink.getvalue().to_pybytes())
+    if start_offset is not None:
+        fields += varint_field(3, start_offset)
+    service.execute_payload = message_field(2, fields)
+    if message is None:
+        assert spark.range(3).collect() == [Row(id=1), Row(id=2), Row(id=3)]
+    else:
+        with pytest.raises(PySparkException, match=re.escape(message)):
+            spark.range(3).collect()
+
+
+def 
test_invalid_utf8_of_a_struct_column_is_raised_field_by_field_as_pyspark(mock_connect):
+    # PySpark converts a struct column in bulk, field by field: with an 
invalid `y` in row 0 and
+    # an invalid `x` in row 1, it raises for the `x` of row 1, the first 
invalid string of `x`.
+    pa = pytest.importorskip("pyarrow")
+    spark, service = mock_connect
+
+    def strings(*values):
+        offsets = [0]
+        for value in values:
+            offsets.append(offsets[-1] + len(value))
+        buffers = [None, pa.py_buffer(array.array("i", offsets)), 
pa.py_buffer(b"".join(values))]
+        return pa.Array.from_buffers(pa.string(), len(values), buffers)
+
+    column = pa.StructArray.from_arrays(
+        [strings(b"ok", b"\xc3"), strings(b"\x80", b"ok")], names=["x", "y"]
+    )
+    batch = pa.record_batch([column], names=["s"])
+    sink = pa.BufferOutputStream()
+    with pa.ipc.new_stream(sink, batch.schema) as writer:
+        writer.write_batch(batch)
+    # ExecutePlanResponse.arrow_batch=2: row_count=1, data=2.
+    service.execute_payload = message_field(
+        2, varint_field(1, 2) + message_field(2, sink.getvalue().to_pybytes())
+    )
+    with pytest.raises(UnicodeDecodeError) as raised:
+        spark.range(2).collect()
+    assert raised.value.object == b"\xc3"
+    assert "can't decode byte 0xc3 in position 0" in str(raised.value)
+
+
+def 
test_client_release_session_after_stop_raises_no_active_session_as_pyspark(mock_connect):
+    # As the `_stub` of PySpark's closed client: nothing is sent.
+    from pyspark.errors.exceptions.connect import SparkConnectException
+    from pyspark.sql.connect.session import SparkSession as ConnectSession
+
+    _, service = mock_connect
+    session = ConnectSession(connection=service.remote)
+    client = session.client
+    session.stop()
+    released = service.release_session_calls
+    with pytest.raises(SparkConnectException) as raised:
+        client.release_session()
+    assert raised.value.getCondition() == "NO_ACTIVE_SESSION"
+    assert service.release_session_calls == released
+
+
 def test_row_iteration():
     """Test iterating over Row values."""
     from pyspark.sql import Row


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

Reply via email to