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 7fa1dcc0 [SPARK-61262][CONNECT] Allow Arrow batch chunking in 
ExecutePlan, so that a value over 128 MB can be collected, as PySpark does
7fa1dcc0 is described below

commit 7fa1dcc065bc41d7d105af8693441e2c465a04d1
Author: Timothy Meehan <[email protected]>
AuthorDate: Tue Nov 10 10:33:37 2026 +0900

    [SPARK-61262][CONNECT] Allow Arrow batch chunking in ExecutePlan, so that a 
value over 128 MB can be collected, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61262](https://issues.apache.org/jira/browse/SPARK-61262): Allow 
Arrow batch chunking in ExecutePlan, so that a value over 128 MB can be 
collected, as PySpark does.
    
    - `SparkConnectClient::execute_plan` and `execute_plan_reattachable` 
(`spark-connect-core`) add `result_chunking_options { 
allow_arrow_batch_chunking: true }` to each ExecutePlan request, before the 
session hooks run, as PySpark's client does. No preferred chunk size is set. 
The protocol's ReattachExecute request has no request options, so the reattach 
does not carry the option; the server keeps the chunking of the execution it 
started.
    - The new `arrow_chunks` module of `spark-connect` joins the chunks of an 
Arrow batch, in order. `ExecutionStream::message`, which every execution 
consumer reads through (collect, collect with schema, collect record batches, 
`to_local_iterator` with and without prefetch, catalog operations, command 
results), applies it, so the batch is joined in one place. A chunk that is not 
the last one of its batch is returned without a batch; the last one carries the 
whole batch.
    - Errors: a chunk out of order and a batch that starts at a later chunk, as 
PySpark's iterator raises them; and, stricter than PySpark, chunks of one batch 
whose count or row count differ, a negative chunk count, and a stream that ends 
inside a batch (PySpark drops such a batch silently, which would return fewer 
rows). PySpark's checks of every batch's `start_offset` and decoded row count 
are not added here, as they are not specific to chunking.
    
    ### Why are the changes needed?
    
    The server sends an Arrow batch larger than the gRPC message limit (128 
MiB) as one message unless the client asks for chunking. Without the option, 
`collect` of a single value over 128 MiB fails with `decoded message length too 
large`. PySpark asks for chunking and joins the chunks, so the same query 
returns the row there.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. A collect, or a stream of rows, whose Arrow batch is larger than the 
message limit now succeeds instead of failing with a gRPC message-size error. 
No API changes. A chunked batch left unfinished at the end of the stream is an 
error rather than a truncated result.
    
    ### How was this patch tested?
    
    - Offline unit tests in `arrow_chunks` (`apache-spark-connect --lib`): 
chunks are joined in order into the batch; a batch that is not chunked passes 
through; responses without a batch may come between chunks; out-of-order 
chunks, a batch starting at a later chunk, a whole batch in the middle of 
chunks, chunks that disagree on the count or the row count, a negative count, 
and a stream that ends inside a batch are errors.
    - `executions_ask_the_server_to_chunk_arrow_batches` 
(`spark-connect-core/tests/server_session.rs`, against the loopback mock 
server): the ExecutePlan requests of both execution paths carry exactly one 
chunking option with `allow_arrow_batch_chunking: true` and no preferred chunk 
size. It fails when the option is not added.
    - `collect_joins_the_chunks_of_a_value_over_the_message_limit` 
(`spark-connect/tests/e2e_dataframe.rs`, server-gated): collects `repeat('x', 
129 MiB)`, one row, and checks its length.
    - Live e2e: `collect_joins_the_chunks_of_a_value_over_the_message_limit` 
passes against a local Spark 4.3.0 Connect server (`--test-threads=1`, 3.1 s, 
peak RSS about 525 MB). With the chunking option removed from the reattachable 
path, it fails with `decoded message length too large: found 135266902 bytes, 
the limit is: 134217728 bytes`.
    - Issue repro, `repeat('x', 140 * 1024 * 1024)` collected on the same 
server: the reference PySpark 4.3.0 client returns the row (length 146800640), 
and the drop-in built from this change returns the same row.
    - Pre-push checks: `cargo test -p apache-spark-connect --release --lib`, 
`--no-run`, and `--features wasm-udf --no-run`; `cargo fmt --all --check`; 
`cargo clippy --workspace --all-targets --release` reports no diagnostic on a 
changed line.
    - The Python client reads its results through the same stream: the offline 
Python suites (2927 passed, 8 skipped) and the live drop-in, Arrow and ML 
suites against a local Spark 4.3.0 server (236 passed, 1 skipped) pass.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5 and Claude Haiku 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #444 from tdcmeehan/SPARK-61262-arrow-batch-chunking.
    
    Lead-authored-by: Timothy Meehan <[email protected]>
    Co-authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/spark-connect-core/src/client.rs           |  17 ++
 crates/spark-connect-core/tests/server_session.rs |  38 +++
 crates/spark-connect/src/arrow_chunks.rs          | 293 ++++++++++++++++++++++
 crates/spark-connect/src/lib.rs                   |   1 +
 crates/spark-connect/src/progress.rs              |  13 +-
 crates/spark-connect/tests/e2e_dataframe.rs       |  20 ++
 6 files changed, 379 insertions(+), 3 deletions(-)

diff --git a/crates/spark-connect-core/src/client.rs 
b/crates/spark-connect-core/src/client.rs
index 24e4cb2b..1509315e 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -258,6 +258,21 @@ fn retry_exception_bound_passed(
 pub type ExecutePlanHook =
     std::sync::Arc<dyn Fn(ExecutePlanRequest) -> Result<ExecutePlanRequest> + 
Send + Sync>;
 
+/// Let the server split the Arrow batches too large for one message into 
chunks, which the
+/// stream of the execution joins, as PySpark's client does, without a 
preferred chunk size.
+fn allow_arrow_batch_chunking(request: &mut ExecutePlanRequest) {
+    use 
spark_connect_proto::execute_plan_request::request_option::RequestOption as 
Kind;
+    use spark_connect_proto::execute_plan_request::RequestOption;
+    request.request_options.push(RequestOption {
+        request_option: Some(Kind::ResultChunkingOptions(
+            spark_connect_proto::ResultChunkingOptions {
+                allow_arrow_batch_chunking: true,
+                preferred_arrow_chunk_size: None,
+            },
+        )),
+    });
+}
+
 /// A Spark Connect client for communicating with a remote Spark server.
 ///
 /// Mirrors `pyspark.sql.connect.client.core.SparkConnectClient`.
@@ -773,6 +788,7 @@ impl SparkConnectClient {
         mut request: ExecutePlanRequest,
     ) -> Result<Streaming<ExecutePlanResponse>> {
         self.ensure_open()?;
+        allow_arrow_batch_chunking(&mut request);
         self.extend_user_context(&mut request.user_context);
         self.fill_user_context(&mut request.user_context);
         self.observe_on(&mut request.client_observed_server_side_session_id);
@@ -966,6 +982,7 @@ impl SparkConnectClient {
         mut request: ExecutePlanRequest,
     ) -> Result<ReattachableResponseStream> {
         self.ensure_open()?;
+        allow_arrow_batch_chunking(&mut request);
         self.extend_user_context(&mut request.user_context);
         // Before the iterator: its ReattachExecute and ReleaseExecute 
requests take the
         // user context of this request, and the request of the hook, as 
PySpark's iterator
diff --git a/crates/spark-connect-core/tests/server_session.rs 
b/crates/spark-connect-core/tests/server_session.rs
index bcf92548..5503d96f 100644
--- a/crates/spark-connect-core/tests/server_session.rs
+++ b/crates/spark-connect-core/tests/server_session.rs
@@ -503,3 +503,41 @@ async fn 
a_client_without_session_tracking_passes_the_ids_of_its_requests_throug
         );
     }
 }
+
+#[tokio::test]
+async fn executions_ask_the_server_to_chunk_arrow_batches() {
+    use 
spark_connect_proto::execute_plan_request::request_option::RequestOption;
+    use spark_connect_proto::ResultChunkingOptions;
+
+    let fixture = Fixture::start().await;
+    let client = fixture.client().await;
+
+    // A reattachable execution that drops after its first response, which is 
reattached, and a
+    // plain ExecutePlan. The reattach has no request options to carry the 
option in.
+    *fixture.state.drop_next_execute.lock().unwrap() = true;
+    run_execution(&client).await;
+    let mut stream = 
client.execute_plan(execute_request(&client)).await.unwrap();
+    while stream.message().await.unwrap().is_some() {}
+
+    let executes = fixture
+        .state
+        .requests_of::<ExecutePlanRequest>("ExecutePlan");
+    assert_eq!(executes.len(), 2);
+    for request in &executes {
+        let chunking: Vec<ResultChunkingOptions> = request
+            .request_options
+            .iter()
+            .filter_map(|option| match &option.request_option {
+                Some(RequestOption::ResultChunkingOptions(options)) => 
Some(*options),
+                _ => None,
+            })
+            .collect();
+        assert_eq!(
+            chunking,
+            [ResultChunkingOptions {
+                allow_arrow_batch_chunking: true,
+                preferred_arrow_chunk_size: None,
+            }]
+        );
+    }
+}
diff --git a/crates/spark-connect/src/arrow_chunks.rs 
b/crates/spark-connect/src/arrow_chunks.rs
new file mode 100644
index 00000000..52795024
--- /dev/null
+++ b/crates/spark-connect/src/arrow_chunks.rs
@@ -0,0 +1,293 @@
+//! The joining of the chunks of the Arrow batches that the server splits, as 
PySpark's
+//! `ExecuteAndFetchAsIterator` joins them.
+//!
+//! 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.
+
+use spark_connect_core::error::{Result, SparkError};
+use spark_connect_proto as proto;
+
+/// The chunks of the batch being assembled, received so far.
+#[derive(Default)]
+pub(crate) struct ArrowChunkAssembler {
+    pending: Option<PendingBatch>,
+}
+
+struct PendingBatch {
+    row_count: i64,
+    start_offset: Option<i64>,
+    num_chunks: i64,
+    received: i64,
+    data: Vec<u8>,
+}
+
+impl ArrowChunkAssembler {
+    /// Take the Arrow batch of `response` as the chunks of a batch: the batch 
of the response is
+    /// replaced by the whole batch once its last chunk is in, and removed 
while chunks are still
+    /// missing. Responses without an Arrow batch are left as they are, as are 
their other fields.
+    pub(crate) fn push(&mut self, response: &mut proto::ExecutePlanResponse) 
-> Result<()> {
+        let batch = match response.response_type.take() {
+            
Some(proto::execute_plan_response::ResponseType::ArrowBatch(batch)) => batch,
+            other => {
+                response.response_type = other;
+                return Ok(());
+            }
+        };
+        let num_chunks = match batch.num_chunks_in_batch {
+            None | Some(0) => 1,
+            Some(n) if n > 0 => n,
+            Some(n) => {
+                return Err(SparkError::connect_msg(format!(
+                    "Invalid number of chunks {n} in an arrow batch."
+                )))
+            }
+        };
+        let index = batch.chunk_index.unwrap_or(0);
+        let mut pending = match self.pending.take() {
+            None => {
+                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 {
+                    response.response_type = Some(
+                        
proto::execute_plan_response::ResponseType::ArrowBatch(batch),
+                    );
+                    return Ok(());
+                }
+                PendingBatch {
+                    row_count: batch.row_count,
+                    start_offset: batch.start_offset,
+                    num_chunks,
+                    received: 0,
+                    data: Vec::new(),
+                }
+            }
+            Some(pending) => {
+                if index != pending.received {
+                    return Err(SparkError::connect_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!(
+                        "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
+                    )));
+                }
+                pending
+            }
+        };
+        pending.data.extend_from_slice(&batch.data);
+        pending.received += 1;
+        if pending.received < pending.num_chunks {
+            self.pending = Some(pending);
+            return Ok(());
+        }
+        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,
+            },
+        ));
+        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(
+        &mut self,
+        response: Option<proto::ExecutePlanResponse>,
+    ) -> Result<Option<proto::ExecutePlanResponse>> {
+        let Some(mut response) = response else {
+            self.finish()?;
+            return Ok(None);
+        };
+        self.push(&mut response)?;
+        Ok(Some(response))
+    }
+
+    /// Check that no batch is left incomplete, once the stream of the 
execution has ended.
+    pub(crate) fn finish(&self) -> Result<()> {
+        match &self.pending {
+            None => Ok(()),
+            Some(pending) => Err(SparkError::connect_msg(format!(
+                "The execution ended after {} of {} chunks of an arrow batch.",
+                pending.received, pending.num_chunks
+            ))),
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use proto::execute_plan_response::{ArrowBatch, ResponseType};
+
+    fn chunk(index: i64, total: i64, rows: i64, data: &[u8]) -> 
proto::ExecutePlanResponse {
+        proto::ExecutePlanResponse {
+            response_id: format!("r{index}"),
+            response_type: Some(ResponseType::ArrowBatch(ArrowBatch {
+                row_count: rows,
+                data: data.to_vec().into(),
+                start_offset: (index == 0).then_some(5),
+                chunk_index: Some(index),
+                num_chunks_in_batch: Some(total),
+            })),
+            ..Default::default()
+        }
+    }
+
+    fn batch_of(response: &proto::ExecutePlanResponse) -> Option<&ArrowBatch> {
+        match &response.response_type {
+            Some(ResponseType::ArrowBatch(batch)) => Some(batch),
+            _ => None,
+        }
+    }
+
+    #[test]
+    fn chunks_are_joined_in_order_into_the_batch_they_make_up() {
+        let mut assembler = ArrowChunkAssembler::default();
+        let mut first = chunk(0, 3, 7, b"ab");
+        assembler.push(&mut first).unwrap();
+        assert!(first.response_type.is_none());
+        let mut second = chunk(1, 3, 7, b"cd");
+        assembler.push(&mut second).unwrap();
+        assert!(second.response_type.is_none());
+        let mut last = chunk(2, 3, 7, b"ef");
+        assembler.push(&mut last).unwrap();
+        assembler.finish().unwrap();
+
+        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.chunk_index, None);
+        assert_eq!(batch.num_chunks_in_batch, None);
+    }
+
+    #[test]
+    fn 
a_batch_that_is_not_chunked_passes_through_and_responses_without_one_are_kept() 
{
+        let mut assembler = ArrowChunkAssembler::default();
+        let mut whole = proto::ExecutePlanResponse {
+            response_type: Some(ResponseType::ArrowBatch(ArrowBatch {
+                row_count: 2,
+                data: b"whole".to_vec().into(),
+                ..Default::default()
+            })),
+            ..Default::default()
+        };
+        assembler.push(&mut whole).unwrap();
+        assert_eq!(&batch_of(&whole).unwrap().data[..], b"whole");
+
+        let mut zero = chunk(0, 0, 1, b"zero");
+        assembler.push(&mut zero).unwrap();
+        assert_eq!(&batch_of(&zero).unwrap().data[..], b"zero");
+
+        let mut metrics = proto::ExecutePlanResponse {
+            response_type: Some(ResponseType::ResultComplete(
+                proto::execute_plan_response::ResultComplete {},
+            )),
+            ..Default::default()
+        };
+        assembler.push(&mut metrics).unwrap();
+        assert!(matches!(
+            metrics.response_type,
+            Some(ResponseType::ResultComplete(_))
+        ));
+        assembler.finish().unwrap();
+    }
+
+    #[test]
+    fn a_response_without_a_batch_may_come_between_the_chunks() {
+        let mut assembler = ArrowChunkAssembler::default();
+        let mut first = chunk(0, 2, 1, b"x");
+        assembler.push(&mut first).unwrap();
+        let mut progress = proto::ExecutePlanResponse {
+            schema: Some(Default::default()),
+            ..Default::default()
+        };
+        assembler.push(&mut progress).unwrap();
+        assert!(progress.schema.is_some());
+        let mut last = chunk(1, 2, 1, b"y");
+        assembler.push(&mut last).unwrap();
+        assert_eq!(&batch_of(&last).unwrap().data[..], b"xy");
+    }
+
+    #[test]
+    fn a_chunk_out_of_order_is_an_error() {
+        let mut assembler = ArrowChunkAssembler::default();
+        assembler.push(&mut chunk(0, 3, 1, b"a")).unwrap();
+        let error = assembler.push(&mut chunk(2, 3, 1, b"c")).unwrap_err();
+        assert_eq!(
+            error.message(),
+            "Expected chunk index 1 of the arrow batch but got 2."
+        );
+    }
+
+    #[test]
+    fn a_batch_that_starts_at_a_later_chunk_is_an_error() {
+        let mut assembler = ArrowChunkAssembler::default();
+        let error = assembler.push(&mut chunk(1, 2, 1, b"b")).unwrap_err();
+        assert_eq!(
+            error.message(),
+            "Expected chunk index 0 of the next arrow batch but got 1."
+        );
+    }
+
+    #[test]
+    fn a_whole_batch_in_the_middle_of_chunks_is_an_error() {
+        let mut assembler = ArrowChunkAssembler::default();
+        assembler.push(&mut chunk(0, 2, 1, b"a")).unwrap();
+        let mut whole = chunk(0, 0, 1, b"b");
+        let error = assembler.push(&mut whole).unwrap_err();
+        assert_eq!(
+            error.message(),
+            "Expected chunk index 1 of the arrow batch but got 0."
+        );
+    }
+
+    #[test]
+    fn chunks_that_disagree_on_the_batch_are_an_error() {
+        let mut assembler = ArrowChunkAssembler::default();
+        assembler.push(&mut chunk(0, 3, 4, b"a")).unwrap();
+        let error = assembler.push(&mut chunk(1, 2, 4, b"b")).unwrap_err();
+        assert_eq!(
+            error.message(),
+            "Chunk 1 of an arrow batch of 4 rows in 2 chunks does not match 
the batch of 4 rows \
+             in 3 chunks."
+        );
+
+        let mut assembler = ArrowChunkAssembler::default();
+        assembler.push(&mut chunk(0, 2, 4, b"a")).unwrap();
+        assert!(assembler.push(&mut chunk(1, 2, 5, b"b")).is_err());
+    }
+
+    #[test]
+    fn a_negative_number_of_chunks_is_an_error() {
+        let mut assembler = ArrowChunkAssembler::default();
+        let error = assembler.push(&mut chunk(0, -1, 1, b"a")).unwrap_err();
+        assert_eq!(
+            error.message(),
+            "Invalid number of chunks -1 in an arrow batch."
+        );
+    }
+
+    #[test]
+    fn a_stream_that_ends_inside_a_batch_is_an_error() {
+        let mut assembler = ArrowChunkAssembler::default();
+        assembler.push(&mut chunk(0, 3, 1, b"a")).unwrap();
+        let error = assembler.finish().unwrap_err();
+        assert_eq!(
+            error.message(),
+            "The execution ended after 1 of 3 chunks of an arrow batch."
+        );
+    }
+}
diff --git a/crates/spark-connect/src/lib.rs b/crates/spark-connect/src/lib.rs
index 91b1a9e8..6acc4f0c 100644
--- a/crates/spark-connect/src/lib.rs
+++ b/crates/spark-connect/src/lib.rs
@@ -15,6 +15,7 @@
 
 #![allow(clippy::result_large_err)] // SparkError is large; changing the type 
would break the API
 
+mod arrow_chunks;
 mod arrow_input;
 pub mod catalog;
 pub mod column;
diff --git a/crates/spark-connect/src/progress.rs 
b/crates/spark-connect/src/progress.rs
index c1a20eae..9f78f8dd 100644
--- a/crates/spark-connect/src/progress.rs
+++ b/crates/spark-connect/src/progress.rs
@@ -138,14 +138,21 @@ impl Drop for ProgressTracker {
 pub(crate) struct ExecutionStream {
     stream: ReattachableResponseStream,
     progress: ProgressTracker,
+    chunks: crate::arrow_chunks::ArrowChunkAssembler,
 }
 
 impl ExecutionStream {
     pub(crate) fn new(stream: ReattachableResponseStream, progress: 
ProgressTracker) -> Self {
-        ExecutionStream { stream, progress }
+        ExecutionStream {
+            stream,
+            progress,
+            chunks: Default::default(),
+        }
     }
 
-    /// The next response of the execution, as 
`ReattachableResponseStream::message`.
+    /// The next response of the execution, as 
`ReattachableResponseStream::message`, with the
+    /// chunks of an Arrow batch joined into the batch: the response of a 
chunk that is not the
+    /// last one has no batch.
     pub(crate) async fn message(&mut self) -> 
Result<Option<proto::ExecutePlanResponse>> {
         let response = self.stream.message().await?;
         if let Some(response) = &response {
@@ -155,7 +162,7 @@ impl ExecutionStream {
                 self.progress.update(progress, &response.operation_id)?;
             }
         }
-        Ok(response)
+        self.chunks.join(response)
     }
 }
 
diff --git a/crates/spark-connect/tests/e2e_dataframe.rs 
b/crates/spark-connect/tests/e2e_dataframe.rs
index 02b81252..f69e0251 100644
--- a/crates/spark-connect/tests/e2e_dataframe.rs
+++ b/crates/spark-connect/tests/e2e_dataframe.rs
@@ -685,6 +685,26 @@ fn subqueries_return_the_rows_of_pyspark() {
     );
 }
 
+/// A value over the 128 MiB message limit arrives as the chunks of its Arrow 
batch, which
+/// `collect` joins.
+#[test]
+fn collect_joins_the_chunks_of_a_value_over_the_message_limit() {
+    if !should_run() {
+        return;
+    }
+    let s = session();
+    let len: i64 = 129 * 1024 * 1024;
+    let df = s.range(1).expect("range").select(vec![f::repeat(
+        spark_connect::column::lit_string("x"),
+        lit(len),
+    )]);
+    let rows = df.collect().unwrap();
+    assert_eq!(rows.len(), 1);
+    let value = rows[0].get(0).unwrap().as_str().unwrap();
+    assert_eq!(value.len(), len as usize);
+    assert!(value.bytes().all(|b| b == b'x'));
+}
+
 /// `repartition_by_range` splits the ids into contiguous ranges, as PySpark's
 /// `repartitionByRange` does; a hash split of the same column would not.
 #[test]


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

Reply via email to