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 6f06ccd0 [SPARK-61250][CONNECT] Run the synchronous API inside a
current-thread Tokio runtime on another thread
6f06ccd0 is described below
commit 6f06ccd05ea8fcf614f34867b4af7d0f85c029b4
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Mon Nov 9 21:06:55 2026 +0900
[SPARK-61250][CONNECT] Run the synchronous API inside a current-thread
Tokio runtime on another thread
### What changes were proposed in this pull request?
[SPARK-61250](https://issues.apache.org/jira/browse/SPARK-61250): Run the
synchronous API inside a current-thread Tokio runtime on another thread.
- `runtime::block_on` runs the future on a scoped thread, while the caller
waits, when the caller is in a `current_thread` runtime. Inside a multi-thread
runtime (block in place) and outside any runtime, the path is unchanged.
- The future is polled on that thread, so the caller's per-thread state is
carried over: `calling_thread_id()` gives the caller's thread ID there, which
keys the user context extensions read by each request; the callback depth and
the recursion failure of the caller are copied in and back out, so a call from
inside a callback bounds its recursion as on the caller's thread. Operation
tags are read when the request is built, on the caller's thread, so they are
unchanged.
- `block_on` now requires `F: Send` and `F::Output: Send`. Every caller in
the workspace satisfies them (`cargo check --workspace --all-targets` and
`--features wasm-udf` are clean).
- The crate docs and the quickstart say the API is synchronous and may be
called from any thread, including inside a Tokio runtime of either flavor, and
that the call blocks the calling thread.
- Official PySpark has no such limit: its client is a plain blocking client
that works from any thread.
### Why are the changes needed?
Inside a `current_thread` runtime, such as the one of `#[tokio::test]` or
of `#[tokio::main(flavor = "current_thread")]`, every synchronous call panicked
with "Cannot start a runtime from within a runtime": `collect`, `count`,
`schema`, `sql` and `stop`. `stop()` marks the session stopped before it
releases the session, so the panic left the session marked stopped and the
server session was never released; it lived until the server's idle timeout.
```rust
#[tokio::test]
async fn t() {
let spark =
SparkSession::builder().remote("sc://localhost:15002").get_or_create().unwrap();
spark.range(3).unwrap().count().unwrap(); // panicked before this change
}
```
### Does this PR introduce _any_ user-facing change?
Yes. The synchronous API works inside a `current_thread` runtime instead of
panicking. The call blocks the calling thread, as it does elsewhere, and the
work runs on a thread of its own.
### How was this patch tested?
- `runtime::tests` (new, in `crates/spark-connect-core/src/runtime.rs`):
`block_on` inside a `current_thread` runtime returns the value; a nested
`block_on` there works; the caller's thread ID is seen from the other thread; a
call from inside a callback at the recursion bound fails with `RecursionError`
there too; a panic propagates to the caller. The first two, and the
caller-thread and callback-depth checks, fail without the change.
- `test_sync_api_inside_a_current_thread_runtime` (new,
`crates/spark-connect/tests/e2e_integration.rs`, before `test_schema`, against
a live server): a `#[tokio::test]` runs `count`, `collect` and `sql`; the
requests seen by an execute-plan hook carry the tag and the user context
extension added on the test thread; a thread interrupts the operation by that
tag; `stop()` releases the session, the stopped session raises
`NO_ACTIVE_SESSION`, and a new session works. It fails without the [...]
- Two existing tests
(`session::tests::version_cache_recovers_after_lookup_panics`,
`dataframe::cache_tests::schema_cache_recovers_after_analysis_panics`) used the
removed panic to poison a cache lock. They now poison the lock directly with a
panic while the guard is held, and keep the same recovery assertions.
- The sync API is PySpark's behavior; the case has no official-PySpark
counterpart to compare against, since it is a Rust-only runtime constraint.
- The tests of the transport crate, and the live Rust tests
`e2e_integration` (18 passed) against a local Spark 4.3.0 server.
- The lib tests of both crates (669 passed), the build of all tests, also
with `wasm-udf`, the offline Python suites (2820 passed, 8 skipped), and the
live drop-in and Arrow suites (232 passed) and live cases (14 passed) against a
local Spark 4.3.0 server. Clippy reports no diagnostics in the changed lines.
### 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 #428 from HyukjinKwon/SPARK-61250-current-thread-runtime.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/spark-connect-core/src/client.rs | 3 +-
crates/spark-connect-core/src/runtime.rs | 124 +++++++++++++++++++++++++-
crates/spark-connect/src/dataframe.rs | 33 +++----
crates/spark-connect/src/lib.rs | 10 +++
crates/spark-connect/src/session.rs | 12 ++-
crates/spark-connect/tests/e2e_integration.rs | 111 +++++++++++++++++++++++
docs/quickstart.md | 8 ++
7 files changed, 269 insertions(+), 32 deletions(-)
diff --git a/crates/spark-connect-core/src/client.rs
b/crates/spark-connect-core/src/client.rs
index 233052e2..fca1639a 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -695,9 +695,10 @@ impl SparkConnectClient {
.user_context_extensions
.lock()
.unwrap_or_else(|e| e.into_inner());
+ // The thread that calls the API, also when this future is polled on
another thread.
let own = extensions
.by_thread
- .get(&std::thread::current().id())
+ .get(&crate::runtime::calling_thread_id())
.map(|own| own.0.lock().unwrap_or_else(|e| e.into_inner()));
if extensions.global.is_empty() && own.as_ref().is_none_or(|own|
own.is_empty()) {
return;
diff --git a/crates/spark-connect-core/src/runtime.rs
b/crates/spark-connect-core/src/runtime.rs
index 7d6b25ed..aa6632b6 100644
--- a/crates/spark-connect-core/src/runtime.rs
+++ b/crates/spark-connect-core/src/runtime.rs
@@ -28,20 +28,78 @@ pub fn get_runtime() -> &'static Runtime {
/// and wait for its result. This should be called with the GIL released
/// in a Python context.
///
+/// The synchronous API may be called from any thread, including inside a
Tokio runtime of
+/// either flavor: the call blocks the calling thread until the future
completes. Inside a
+/// multi-thread runtime the thread is blocked in place; inside a
`current_thread` runtime it
+/// cannot block in place, so the future runs on a thread of its own, which
the calling thread
+/// waits for (see [`block_on_other_thread`]).
+///
/// Also called from a callback that runs inside the runtime (a progress
handler, or a
/// 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`. A `current_thread` runtime cannot block
in place, so the
-/// call keeps failing there.
-pub fn block_on<F: std::future::Future>(f: F) -> F::Output {
+/// leaves for the nested `block_on`.
+pub fn block_on<F>(f: F) -> F::Output
+where
+ F: std::future::Future + Send,
+ F::Output: Send,
+{
match tokio::runtime::Handle::try_current() {
Ok(handle) if handle.runtime_flavor() ==
tokio::runtime::RuntimeFlavor::MultiThread => {
tokio::task::block_in_place(|| get_runtime().block_on(f))
}
+ Ok(_) => block_on_other_thread(f),
_ => get_runtime().block_on(f),
}
}
+/// Run a future to completion on the shared runtime, on a thread of its own,
while the calling
+/// thread waits for it: the calling thread is inside a `current_thread`
runtime, which cannot
+/// block in place and cannot start another runtime.
+///
+/// The future is polled on the other thread, so the state that the client
keeps per thread is
+/// that of the caller: [`calling_thread_id`] is the caller's ID there, and
the callback depth
+/// and the recursion failure of the caller carry over, then back, so a call
made from inside a
+/// callback bounds its recursion as on the caller's own thread.
+fn block_on_other_thread<F>(f: F) -> F::Output
+where
+ F: std::future::Future + Send,
+ F::Output: Send,
+{
+ let caller = std::thread::current().id();
+ let depth = CALLBACK_DEPTH.with(std::cell::Cell::get);
+ let recursion_failed =
CALLBACK_RECURSION_FAILED.with(std::cell::Cell::get);
+ let (output, recursion_failed) = std::thread::scope(|scope| {
+ let worker = scope.spawn(move || {
+ CALLER_THREAD.with(|caller_thread|
caller_thread.set(Some(caller)));
+ CALLBACK_DEPTH.with(|d| d.set(depth));
+ CALLBACK_RECURSION_FAILED.with(|failed|
failed.set(recursion_failed));
+ let output = get_runtime().block_on(f);
+ (output, CALLBACK_RECURSION_FAILED.with(std::cell::Cell::get))
+ });
+ match worker.join() {
+ Ok(result) => result,
+ Err(panic) => std::panic::resume_unwind(panic),
+ }
+ });
+ CALLBACK_RECURSION_FAILED.with(|failed| failed.set(recursion_failed));
+ output
+}
+
+thread_local! {
+ /// The thread that the calls of this thread act for, while
[`block_on_other_thread`] runs a
+ /// future on this thread for it.
+ static CALLER_THREAD: std::cell::Cell<Option<std::thread::ThreadId>> =
const { std::cell::Cell::new(None) };
+}
+
+/// The thread whose per-thread state the calls on this thread use: the thread
that calls the
+/// synchronous API, also while a future of such a call is polled on another
thread (see
+/// [`block_on`]). Its operation tags and user context extensions are keyed by
it.
+pub fn calling_thread_id() -> std::thread::ThreadId {
+ CALLER_THREAD
+ .with(std::cell::Cell::get)
+ .unwrap_or_else(|| std::thread::current().id())
+}
+
/// How many progress handlers and hooks may run nested on a thread, each one
running a query
/// that runs the next one. Past it, an execution fails with a
`RecursionError` (as PySpark's
/// recursion limit raises it) instead of recursing until the native stack of
the thread
@@ -148,4 +206,64 @@ mod tests {
});
assert_eq!(result, 30);
}
+
+ fn current_thread_runtime() -> tokio::runtime::Runtime {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ }
+
+ #[test]
+ fn test_block_on_inside_current_thread_runtime() {
+ // The default flavor of `#[tokio::test]`: the sync API blocks the
thread, which the
+ // runtime cannot block in place.
+ let result = current_thread_runtime().block_on(async { block_on(async
{ 42 }) });
+ assert_eq!(result, 42);
+ }
+
+ #[test]
+ fn test_block_on_nested_inside_current_thread_runtime() {
+ // A callback of the execution runs a query, which runs inside the
current_thread runtime.
+ let result = current_thread_runtime()
+ .block_on(async { block_on(async { block_on(async { 7 }) + 1 }) });
+ assert_eq!(result, 8);
+ }
+
+ #[test]
+ fn test_block_on_inside_current_thread_runtime_keeps_caller_thread() {
+ // The per-thread state (tags and extensions) of the caller is read as
on its own thread.
+ let caller = std::thread::current().id();
+ let seen =
+ current_thread_runtime().block_on(async { block_on(async {
calling_thread_id() }) });
+ assert_eq!(seen, caller);
+ assert_eq!(calling_thread_id(), caller);
+ }
+
+ #[test]
+ fn test_block_on_inside_current_thread_runtime_keeps_callback_depth() {
+ // A call from a callback at the bound fails with a RecursionError on
the other thread too.
+ let guards: Vec<CallbackGuard> = (0..MAX_CALLBACK_DEPTH)
+ .map(|_| CallbackGuard::enter())
+ .collect();
+ let err = current_thread_runtime()
+ .block_on(async { block_on(async { check_callback_depth() }) })
+ .unwrap_err();
+ assert_eq!(err.kind, crate::error::SparkErrorKind::RecursionError);
+ drop(guards);
+ // The failure is released with the outermost callback, as on this
thread.
+ assert!(current_thread_runtime()
+ .block_on(async { block_on(async { check_callback_depth() }) })
+ .is_ok());
+ }
+
+ #[test]
+ fn test_block_on_inside_current_thread_runtime_propagates_panic() {
+ let result = std::panic::catch_unwind(|| {
+ current_thread_runtime().block_on(async {
+ block_on(async { panic!("from the future") });
+ })
+ });
+ assert!(result.is_err());
+ }
}
diff --git a/crates/spark-connect/src/dataframe.rs
b/crates/spark-connect/src/dataframe.rs
index 0d496cdd..6e5fd538 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -4036,27 +4036,18 @@ mod cache_tests {
.unwrap();
let df = spark.range(3).unwrap();
let cloned = df.clone();
- // A current-thread runtime: the synchronous API cannot block in place
in it.
- let runtime = tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap();
-
- // Calling the synchronous API inside a runtime panics during analysis.
- // A clone must still attempt analysis afterward, rather than returning
- // a permanent cache-poisoning error.
- for frame in [&df, &cloned] {
- let result = runtime.block_on(async {
- std::panic::catch_unwind(std::panic::AssertUnwindSafe(||
frame.schema()))
- });
- assert!(result.is_err());
- // Poisoning proves the lock spans the analysis boundary without
- // relying on thread scheduling to produce contended cache misses.
- assert!(
- frame.schema_cache.is_poisoned(),
- "schema analysis must hold the shared cache lock"
- );
- }
+ // A panic under the cache lock, as a panicking analysis leaves it:
the clones must still
+ // analyze afterward, rather than returning a permanent
cache-poisoning error.
+ let cache = Arc::clone(&df.schema_cache);
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ let _held = cache.lock().unwrap();
+ panic!("an analysis panics while the cache lock is held");
+ }));
+ assert!(result.is_err());
+ assert!(
+ df.schema_cache.is_poisoned(),
+ "the cache lock must be poisoned for this test"
+ );
let mut cached = df.schema_cache.lock().unwrap_err().into_inner();
assert!(cached.is_none());
let schema = DataType::Struct { fields: vec![] };
diff --git a/crates/spark-connect/src/lib.rs b/crates/spark-connect/src/lib.rs
index 98663dc0..91b1a9e8 100644
--- a/crates/spark-connect/src/lib.rs
+++ b/crates/spark-connect/src/lib.rs
@@ -2,6 +2,16 @@
//!
//! This crate provides the core data types and operations for interacting with
//! Apache Spark via the Spark Connect protocol.
+//!
+//! # Synchronous API
+//!
+//! Every method is synchronous: it returns once the server has answered. The
API may be called
+//! from any thread, including inside a Tokio runtime of either flavor. The
call blocks the
+//! calling thread until it completes, as any blocking call does, so avoid it
in a task that
+//! must keep other tasks of the same runtime running. In a multi-thread
runtime the thread is
+//! blocked in place. In a `current_thread` runtime (the default of
`#[tokio::test]` and of
+//! `#[tokio::main(flavor = "current_thread")]`) the work runs on a thread of
its own while the
+//! calling thread waits, and it uses the tags and user context extensions of
the calling thread.
#![allow(clippy::result_large_err)] // SparkError is large; changing the type
would break the API
diff --git a/crates/spark-connect/src/session.rs
b/crates/spark-connect/src/session.rs
index 30006804..f8fc76de 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -2978,14 +2978,12 @@ mod tests {
fn version_cache_recovers_after_lookup_panics() {
let spark = session();
let handle = spark.clone();
- // Like other synchronous RPC helpers, version() cannot run inside a
current-thread
- // Tokio runtime, which cannot block in place. That caller's panic
must not
- // permanently break this session's cache.
- let runtime = tokio::runtime::Builder::new_current_thread()
- .build()
- .unwrap();
+ // A panic under the cache lock, as a panicking lookup leaves it, must
not permanently
+ // break this session's cache.
+ let cache = std::sync::Arc::clone(&spark.server_version);
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
- runtime.block_on(async { spark.version() })
+ let _held = cache.lock().unwrap();
+ panic!("a lookup panics while the cache lock is held");
}));
assert!(result.is_err());
assert!(spark.server_version.is_poisoned());
diff --git a/crates/spark-connect/tests/e2e_integration.rs
b/crates/spark-connect/tests/e2e_integration.rs
index cdb93841..11937a8e 100644
--- a/crates/spark-connect/tests/e2e_integration.rs
+++ b/crates/spark-connect/tests/e2e_integration.rs
@@ -265,6 +265,117 @@ fn test_count() {
assert_eq!(count, 100, "Expected count of 100");
}
+/// The sync API inside a `current_thread` runtime, as the default
`#[tokio::test]` is: it blocks
+/// the test thread, and the requests carry the tags and the user context
extensions of that
+/// thread, as they do on a plain thread.
+#[tokio::test]
+async fn test_sync_api_inside_a_current_thread_runtime() {
+ if !should_run() {
+ println!(
+ "Skipping test_sync_api_inside_a_current_thread_runtime - set
SPARK_REMOTE to run"
+ );
+ return;
+ }
+
+ let session = SparkSession::builder()
+ .remote(&remote_url())
+ .get_or_create()
+ .expect("Failed to create session");
+
+ // The requests as the client sends them: their tags and the types of
their extensions.
+ type SentRequests = Vec<(Vec<String>, Vec<String>)>;
+ let sent: std::sync::Arc<std::sync::Mutex<SentRequests>> =
Default::default();
+ let recorded = std::sync::Arc::clone(&sent);
+ session.set_execute_plan_hook(Some(std::sync::Arc::new(move |request| {
+ let extensions = request
+ .user_context
+ .iter()
+ .flat_map(|context| context.extensions.iter().map(|e|
e.type_url.clone()))
+ .collect();
+ recorded
+ .lock()
+ .unwrap()
+ .push((request.tags.clone(), extensions));
+ Ok(request)
+ })));
+
+ let df = session.range(3).expect("Failed to create range DataFrame");
+ assert_eq!(df.count().expect("count"), 3);
+ assert_eq!(df.collect().expect("collect").len(), 3);
+ let rows = session
+ .sql("SELECT 1 AS x")
+ .and_then(|df| df.collect())
+ .expect("sql");
+ assert_eq!(rows.len(), 1);
+
+ // A tag and an extension of the test thread are on the operation that the
test thread runs,
+ // which a thread that waits for the server to show it interrupts by the
tag.
+ let tag = "s13-current-thread-tag";
+ let extension_type = "type.googleapis.com/s13.current_thread";
+ session.add_tag(tag).expect("add_tag");
+ assert_eq!(session.get_tags(), vec![tag.to_string()]);
+ session.add_threadlocal_user_context_extension(prost_types::Any {
+ type_url: extension_type.to_string(),
+ value: Vec::new(),
+ });
+ let running = std::sync::atomic::AtomicBool::new(true);
+ let interrupted = std::thread::scope(|scope| {
+ let interrupter = scope.spawn(|| {
+ let deadline = std::time::Instant::now() + Duration::from_secs(60);
+ while running.load(std::sync::atomic::Ordering::SeqCst) {
+ let ids = session.interrupt_tag(tag).expect("interrupt_tag");
+ if !ids.is_empty() {
+ return ids;
+ }
+ assert!(
+ std::time::Instant::now() < deadline,
+ "the operation never started"
+ );
+ std::thread::sleep(Duration::from_millis(200));
+ }
+ Vec::new()
+ });
+ let outcome = session
+ .sql("SELECT reflect('java.lang.Thread', 'sleep', 60000L)")
+ .and_then(|df| df.collect());
+ running.store(false, std::sync::atomic::Ordering::SeqCst);
+ assert!(outcome.is_err(), "the interrupted operation must fail");
+ interrupter.join().expect("interrupter")
+ });
+ assert_eq!(
+ interrupted.len(),
+ 1,
+ "the tag of the test thread is on its operation"
+ );
+ {
+ let sent = sent.lock().unwrap();
+ assert!(
+ sent.iter().any(|(tags, exts)| tags == &[tag.to_string()]
+ && exts.iter().any(|e| e == extension_type)),
+ "the operation carries the tag and the extension of the test
thread: {sent:?}"
+ );
+ }
+ session.set_execute_plan_hook(None);
+ session.remove_tag(tag);
+ assert!(session.get_tags().is_empty());
+
+ // stop() releases the session from this thread too; the stopped session
then raises
+ // NO_ACTIVE_SESSION, and a new session works.
+ session.stop().expect("stop");
+ assert!(session.is_stopped());
+ let err = session
+ .range(1)
+ .and_then(|df| df.count())
+ .expect_err("a stopped session must not run");
+ assert_eq!(err.get_condition().as_deref(), Some("NO_ACTIVE_SESSION"));
+ let fresh = SparkSession::builder()
+ .remote(&remote_url())
+ .get_or_create()
+ .expect("Failed to create a new session");
+ assert_eq!(fresh.range(2).and_then(|df| df.count()).expect("count"), 2);
+ fresh.stop().expect("stop");
+}
+
#[test]
fn test_schema() {
if !should_run() {
diff --git a/docs/quickstart.md b/docs/quickstart.md
index 31060b3f..3055e59c 100644
--- a/docs/quickstart.md
+++ b/docs/quickstart.md
@@ -64,6 +64,14 @@ df
.show(20)?;
```
+## Using it from an async runtime
+
+The API is synchronous and can be called from any thread, including inside a
Tokio runtime of
+either flavor. The call blocks the thread it runs on until the server answers,
so keep it out of
+tasks that must keep the rest of their runtime running. A `current_thread`
runtime, such as the
+one of `#[tokio::test]`, works too: the query runs on a thread of its own
while the calling
+thread waits, and it keeps the tags and user context extensions of the calling
thread.
+
## Next Steps
- [DataFrames](dataframes.md) - column operations, joins, window functions
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]