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 fa564506 [SPARK-61469][CONNECT] Drive the future of a blocking call 
from the heap in Spark Connect Rust, so that a request does not overflow a 
small stack of the calling thread
fa564506 is described below

commit fa5645065ff834121f7c679e0bb0d72001174084
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 08:28:08 2026 +0900

    [SPARK-61469][CONNECT] Drive the future of a blocking call from the heap in 
Spark Connect Rust, so that a request does not overflow a small stack of the 
calling thread
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61469](https://issues.apache.org/jira/browse/SPARK-61469): 
`runtime::block_on` and `runtime::block_on_abortable` 
(`crates/spark-connect-core/src/runtime.rs`) pin the future they drive on the 
heap (`Box::pin(f)`) before handing it on. The frames that move it to the 
runtime (`drive`, the runtime's `block_on`, the closure of `block_in_place`) 
then hold only a pointer to it, whatever the compiler inlines.
    
    ### Why are the changes needed?
    
    The future of a request holds the state of its gRPC call and of its 
retries, tens of KiB: the `analyze_plan` future is about 45 to 75 KiB. Moved by 
value, each frame between the caller and the runtime keeps a copy of it on the 
calling thread, unless the compiler inlines that frame. Which frames are 
inlined depends on the code of the crate that calls them, so an unrelated 
change tips it.
    
    - On master, on macOS arm64 in release, `DataFrame::schema()` of a plan 
already used about 355 KiB of the stack before the request was cloned.
    - With other open changes on top (#495, #503, #515), `runtime::drive` 
stopped being inlined and became its own frame of 147 KiB. The use then went 
past the 512 KiB thread that SPARK-61400's `deep_request_stack_tests` run on, 
the smallest stack a Python thread may have. Those tests aborted with a stack 
overflow (SIGABRT or SIGBUS), even for `spark.range(1).schema()`. Three 
sessions hit this independently with three different changes.
    
    | Frame, release, macOS arm64 | Before | After |
    |---|---|---|
    | `runtime::block_on` | 147 KiB | 832 B |
    | `runtime::drive` (when not inlined) | 147 KiB | a pointer |
    | the runtime's `block_on` | 73 KiB | 80 B |
    | used up to the request clone in `schema()` | ~355-526 KiB | ~127 KiB |
    
    With the future boxed, `schema()` and `collect()` of shallow and 746-level 
plans pass on threads of 512, 384, 256 and 192 KiB, and fail only at 128 KiB. 
Thanks to spark-0b's measurements. The cost is one heap allocation per blocking 
call, next to a gRPC call.
    
    ### Does this PR introduce _any_ user-facing change?
    
    No behavior change. A Rust API or Python client call made on a thread with 
a small stack (for example, a Python thread created with 
`threading.stack_size(512 * 1024)`) no longer overflows it, whatever else is in 
the build.
    
    ### How was this patch tested?
    
    - New test `test_block_on_holds_no_copy_of_a_large_future_on_a_small_stack` 
in `crates/spark-connect-core/src/runtime.rs`, after 
`test_block_on_async_task`. It drives a future with a 192 KiB state through 
`block_on` on a 512 KiB thread in release, and on an 8 MiB thread in debug, 
where frames are larger, as in SPARK-61400's tests. Without the boxing, it 
overflows the thread.
    - `cargo test -p apache-spark-connect-core --release --lib -- runtime::`, 
`cargo test -p apache-spark-connect --release --lib` (including 
`deep_request_stack_tests`), the build of all tests without warnings, and 
`cargo fmt --all --check`.
    - With this change, the small-stack tests also pass on master with #495, 
#503 or #515 on top, each of which overflowed them before.
    
    ### 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 #522 from HyukjinKwon/SPARK-61469-block-on-heap-future.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/spark-connect-core/src/runtime.rs | 40 +++++++++++++++++++++++++++++++-
 1 file changed, 39 insertions(+), 1 deletion(-)

diff --git a/crates/spark-connect-core/src/runtime.rs 
b/crates/spark-connect-core/src/runtime.rs
index 2b6678fc..678bfd3d 100644
--- a/crates/spark-connect-core/src/runtime.rs
+++ b/crates/spark-connect-core/src/runtime.rs
@@ -41,11 +41,20 @@ pub fn get_runtime() -> &'static Runtime {
 /// session hook of the executions), which may run a query itself: as PySpark 
does, the
 /// nested query runs. The thread is then in the runtime's context, which 
`block_in_place`
 /// leaves for the nested `block_on`.
+///
+/// The future is driven from the heap, so that the stack of the calling 
thread holds no copy of
+/// it, however large it is.
 pub fn block_on<F>(f: F) -> F::Output
 where
     F: std::future::Future + Send,
     F::Output: Send,
 {
+    // The future of a request holds the state of its gRPC call and of its 
retries, tens of KiB,
+    // and each frame that moves it on to the runtime (`drive`, the runtime's 
`block_on`, the
+    // closure of `block_in_place`) keeps a copy of it on the calling thread, 
unless the compiler
+    // inlines that frame, which depends on the crate that calls this one. A 
Python thread may
+    // have a stack of 512 KiB. Moved from the heap, those frames hold only 
its pointer.
+    let f = Box::pin(f);
     let watch = WAIT_WATCH.with(|watch| watch.borrow().clone());
     match tokio::runtime::Handle::try_current() {
         Ok(handle) if handle.runtime_flavor() == 
tokio::runtime::RuntimeFlavor::MultiThread => {
@@ -160,8 +169,10 @@ where
     F: std::future::Future + Send,
     F::Output: Send,
 {
+    // Driven from the heap, as `block_on` drives its future.
+    let f = Box::pin(f);
     let watch = WAIT_WATCH.with(|watch| watch.borrow().clone());
-    let drive = |f: F| match watch {
+    let drive = |f: Pin<Box<F>>| match watch {
         Some(watch) => get_runtime().block_on(watched_abortable(f, watch)),
         None => Some(get_runtime().block_on(f)),
     };
@@ -417,6 +428,33 @@ mod tests {
         assert_eq!(result, 30);
     }
 
+    /// A future of a large state, as the future of a request is of the state 
of its gRPC call,
+    /// is driven from the heap: a thread of a small stack, which holds it 
once, holds no other
+    /// copy of it in the frames that drive it, whatever the compiler inlines. 
(The frames of a
+    /// debug build copy more, so its thread has the stack of a default thread 
of Linux.)
+    #[test]
+    fn test_block_on_holds_no_copy_of_a_large_future_on_a_small_stack() {
+        const STATE: usize = 192 << 10;
+        let stack = if cfg!(debug_assertions) {
+            8 << 20
+        } else {
+            512 << 10
+        };
+        let output = std::thread::Builder::new()
+            .stack_size(stack)
+            .spawn(|| {
+                block_on(async {
+                    let state = [7u8; STATE];
+                    tokio::task::yield_now().await;
+                    state[STATE - 1]
+                })
+            })
+            .unwrap()
+            .join()
+            .unwrap();
+        assert_eq!(output, 7);
+    }
+
     #[test]
     fn test_watch_is_called_while_the_future_waits() {
         use std::sync::atomic::{AtomicUsize, Ordering};


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

Reply via email to