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 5525cb27 [SPARK-61241][CONNECT] Keep a panicking Rust progress handler
or listener from aborting the process, wedging the listener bus, or cutting a
prefetched local iterator short
5525cb27 is described below
commit 5525cb2760be8a6205753f94130ed2b4d7149b72
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Mon Nov 9 20:43:22 2026 +0900
[SPARK-61241][CONNECT] Keep a panicking Rust progress handler or listener
from aborting the process, wedging the listener bus, or cutting a prefetched
local iterator short
### What changes were proposed in this pull request?
[SPARK-61241](https://issues.apache.org/jira/browse/SPARK-61241): keep a
panicking Rust progress handler or listener from aborting the process or
wedging the listener bus.
- Progress: `ProgressTracker`'s `Drop` no longer calls the progress
handlers while a panic unwinds. Before, a handler that panicked on an update
and again on the final done call aborted the process ("panic in a destructor
during cleanup"). Now the first panic propagates to the caller as an ordinary
panic, and the process survives. The handlers still get the done call on normal
ends.
- Prefetching local iterator: `to_local_iterator(true)` reads the stream on
a background task, where a panic of a progress handler ended the task and
closed its channel, so the iterator stopped early and returned `Ok` with the
rows so far (0 of 3 in a probe), a silent truncation. The iterator now joins
the task once the channel closes and raises its panic in the caller
(`resume_unwind`), as the iterator without prefetching does.
- Listeners: a panic in a native Rust listener's
`try_post_to_all`/`try_on_event` is a failure of the subscription, turned into
a `SparkError` ("a streaming query listener panicked: ...") and reported
through `on_stream_error` exactly like a returned error. A panic in
`on_stream_error` is contained, so the remaining listeners are still told. The
worker's registrations are cleared by a drop guard, so they are cleared also
when the loop unwinds.
- Re-subscription: after a callback or decoder failure the server still
holds the listener, and it refuses a new `ADD_LISTENER_BUS_LISTENER` until
`REMOVE_LISTENER_BUS_LISTENER` (the server acknowledges nothing and the add
waits). `add_listener` therefore sends a best-effort remove when the bus has no
live worker and the failed listener's server registration is still held, then
opens a new subscription. It no longer appends a listener to a bus whose worker
has ended.
Rust API: no signature change. `add_listener`'s documented contract (a
terminal failure clears all registrations, and a new add opens a new
subscription) now holds for panics as it did for returned errors.
### Why are the changes needed?
- A Rust progress handler that panics on an update and again when the
execution unwinds (its done call runs during the unwinding) makes Rust abort
the process with SIGABRT. Repro: a handler that panics on every call, running
`spark.sql("SELECT reflect('java.lang.Thread','sleep',4000L)").collect()`.
- With `to_local_iterator(true)`, the same panicking handler made the
iterator end early without an error: the rows were cut short silently.
- A native listener that panics in a callback unwinds its worker. The
registrations stay on the bus, no `on_stream_error` is reported, and a listener
added afterwards is appended to the dead bus and never gets an event.
Both are Rust-only: PySpark has no native callback path, and the Python
bridge already turns Python listener and progress exceptions into returned
errors, which is unchanged.
### Does this PR introduce _any_ user-facing change?
Yes, for Rust users of `apache-spark-connect`. A panicking progress handler
no longer aborts the process, and a panicking native listener now ends its
subscription with a reported error, so a later `add_listener` gets events. The
Python drop-in is unchanged.
### How was this patch tested?
-
`progress::tests::a_handler_that_panics_does_not_abort_when_the_tracker_unwinds`,
inserted before
`detached_progress_registry_preserves_the_execution_recursion_bound`: a handler
that panics on every call, with a tracker dropped while unwinding. The handler
is called once and the process does not abort. It aborts with SIGABRT without
the fix.
-
`streaming::tests::a_panicking_native_listener_fails_the_subscription_like_an_error`,
inserted before `a_stale_worker_does_not_report_errors_to_a_new_generation`: a
native listener panics on its first event. The subscription ends,
`on_stream_error` gets the panic message, the registrations are cleared, no
later event is read, and the server-held registration is marked for removal. It
fails without the fix (the panic escapes the worker loop).
-
`test_a_panicking_progress_handler_reaches_the_caller_of_a_local_iterator`
(new, `crates/spark-connect/tests/e2e_integration.rs`, before
`test_dropped_stream_releases_its_execution`): a progress handler that panics
on an update reaches the caller of `to_local_iterator`, with prefetching and
without; without the fix the prefetching iterator returns `Ok` with 0 rows.
- Live, against a Spark 4.3.0 Connect server (not a PR test): a native
listener that panics on its first asynchronous event, and one that returns an
error, each reported once; a listener added afterwards on the same session then
got events of a new subscription. Before this change, the panic case reported
nothing and the later listener never got events (from the code, not run live),
and a returned error made the later add wait forever for the server's
acknowledgement (seen live withou [...]
- Rust: `cargo test -p apache-spark-connect --lib` (release and debug),
`cargo test -p apache-spark-connect --release --no-run` and the wasm-udf
variant, `apache-spark-connect-core` tests, `e2e_streaming` against a live
server. `cargo fmt --all --check`, clippy: no new warnings.
- The live Rust tests `e2e_integration` (18 passed) and `e2e_streaming` (5
passed) against a local Spark 4.3.0 server.
- The lib tests of both crates (666 passed), the build of all tests, also
with `wasm-udf`, the offline Python suites (2819 passed, 8 skipped), and the
live drop-in and Arrow suites (233 passed) and live cases (13 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 #424 from HyukjinKwon/SPARK-61241-listener-panics.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/spark-connect/src/dataframe.rs | 37 +++++--
crates/spark-connect/src/progress.rs | 32 +++++-
crates/spark-connect/src/streaming.rs | 144 +++++++++++++++++++++++---
crates/spark-connect/tests/e2e_integration.rs | 39 +++++++
4 files changed, 231 insertions(+), 21 deletions(-)
diff --git a/crates/spark-connect/src/dataframe.rs
b/crates/spark-connect/src/dataframe.rs
index aac9ad53..346bb6dc 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -141,6 +141,9 @@ enum RowSource {
/// current batch's rows (`prefetchPartitions=True`).
Prefetch {
rx: tokio::sync::mpsc::Receiver<Result<Vec<Row>>>,
+ /// The task, to raise its panic (of a progress handler, say) in the
caller once its
+ /// channel closes, as the on-demand source raises it, instead of
ending early.
+ task: Option<tokio::task::JoinHandle<()>>,
},
}
@@ -153,8 +156,12 @@ impl LocalRowIterator {
) -> Self {
let schema = SchemaSlot::default();
let source = if prefetch_partitions {
- RowSource::Prefetch {
- rx: spawn_prefetch(session, stream, Arc::clone(&schema)),
+ {
+ let (rx, task) = spawn_prefetch(session, stream,
Arc::clone(&schema));
+ RowSource::Prefetch {
+ rx,
+ task: Some(task),
+ }
}
} else {
RowSource::OnDemand {
@@ -224,7 +231,22 @@ impl LocalRowIterator {
}
}
},
- RowSource::Prefetch { rx } => block_on(rx.recv()),
+ RowSource::Prefetch { rx, task } => {
+ let batch = block_on(rx.recv());
+ if batch.is_none() {
+ // The channel closed: the task ended, or it panicked,
which then drops its
+ // sender without an error. Raise the panic here, so the
rows are not cut
+ // short silently.
+ if let Some(task) = task.take() {
+ if let Err(error) = block_on(task) {
+ if error.is_panic() {
+ std::panic::resume_unwind(error.into_panic());
+ }
+ }
+ }
+ }
+ batch
+ }
}
}
}
@@ -264,9 +286,12 @@ fn spawn_prefetch(
session: SparkSession,
mut stream: ExecutionStream,
schema: SchemaSlot,
-) -> tokio::sync::mpsc::Receiver<Result<Vec<Row>>> {
+) -> (
+ tokio::sync::mpsc::Receiver<Result<Vec<Row>>>,
+ tokio::task::JoinHandle<()>,
+) {
let (tx, rx) = tokio::sync::mpsc::channel::<Result<Vec<Row>>>(1);
- get_runtime().spawn(async move {
+ let task = get_runtime().spawn(async move {
let mut execution_info = ExecutionInfo::default();
loop {
// Closing the consumer must release the execution even while the
server has
@@ -313,7 +338,7 @@ fn spawn_prefetch(
}
session.record_execution(execution_info);
});
- rx
+ (rx, task)
}
impl DataFrame {
diff --git a/crates/spark-connect/src/progress.rs
b/crates/spark-connect/src/progress.rs
index 5a3a1130..175cda61 100644
--- a/crates/spark-connect/src/progress.rs
+++ b/crates/spark-connect/src/progress.rs
@@ -110,9 +110,12 @@ impl ProgressTracker {
}
impl Drop for ProgressTracker {
- /// As PySpark's `Progress.finish` when its execution ends, also of an
error.
+ /// As PySpark's `Progress.finish` when its execution ends, also of an
error. While a panic
+ /// unwinds, a handler is not called: one that panics again would abort
the process.
fn drop(&mut self) {
- self.notify(true);
+ if !std::thread::panicking() {
+ self.notify(true);
+ }
}
}
@@ -208,6 +211,31 @@ mod tests {
session.remove_progress_handler(id);
}
+ /// A handler that panics on every call, as a user's `unwrap` may: the
panic of the update
+ /// unwinds out of the tracker, and its drop must not call the handler
again while
+ /// unwinding, which would abort the process.
+ #[test]
+ fn a_handler_that_panics_does_not_abort_when_the_tracker_unwinds() {
+ let session = SparkSession::builder()
+ .remote("sc://localhost:15002")
+ .get_or_create()
+ .expect("session");
+ let calls = Arc::new(AtomicUsize::new(0));
+ let seen = Arc::clone(&calls);
+ let id = session.register_progress_handler(move |_| {
+ seen.fetch_add(1, Ordering::SeqCst);
+ panic!("handler panic");
+ });
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ let mut tracker = ProgressTracker::new(&session, None);
+ tracker.update(&progress(&[(1, 1)], 0), "op");
+ }));
+ assert!(result.is_err());
+ // Only the update called the handler; the done call during unwinding
is skipped.
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+ session.remove_progress_handler(id);
+ }
+
#[test]
fn detached_progress_registry_preserves_the_execution_recursion_bound() {
use spark_connect_core::error::SparkErrorKind;
diff --git a/crates/spark-connect/src/streaming.rs
b/crates/spark-connect/src/streaming.rs
index 49fc586f..e72549a5 100644
--- a/crates/spark-connect/src/streaming.rs
+++ b/crates/spark-connect/src/streaming.rs
@@ -1009,6 +1009,10 @@ struct ListenerBusState {
/// The threads delivering a synchronous started event in
`start`/`toTable`, one entry
/// per delivery. As with `dispatching`, a removal from another thread
waits for them.
started_dispatches: Vec<std::thread::ThreadId>,
+ /// Set when the worker of the current generation failed in a callback, so
the server still
+ /// holds its listener: the server removes it only on
REMOVE_LISTENER_BUS_LISTENER, and
+ /// refuses a new ADD_LISTENER_BUS_LISTENER until then. A new subscription
removes it first.
+ server_registration_held: bool,
}
/// A synchronous started event in delivery by the calling thread of
`start`/`toTable`.
@@ -1067,6 +1071,15 @@ impl ListenerBus {
}
}
+ /// Record that the server still holds the listener of `generation`, whose
worker failed in
+ /// a callback or a decoder (not in the transport, which may have ended
the server's side).
+ fn mark_server_registration_held(&self, generation: u64) {
+ let mut state = self.state.lock().unwrap();
+ if state.generation == generation {
+ state.server_registration_held = true;
+ }
+ }
+
/// Post a synchronous start event without holding the state lock across
callbacks.
fn post_to_all(&self, event: &StreamingQueryListenerEvent) {
let listeners: Vec<Arc<dyn StreamingQueryListener>> = self
@@ -1083,6 +1096,32 @@ impl ListenerBus {
}
}
+/// 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 {
+ bus: Weak<ListenerBus>,
+ generation: u64,
+}
+
+impl Drop for FinishGeneration {
+ fn drop(&mut self) {
+ if let Some(bus) = self.bus.upgrade() {
+ bus.finish_generation(self.generation);
+ }
+ }
+}
+
+/// The error of a panic in a native listener's callback: a failure of that
callback, as a
+/// returned error from it.
+fn listener_panic_error(payload: &(dyn std::any::Any + Send)) -> SparkError {
+ let message = payload
+ .downcast_ref::<&str>()
+ .copied()
+ .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
+ .unwrap_or("a non-string payload");
+ SparkError::connect_msg(format!("a streaming query listener panicked:
{message}"))
+}
+
/// The worker retains neither the session nor its bus. The stream owns only
transport
/// and progress-handler state; dropping the last session/manager cancels the
reader.
fn run_listener_event_loop(
@@ -1090,6 +1129,11 @@ fn run_listener_event_loop(
bus: Weak<ListenerBus>,
generation: u64,
) {
+ // Declared first so it runs last, after the dispatch guard, also when a
callback unwinds.
+ let _finish = FinishGeneration {
+ bus: bus.clone(),
+ generation,
+ };
let mut stream = stream.into_iter();
let mut failure = None;
for item in &mut stream {
@@ -1124,15 +1168,22 @@ fn run_listener_event_loop(
event_type,
event_json,
};
- let dispatched = 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))
- });
+ // A panic of a callback is a failure of the subscription, as a
returned error is.
+ 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())));
if let Err(error) = dispatched {
+ if let Some(owner) = bus.upgrade() {
+ owner.mark_server_registration_held(generation);
+ }
failure = Some((listeners, error, dispatch));
break;
}
@@ -1143,15 +1194,15 @@ fn run_listener_event_loop(
// as it waits for an ordinary event. No state lock or strong bus
owner is
// held across either callback path; the worker can still remove
itself.
for listener in listeners {
- if listener.on_stream_error(&error) {
+ let reported =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ listener.on_stream_error(&error)
+ }));
+ if reported.unwrap_or(false) {
break;
}
}
drop(dispatch);
}
- if let Some(bus) = bus.upgrade() {
- bus.finish_generation(generation);
- }
}
/// Manager for active streaming queries.
@@ -1208,10 +1259,18 @@ impl StreamingQueryManager {
return Err(Self::no_active_session());
}
let id = uuid::Uuid::new_v4().to_string();
- if !state.listeners.is_empty() {
+ let worker_alive = state
+ .thread
+ .as_ref()
+ .is_some_and(|worker| !worker.is_finished());
+ if !state.listeners.is_empty() && worker_alive {
state.listeners.push((id.clone(), listener));
return Ok(id);
}
+ // The registrations of a worker that has ended get no more events:
they are
+ // cleared, and this listener opens a new subscription.
+ let stale = std::mem::take(&mut state.listeners);
+ let release_server = std::mem::take(&mut
state.server_registration_held);
state.phase = ListenerBusPhase::Starting;
// An earlier worker must not clear this registration's cancellation
sender.
state.generation = state.generation.wrapping_add(1);
@@ -1220,7 +1279,13 @@ impl StreamingQueryManager {
state.cancel = Some(cancel);
let previous = state.thread.take();
drop(state);
+ drop(stale);
Self::join_listener_thread(previous);
+ if release_server {
+ // Best effort: the server's listener is gone if the removal
fails, and then the
+ // add below reports it.
+ let _ = self.remove_server_listener();
+ }
let stream = self.listener_event_stream().and_then(|mut stream| {
// Cancel a pending acknowledgement once the RPC stream exists.
Establishing
// the stream above still follows the transport's deadline and
retry policy.
@@ -2085,6 +2150,59 @@ 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.
+ #[test]
+ fn a_panicking_native_listener_fails_the_subscription_like_an_error() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ struct Listener {
+ 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");
+ }
+
+ fn on_stream_error(&self, error: &SparkError) -> bool {
+ self.errors.lock().unwrap().push(error.message());
+ true
+ }
+ }
+ let bus = Arc::new(ListenerBus::default());
+ let listener = Arc::new(Listener {
+ events: AtomicUsize::new(0),
+ errors: Mutex::new(vec![]),
+ });
+ {
+ let mut state = bus.state.lock().unwrap();
+ state.generation = 3;
+ state
+ .listeners
+ .push(("first".to_string(), listener.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,
+ );
+ 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()],
+ );
+ 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);
+ }
+
#[test]
fn a_stale_worker_does_not_report_errors_to_a_new_generation() {
use std::sync::atomic::{AtomicUsize, Ordering};
diff --git a/crates/spark-connect/tests/e2e_integration.rs
b/crates/spark-connect/tests/e2e_integration.rs
index 0a81f1bb..cdb93841 100644
--- a/crates/spark-connect/tests/e2e_integration.rs
+++ b/crates/spark-connect/tests/e2e_integration.rs
@@ -599,6 +599,45 @@ fn test_completed_execution_is_released() {
});
}
+/// A progress handler that panics during an execution of a local iterator
panics in the caller,
+/// with prefetching as without, instead of ending the rows early without an
error.
+#[test]
+fn test_a_panicking_progress_handler_reaches_the_caller_of_a_local_iterator() {
+ if !should_run() {
+ return;
+ }
+ let spark = SparkSession::builder()
+ .remote(&remote_url())
+ .get_or_create()
+ .expect("session");
+ // Updates every 10 ms (2 s by default), so the tasks below report
progress.
+ spark
+ .conf()
+ .set("spark.connect.progress.reportInterval", "10ms")
+ .expect("conf");
+ spark.register_progress_handler(|update| {
+ if !update.done {
+ panic!("a progress handler panics");
+ }
+ });
+ for prefetch in [true, false] {
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ spark
+ .sql("SELECT id, reflect('java.lang.Thread', 'sleep', 500L) AS
s FROM range(0, 4, 1, 4)")
+ .expect("sql")
+ .to_local_iterator(prefetch)
+ .expect("iterator")
+ .collect::<Result<Vec<_>, _>>()
+ .map(|rows| rows.len())
+ }));
+ assert!(
+ result.is_err(),
+ "prefetch={prefetch}: the panic of the handler must reach the
caller, got {result:?}"
+ );
+ }
+ let _ = spark.stop();
+}
+
/// A stream dropped before its result is complete releases its execution as
well.
#[test]
fn test_dropped_stream_releases_its_execution() {
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]