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 50046d72 [SPARK-61397][CONNECT] Raise SparkConnectException for a 
malformed chunked Arrow batch, as PySpark does
50046d72 is described below

commit 50046d728f906278fb373336a60c89031fe67275
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 09:39:14 2026 +0900

    [SPARK-61397][CONNECT] Raise SparkConnectException for a malformed chunked 
Arrow batch, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61397](https://issues.apache.org/jira/browse/SPARK-61397): a 
follow-up of #444 (SPARK-61262) and #472 (SPARK-61367), from a review of #444. 
A malformed chunked Arrow batch now raises `SparkConnectException` in the 
Python drop-in, with PySpark's messages, instead of `PySparkRuntimeError`:
    
    - A new `SparkErrorKind::ConnectMessage`, built by 
`SparkError::connect_exception_msg`: a `SparkConnectException` of a plain 
message, without an error class. The drop-in raises it as 
`pyspark.errors.exceptions.connect.SparkConnectException`.
    - The chunk-assembly errors of `crates/spark-connect/src/arrow_chunks.rs` 
use it, including the offset and row-count checks of #472.
    - The docs of the core client's `execute_plan`, `execute_plan_reattachable` 
and `ReattachableResponseStream` say that the raw responses of a batch over the 
chunk size are its chunks, partial IPC bytes in `arrow_batch.data`, which a 
consumer joins in order, as the higher-level streams and `DataFrame::collect` 
do. No behavior change there.
    
    ### Why are the changes needed?
    
    A chunk of an Arrow batch that is out of order, or a batch that does not 
start where the rows before it end, raised a plain Connect error, which the 
drop-in maps to `PySparkRuntimeError`. PySpark 4.3.0 raises 
`SparkConnectException` for the same conditions (`client/core.py`), so `except 
SparkConnectException` did not catch ours:
    
    ```
    # the server sends chunk index 2 after index 0 of 3
    before: PySparkRuntimeError: Expected chunk index 1 of the arrow batch but 
got 2.
    after:  SparkConnectException: Expected chunk index 1 of the arrow batch 
but got 2.
    ```
    
    The reference client, against the same mock server and responses, raises 
the same exception with the same messages.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. A malformed chunked Arrow batch raises `SparkConnectException` instead 
of `PySparkRuntimeError`, with the same message. The core crate gets a new 
`SparkErrorKind` variant and constructor.
    
    ### How was this patch tested?
    
    - An offline test, 
`test_malformed_arrow_chunks_raise_spark_connect_exception_as_pyspark`, whose 
mock server streams the responses of three malformed results (a chunk index 
skipped, a batch that starts at chunk 1, a batch at the wrong offset). It 
checks the exception type, the message and no error class, and fails without 
the change.
    - A Rust assertion on the kind in `a_chunk_out_of_order_is_an_error`.
    - `cargo test -p apache-spark-connect -p apache-spark-connect-core 
--release --lib`, the `--no-run` builds, `cargo fmt --check`, 
`scripts/audit_no_stubs.sh`, the full offline drop-in suite, and the 
chunked-collect e2e tests against a Spark 4.3.0 server.
    
    ### 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 #483 from HyukjinKwon/SPARK-61397-chunk-errors-connect-exception.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/errors.rs          | 10 +++++---
 crates/spark-connect-core/src/client.rs  | 23 +++++++++++++++++
 crates/spark-connect-core/src/error.rs   | 14 +++++++++++
 crates/spark-connect/src/arrow_chunks.rs | 17 +++++++------
 python/tests/_mock_connect_server.py     | 12 +++++++--
 python/tests/test_dropin_offline.py      | 43 ++++++++++++++++++++++++++++++++
 6 files changed, 107 insertions(+), 12 deletions(-)

diff --git a/crates/pyspark-rs/src/errors.rs b/crates/pyspark-rs/src/errors.rs
index ba73a360..a4d6a395 100644
--- a/crates/pyspark-rs/src/errors.rs
+++ b/crates/pyspark-rs/src/errors.rs
@@ -51,6 +51,8 @@ fn kind_to_pyspark_class_name(kind: SparkErrorKind) -> 
&'static str {
         // so we fall back to PySparkRuntimeError. An error that the server 
raised is built by
         // `server_error_to_py` instead.
         SparkErrorKind::Connect => "PySparkRuntimeError",
+        // A `SparkConnectException` of a plain message: 
`spark_error_to_py_exception` raises it.
+        SparkErrorKind::ConnectMessage => "PySparkRuntimeError",
         SparkErrorKind::ConnectGrpc => "PySparkRuntimeError",
         SparkErrorKind::InvalidPlanInput => "PySparkRuntimeError",
         SparkErrorKind::Spark => "PySparkRuntimeError",
@@ -264,9 +266,11 @@ pub fn spark_error_to_py_exception(err: SparkError) -> 
PyErr {
             }
         };
 
-        // A classed Connect error, such as `NO_ACTIVE_SESSION`, is a 
`SparkConnectException`, as
-        // the reference client raises it.
-        let exc_class = if err.kind == SparkErrorKind::Connect && 
!err.error_class.is_empty() {
+        // A classed Connect error, such as `NO_ACTIVE_SESSION`, and a Connect 
error of a plain
+        // message are `SparkConnectException`s, as the reference client 
raises them.
+        let connect_class = err.kind == SparkErrorKind::ConnectMessage
+            || (err.kind == SparkErrorKind::Connect && 
!err.error_class.is_empty());
+        let exc_class = if connect_class {
             py.import("pyspark.errors.exceptions.connect")
                 .and_then(|module| module.getattr("SparkConnectException"))
         } else {
diff --git a/crates/spark-connect-core/src/client.rs 
b/crates/spark-connect-core/src/client.rs
index 460d2900..0f25f63a 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -1084,6 +1084,10 @@ impl SparkConnectClient {
 
     /// Execute a plan and return a stream of responses.
     ///
+    /// The request allows the server to chunk an Arrow batch too large for 
one message, so a
+    /// batch may arrive as several responses, whose `arrow_batch` fields are 
not decodable on
+    /// their own. The chunks are returned as they arrive: see 
[`ReattachableResponseStream`].
+    ///
     /// Mirrors 
`pyspark.sql.connect.client.core.SparkConnectClient.execute_plan`.
     pub async fn execute_plan(
         &self,
@@ -1292,6 +1296,9 @@ impl SparkConnectClient {
     /// or the server ends it before `ResultComplete`, transparently resumes 
it with
     /// `ReattachExecute` from the last observed `response_id`. The stream 
releases the
     /// execution on the server with `ReleaseExecute` (see 
[`ReattachableResponseStream`]).
+    ///
+    /// The responses are the raw responses of the execution, chunks included, 
as the server
+    /// sent them: see [`ReattachableResponseStream`] for how a chunked Arrow 
batch is read.
     /// Mirrors the reference reattachable execute path.
     pub async fn execute_plan_reattachable(
         &self,
@@ -2159,6 +2166,22 @@ impl SparkConnectClient {
 /// execution once the result is complete, the stream fails, or it is dropped, 
so that the
 /// server does not keep them until the execution is abandoned. Mirrors
 /// 
`pyspark.sql.connect.client.reattach.ExecutePlanResponseReattachableIterator`.
+///
+/// # Chunked Arrow batches
+///
+/// The execution allows the server to split an Arrow batch that is too large 
for one message.
+/// The chunks of a batch come as responses in order, each with an 
`arrow_batch` whose
+/// `chunk_index` is its place among the `num_chunks_in_batch` chunks of the 
batch. Other
+/// responses may come between the chunks. `start_offset`, when the server 
sets it, is the row
+/// where the batch starts, and `row_count` is the number of rows of the whole 
batch, not of
+/// the chunk.
+///
+/// This stream returns the responses as they arrive, so the 
`arrow_batch.data` of a chunk
+/// is a part of the Arrow IPC stream of its batch, not a batch of its own. A 
consumer that
+/// reads the responses itself must join the `data` of the chunks of a batch, 
in order, before
+/// it decodes the batch, and must check the order and the count of the chunks 
as PySpark
+/// does. The high-level APIs of the `apache-spark-connect` crate, such as 
`DataFrame::collect`,
+/// do this join for their results.
 pub struct ReattachableResponseStream {
     /// The client that started the execution, whose stub, headers and session 
it uses.
     client: SparkConnectClient,
diff --git a/crates/spark-connect-core/src/error.rs 
b/crates/spark-connect-core/src/error.rs
index ccf28ca3..2be99f81 100644
--- a/crates/spark-connect-core/src/error.rs
+++ b/crates/spark-connect-core/src/error.rs
@@ -243,6 +243,10 @@ pub enum SparkErrorKind {
     ImportError,
     /// ``pyspark.errors.exceptions.connect.SparkConnectException`` and 
subclasses
     Connect,
+    /// ``pyspark.errors.exceptions.connect.SparkConnectException`` of a plain 
message, which has
+    /// no error class: the reference client raises it for a malformed result, 
such as a chunk of
+    /// an Arrow batch that is out of order.
+    ConnectMessage,
     /// ``pyspark.errors.exceptions.connect.SparkConnectGrpcException``
     ConnectGrpc,
     /// ``pyspark.errors.exceptions.base.AnalysisException``
@@ -331,6 +335,15 @@ impl SparkError {
         }
     }
 
+    /// Create a ConnectMessage-kind error with a plain message (no error 
class), which is a
+    /// `SparkConnectException` in Python.
+    pub fn connect_exception_msg(message: impl Into<String>) -> Self {
+        Self {
+            kind: SparkErrorKind::ConnectMessage,
+            ..Self::connect_msg(message)
+        }
+    }
+
     /// Create a ValueError-kind error with a plain message (no error class).
     ///
     /// For invalid client-side configuration (e.g. a malformed connection 
string)
@@ -1242,6 +1255,7 @@ mod tests {
         let _ = SparkErrorKind::PicklingError;
         let _ = SparkErrorKind::ImportError;
         let _ = SparkErrorKind::Connect;
+        let _ = SparkErrorKind::ConnectMessage;
         let _ = SparkErrorKind::ConnectGrpc;
         let _ = SparkErrorKind::Analysis;
         let _ = SparkErrorKind::Parse;
diff --git a/crates/spark-connect/src/arrow_chunks.rs 
b/crates/spark-connect/src/arrow_chunks.rs
index 7dfb2537..c7727a62 100644
--- a/crates/spark-connect/src/arrow_chunks.rs
+++ b/crates/spark-connect/src/arrow_chunks.rs
@@ -42,7 +42,7 @@ impl ArrowChunkAssembler {
             None | Some(0) => 1,
             Some(n) if n > 0 => n,
             Some(n) => {
-                return Err(SparkError::connect_msg(format!(
+                return Err(SparkError::connect_exception_msg(format!(
                     "Invalid number of chunks {n} in an arrow batch."
                 )))
             }
@@ -52,14 +52,14 @@ impl ArrowChunkAssembler {
             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!(
+                    return Err(SparkError::connect_exception_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!(
+                    return Err(SparkError::connect_exception_msg(format!(
                         "Expected chunk index 0 of the next arrow batch but 
got {index}."
                     )));
                 }
@@ -89,13 +89,13 @@ impl ArrowChunkAssembler {
             }
             Some(pending) => {
                 if index != pending.received {
-                    return Err(SparkError::connect_msg(format!(
+                    return Err(SparkError::connect_exception_msg(format!(
                         "Expected chunk index {} of the arrow batch but got 
{index}.",
                         pending.received
                     )));
                 }
                 if num_chunks != pending.num_chunks || batch.row_count != 
pending.row_count {
-                    return Err(SparkError::connect_msg(format!(
+                    return Err(SparkError::connect_exception_msg(format!(
                         "Chunk {index} of an arrow batch of {} rows in {} 
chunks does not match \
                          the batch of {} rows in {} chunks.",
                         batch.row_count, num_chunks, pending.row_count, 
pending.num_chunks
@@ -139,7 +139,7 @@ impl ArrowChunkAssembler {
             .into_iter()
             .fold(0i64, |rows, record_batch| 
rows.saturating_add(record_batch));
         if rows != batch.row_count {
-            return Err(SparkError::connect_msg(format!(
+            return Err(SparkError::connect_exception_msg(format!(
                 "Expected {} rows in arrow batch but got {rows}.",
                 batch.row_count
             )));
@@ -166,7 +166,7 @@ impl ArrowChunkAssembler {
     pub(crate) fn finish(&self) -> Result<()> {
         match &self.pending {
             None => Ok(()),
-            Some(pending) => Err(SparkError::connect_msg(format!(
+            Some(pending) => Err(SparkError::connect_exception_msg(format!(
                 "The execution ended after {} of {} chunks of an arrow batch.",
                 pending.received, pending.num_chunks
             ))),
@@ -214,6 +214,7 @@ fn record_batch_rows(data: &[u8]) -> Option<Vec<i64>> {
 mod tests {
     use super::*;
     use proto::execute_plan_response::{ArrowBatch, ResponseType};
+    use spark_connect_core::error::SparkErrorKind;
 
     fn chunk(index: i64, total: i64, rows: i64, data: &[u8]) -> 
proto::ExecutePlanResponse {
         proto::ExecutePlanResponse {
@@ -315,6 +316,8 @@ mod tests {
             error.message(),
             "Expected chunk index 1 of the arrow batch but got 2."
         );
+        // A SparkConnectException of a plain message, as PySpark raises it.
+        assert_eq!(error.kind, SparkErrorKind::ConnectMessage);
     }
 
     #[test]
diff --git a/python/tests/_mock_connect_server.py 
b/python/tests/_mock_connect_server.py
index 689cb188..92c0a30d 100644
--- a/python/tests/_mock_connect_server.py
+++ b/python/tests/_mock_connect_server.py
@@ -289,6 +289,7 @@ def serve(connection):
             self.execute_requests = []
             self.release_execute_requests = []
             self.execute_payload = b""
+            self.execute_payloads = None
             self.execute_failure = None
             self.execute_error = None
             self.retry_info_failures = []
@@ -420,6 +421,9 @@ def serve(connection):
         execute_requests = []
         release_execute_requests = []
         execute_payload = b""
+        # With `execute_payloads` set (a list of raw ExecutePlanResponse 
fields), the execution
+        # streams one response of each, r1, r2, ..., instead of 
`execute_payload`.
+        execute_payloads = None
         execute_failure = None
         # With `execute_error` set to (message, reason, metadata), ExecutePlan 
fails as the
         # server does for an error that it raised: INTERNAL, with a 
google.rpc.Status of an
@@ -673,7 +677,11 @@ def serve(connection):
             header = message_field(1, parse_message(request).get(1, [b""])[0]) 
+ message_field(
                 12, operation_id
             )
-            yield header + message_field(13, "r1") + self.execute_payload
+            payloads = (
+                [self.execute_payload] if self.execute_payloads is None else 
self.execute_payloads
+            )
+            for index, payload in enumerate(payloads, 1):
+                yield header + message_field(13, f"r{index}") + payload
             if block_result_complete:
                 released = self.wait_for_response(response_gate, operation_id, 
30)
                 if released == "interrupted":
@@ -684,7 +692,7 @@ def serve(connection):
                         "ResultComplete was not released by the test",
                     )
             result_complete_operations.append(operation_id)
-            yield header + message_field(13, "r2") + message_field(14, b"")
+            yield header + message_field(13, f"r{len(payloads) + 1}") + 
message_field(14, b"")
 
         def warnings_fields(self):
             # ConfigResponse.warnings=3, of `config_warnings`.
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 48374228..4f2ededf 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -1137,6 +1137,49 @@ def 
test_collect_of_a_string_that_is_not_utf8_raises_as_pyspark(mock_connect):
     assert spark.range(1).collect() == [Row(s="a")]
     assert len(list(spark.range(1).toLocalIterator())) == 1
 
+def 
test_malformed_arrow_chunks_raise_spark_connect_exception_as_pyspark(mock_connect):
+    # As PySpark Connect's ExecuteAndFetchAsIterator: a chunk that is not the 
next one of its
+    # batch, or a batch that does not start where the rows before it end, 
raises a
+    # SparkConnectException of the message of the reference client, with no 
error class.
+    from pyspark.errors.exceptions.connect import SparkConnectException
+
+    spark, service = mock_connect
+
+    def batch(index, num_chunks, data, start_offset=None):
+        # ExecutePlanResponse.arrow_batch=2: ArrowBatch.row_count=1, data=2, 
start_offset=3,
+        # chunk_index=4, num_chunks_in_batch=5. A batch that is not chunked 
has no chunk fields.
+        fields = varint_field(1, 1) + message_field(2, data)
+        if start_offset is not None:
+            fields += varint_field(3, start_offset)
+        if num_chunks is not None:
+            fields += varint_field(4, index) + varint_field(5, num_chunks)
+        return message_field(2, fields)
+
+    cases = [
+        (
+            [batch(0, 3, b"a", start_offset=0), batch(2, 3, b"c")],
+            "Expected chunk index 1 of the arrow batch but got 2.",
+        ),
+        (
+            [batch(1, 2, b"b", start_offset=0)],
+            "Expected chunk index 0 of the next arrow batch but got 1.",
+        ),
+        (
+            [batch(0, None, b"a", start_offset=5)],
+            "Expected arrow batch to start at row offset 0 in results, but 
received arrow batch "
+            "starting at offset 5.",
+        ),
+    ]
+    for payloads, message in cases:
+        service.execute_payloads = payloads
+        with pytest.raises(SparkConnectException) as e:
+            spark.range(1).collect()
+        assert type(e.value) is SparkConnectException
+        assert str(e.value) == message
+        assert e.value.getCondition() is None
+    service.execute_payloads = None
+
+
 def test_tags_are_those_of_each_thread_as_pyspark(mock_connect):
     # As PySpark's: the tags of addTag are those of the current thread, of a 
set of getTags,
     # which the operations that the thread starts carry; a new thread starts 
without tags.


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

Reply via email to