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 d3a35ce6 [SPARK-61441][CONNECT][FOLLOWUP] Keep a listener re-added 
from a stream error subscribed, and free the listener bus after a panicking 
progress handler
d3a35ce6 is described below

commit d3a35ce6e10f4c0805a95ba6227b82b339987915
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 09:48:45 2026 +0900

    [SPARK-61441][CONNECT][FOLLOWUP] Keep a listener re-added from a stream 
error subscribed, and free the listener bus after a panicking progress handler
    
    ### What changes were proposed in this pull request?
    
    A follow-up of #509 (SPARK-61441), from a review of the listener bus that 
it restructured (`crates/spark-connect/src/streaming.rs`):
    
    - **A listener added from the terminal error of its subscription stays 
subscribed.** When a worker begins its terminal failure, the bus marks its 
generation as terminating, together with the record that the server may still 
hold its listener. `add_listener` then opens a new subscription instead of 
joining the generation that is ending. Before, a listener re-added from 
`on_stream_error` joined the ending generation, which then cleared it, while 
`add_listener` had returned `Ok`.
    - **A panic of a session progress handler during the removal of the last 
listener no longer leaves the bus stopping.** `stop_listener_bus` catches the 
unwind of the reported removal, finishes the removal as a failed one (the phase 
goes back to idle and the registrations and the worker are kept for a retry, as 
for a removal that fails), and resumes the panic. Before, the phase stayed 
`Stopping` and the next `close()` waited forever.
    - **The drop of the bus isolates the drops of the listeners it still 
holds**, as #509 isolates them on the four paths that remove listeners: a panic 
of a listener's `Drop` when a session is dropped without `close()` is reported, 
not propagated.
    - The locking notes said that dropping the event stream of a subscription 
runs the progress handlers of the user. Its execution is unreported, so no user 
code runs there; the notes say so now.
    
    ### Why are the changes needed?
    
    #509 documents adding listeners again as the way to subscribe again after a 
terminal error, and says that a bus whose listeners or handlers panicked keeps 
working. Both failed: the re-added listener was dropped silently, and a 
panicking progress handler made the next `close()` hang.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, in the Rust API, on unreleased behavior: a listener re-added from 
`on_stream_error` receives the events of the new subscription; `close()` 
returns after a progress handler panicked during a listener removal; dropping a 
session no longer propagates the panic of a listener's `Drop`.
    
    ### How was this patch tested?
    
    - `a_listener_added_from_the_stream_error_of_its_generation_is_subscribed` 
and `dropping_the_bus_isolates_the_panic_of_a_listener_it_still_holds` (unit 
tests in `streaming.rs`): the first fails without the change, and the test 
binary aborts on the second ("panic in a destructor during cleanup").
    - `streaming_listener_readded_from_a_stream_error_receives_events` and 
`streaming_listener_close_returns_after_a_panicking_progress_handler` in 
`crates/spark-connect/tests/e2e_streaming.rs`, against a Spark 4.3.0 server: 
the first fails and the second times out after 60 s without the change.
    - `cargo test -p apache-spark-connect --release --lib` (610 passed), 
`e2e_streaming` (7 passed, also with a 1 MiB `senderMaxStreamSize`), the 
`--no-run` builds, the offline drop-in suites (1945 passed), `cargo fmt --all 
-- --check` and `scripts/audit_no_stubs.sh`.
    
    ### 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 #523 from HyukjinKwon/SPARK-61441-followup-listener-bus.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/spark-connect/src/streaming.rs       | 164 ++++++++++++++++++++++++++--
 crates/spark-connect/tests/e2e_streaming.rs | 141 ++++++++++++++++++++++++
 2 files changed, 293 insertions(+), 12 deletions(-)

diff --git a/crates/spark-connect/src/streaming.rs 
b/crates/spark-connect/src/streaming.rs
index 2c48c97c..aa7a6d1a 100644
--- a/crates/spark-connect/src/streaming.rs
+++ b/crates/spark-connect/src/streaming.rs
@@ -1003,10 +1003,11 @@ pub trait StreamingQueryListener: Send + Sync {
 ///
 /// `state` is the only lock of the bus, and it is taken only through 
[`ListenerBus::lock`] and
 /// [`ListenerBus::wait`]. Nothing that can block or run the code of a user 
happens while it is
-/// held: no listener callback, no drop of a listener (see [`drop_isolated`]), 
no RPC, no join of
-/// the worker and no drop of an event stream, whose progress handlers are of 
the user. A critical
-/// section only reads and assigns the fields and takes no other lock, so the 
bus has no lock
-/// order to break. The waits for another thread are on `changed`, which 
releases the lock.
+/// held: no listener callback, no drop of a listener (see [`drop_isolated`]), 
no RPC and no join of
+/// the worker. An event stream is dropped without the lock too, though its 
drop runs no code of
+/// a user: its execution is unreported, so the progress handlers are none. A 
critical section only
+/// reads and assigns the fields and takes no other lock, so the bus has no 
lock order to break.
+/// The waits for another thread are on `changed`, which releases the lock.
 #[derive(Default)]
 pub(crate) struct ListenerBus {
     state: Mutex<ListenerBusState>,
@@ -1038,6 +1039,9 @@ struct ListenerBusState {
     /// listener: the server removes it only on REMOVE_LISTENER_BUS_LISTENER, 
and answers a new
     /// ADD_LISTENER_BUS_LISTENER for it with no response. A new subscription 
removes it first.
     server_registration_held: bool,
+    /// The generation whose worker has begun its terminal failure. Its 
callbacks run before its
+    /// registrations are cleared, so a listener added from them opens a new 
subscription.
+    terminating: Option<u64>,
 }
 
 /// A synchronous started event in delivery by the calling thread of 
`start`/`toTable`.
@@ -1086,6 +1090,22 @@ enum ListenerBusPhase {
     Stopping,
 }
 
+impl Drop for ListenerBus {
+    /// The last owner of the bus drops the listeners that it still holds, as 
the removals do: a
+    /// listener's `Drop` is code of the user, so its panic is isolated and 
does not reach the
+    /// dropper of the session.
+    fn drop(&mut self) {
+        let listeners = std::mem::take(
+            &mut self
+                .state
+                .get_mut()
+                .unwrap_or_else(PoisonError::into_inner)
+                .listeners,
+        );
+        drop_isolated(listeners);
+    }
+}
+
 impl ListenerBus {
     /// Lock the state of the bus. A poisoned lock is recovered rather than 
propagated: no
     /// critical section runs the code of a user or leaves the fields 
half-updated where it can
@@ -1120,11 +1140,13 @@ impl ListenerBus {
         drop_isolated(stale);
     }
 
-    /// Record that the server may still hold the listener of `generation`, 
whose worker failed.
-    fn mark_server_registration_held(&self, generation: u64) {
+    /// Record that the worker of `generation` has failed: the server may 
still hold its listener,
+    /// and its registrations are cleared once the terminal notification has 
been made.
+    fn begin_terminal_failure(&self, generation: u64) {
         let mut state = self.lock();
         if state.generation == generation {
             state.server_registration_held = true;
+            state.terminating = Some(generation);
         }
     }
 
@@ -1283,7 +1305,7 @@ fn run_listener_event_loop(
         // listener registered: the server drops it only on a later failed 
event send or on
         // REMOVE, so the next subscription removes it first.
         if let Some(owner) = bus.upgrade() {
-            owner.mark_server_registration_held(generation);
+            owner.begin_terminal_failure(generation);
         }
         // A removal from another thread waits for this terminal notification, 
just
         // as it waits for an ordinary event. No state lock or strong bus 
owner is
@@ -1363,11 +1385,12 @@ impl StreamingQueryManager {
             .thread
             .as_ref()
             .is_some_and(|worker| !worker.is_finished());
-        if !state.listeners.is_empty() && worker_alive {
+        let terminating = state.terminating == Some(state.generation);
+        if !state.listeners.is_empty() && worker_alive && !terminating {
             state.listeners.push((id.clone(), listener));
             return Ok(id);
         }
-        // The registrations of a worker that has ended get no more events: 
they are
+        // The registrations of a worker that has ended or is failing 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);
@@ -1412,8 +1435,8 @@ impl StreamingQueryManager {
         match stream {
             Ok(stream) => {
                 // The worker is given the stream only once it exists: a 
thread that cannot be
-                // spawned is an error rather than a panic under the lock, and 
the stream, whose
-                // drop runs the progress handlers of the user, is then 
dropped without the lock.
+                // spawned is an error rather than a panic under the lock, and 
the stream is then
+                // dropped without the lock.
                 let bus = Arc::downgrade(&self.bus);
                 let (handover, handed_over) = 
std::sync::mpsc::channel::<ListenerEventStream>();
                 let spawned = std::thread::Builder::new().spawn(move || {
@@ -1536,7 +1559,24 @@ impl StreamingQueryManager {
         let worker = state.thread.take();
         drop(state);
         let removal = if had_listeners {
-            self.remove_server_listener(true)
+            // The reported removal runs the progress handlers of the session, 
and a panic of one
+            // must not leave the phase of the bus set: the removal fails as 
an error does, which
+            // keeps its registrations and worker for a retry, and the panic 
then goes on.
+            match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+                self.remove_server_listener(true)
+            })) {
+                Ok(removal) => removal,
+                Err(payload) => {
+                    let _ = self.finish_listener_removal(
+                        generation,
+                        worker,
+                        Err(SparkError::connect_msg(
+                            "removing the streaming query listener panicked",
+                        )),
+                    );
+                    std::panic::resume_unwind(payload);
+                }
+            }
         } else {
             Ok(())
         };
@@ -2126,6 +2166,106 @@ mod tests {
         }
     }
 
+    /// A listener that the terminal error of its subscription re-adds from 
`on_stream_error`, as a
+    /// client resubscribes, is not left on the ending generation: the 
generation clears its
+    /// registrations after the callbacks. The add opens a new subscription, 
so the listener is
+    /// listed afterwards when the add succeeds, and the add reports an error 
otherwise.
+    #[test]
+    fn 
a_listener_added_from_the_stream_error_of_its_generation_is_subscribed() {
+        struct Listener;
+        impl StreamingQueryListener for Listener {
+            fn on_event(&self, _: &StreamingQueryListenerEvent) {}
+        }
+        struct Resubscribing {
+            manager: StreamingQueryManager,
+            listener: Arc<dyn StreamingQueryListener>,
+            result: Mutex<Option<Result<String>>>,
+        }
+        impl StreamingQueryListener for Resubscribing {
+            fn on_event(&self, _: &StreamingQueryListenerEvent) {}
+
+            fn on_stream_error(&self, _: &SparkError) -> bool {
+                let added = 
self.manager.add_listener(Arc::clone(&self.listener));
+                *self.result.lock().unwrap() = Some(added);
+                true
+            }
+        }
+
+        let session = unreachable_session_without_retries();
+        let bus = session.listener_bus();
+        // A live worker, so that the bus holds a generation whose worker is 
still running.
+        let _quiet = waiting_listener_worker(&session);
+        let generation = {
+            let mut state = bus.lock();
+            state.listeners.clear();
+            state.generation
+        };
+        let resubscribing = Arc::new(Resubscribing {
+            manager: session.streams(),
+            listener: Arc::new(Listener),
+            result: Mutex::new(None),
+        });
+        bus.lock()
+            .listeners
+            .push(("resubscribing".to_string(), resubscribing.clone()));
+
+        run_listener_event_loop(
+            vec![Err(SparkError::connect_msg("transport failed"))],
+            Arc::downgrade(&bus),
+            generation,
+        );
+
+        let result = resubscribing
+            .result
+            .lock()
+            .unwrap()
+            .take()
+            .expect("the terminal error reached the listener");
+        let state = bus.lock();
+        assert_ne!(
+            state.generation, generation,
+            "the add opens a new subscription rather than joining the ending 
generation"
+        );
+        match result {
+            Ok(id) => assert!(
+                state
+                    .listeners
+                    .iter()
+                    .any(|(listener_id, _)| *listener_id == id),
+                "a listener whose add succeeded is subscribed"
+            ),
+            Err(_) => assert!(state.listeners.is_empty()),
+        }
+    }
+
+    /// The bus drops the listeners that it still holds when its last owner 
goes, as it drops the
+    /// removed ones: a panic of their `Drop` is isolated, and it does not 
reach the dropper.
+    #[test]
+    fn dropping_the_bus_isolates_the_panic_of_a_listener_it_still_holds() {
+        struct PanicsOnDrop;
+        impl StreamingQueryListener for PanicsOnDrop {
+            fn on_event(&self, _: &StreamingQueryListenerEvent) {}
+        }
+        impl Drop for PanicsOnDrop {
+            fn drop(&mut self) {
+                panic!("the drop of the listener panics");
+            }
+        }
+
+        let bus = Arc::new(ListenerBus::default());
+        {
+            let mut state = bus.lock();
+            state
+                .listeners
+                .push(("first".to_string(), Arc::new(PanicsOnDrop)));
+            state
+                .listeners
+                .push(("second".to_string(), Arc::new(PanicsOnDrop)));
+        }
+        std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || 
drop(bus)))
+            .expect("the drop of the bus does not propagate the panic of a 
listener");
+    }
+
     #[test]
     fn 
nonlast_removal_waits_for_transport_decode_and_batch_error_notifications() {
         use std::sync::atomic::{AtomicUsize, Ordering};
diff --git a/crates/spark-connect/tests/e2e_streaming.rs 
b/crates/spark-connect/tests/e2e_streaming.rs
index 564f7600..cdd906d6 100644
--- a/crates/spark-connect/tests/e2e_streaming.rs
+++ b/crates/spark-connect/tests/e2e_streaming.rs
@@ -300,3 +300,144 @@ fn 
streaming_last_native_owner_drop_cancels_a_quiet_listener_worker() {
         .recv_timeout(Duration::from_secs(5))
         .expect("dropping every native owner releases the listener of the 
quiet real worker");
 }
+
+/// A listener whose subscription fails on its first event re-adds another 
listener from its
+/// `on_stream_error`, as a client resubscribes. The re-added listener must be 
subscribed on the
+/// server: it receives the events of a query that runs afterwards.
+#[test]
+fn streaming_listener_readded_from_a_stream_error_receives_events() {
+    if !should_run() {
+        return;
+    }
+    use spark_connect::streaming::{StreamingQueryListener, 
StreamingQueryListenerEvent};
+    use spark_connect::streaming::{StreamingQueryManager, 
QUERY_PROGRESS_EVENT};
+    use spark_connect::{Result, SparkError};
+    use std::sync::atomic::{AtomicUsize, Ordering};
+    use std::sync::{Arc, Mutex};
+    use std::time::Duration;
+
+    struct Counting(AtomicUsize);
+    impl StreamingQueryListener for Counting {
+        fn on_event(&self, event: &StreamingQueryListenerEvent) {
+            if event.event_type == QUERY_PROGRESS_EVENT {
+                self.0.fetch_add(1, Ordering::SeqCst);
+            }
+        }
+    }
+
+    struct FailsThenReadds {
+        manager: StreamingQueryManager,
+        next: Arc<dyn StreamingQueryListener>,
+        result: Mutex<Option<Result<String>>>,
+    }
+    impl StreamingQueryListener for FailsThenReadds {
+        fn on_event(&self, _: &StreamingQueryListenerEvent) {}
+
+        fn try_on_event(&self, _: &StreamingQueryListenerEvent) -> Result<()> {
+            Err(SparkError::connect_msg("the event cannot be read"))
+        }
+
+        fn on_stream_error(&self, _: &SparkError) -> bool {
+            let added = self.manager.add_listener(Arc::clone(&self.next));
+            *self.result.lock().unwrap() = Some(added);
+            true
+        }
+    }
+
+    let spark = session();
+    let manager = spark.streams();
+    let counting = Arc::new(Counting(AtomicUsize::new(0)));
+    let failing = Arc::new(FailsThenReadds {
+        manager: spark.streams(),
+        next: counting.clone(),
+        result: Mutex::new(None),
+    });
+    manager
+        .add_listener(failing.clone())
+        .expect("add the listener that fails");
+    let query = spark
+        .read_stream()
+        .format("rate")
+        .option("rowsPerSecond", "1")
+        .load(None)
+        .write_stream()
+        .format("noop")
+        .query_name("e2e_listener_readded_after_stream_error")
+        .start("")
+        .expect("start the query");
+    for _ in 0..60 {
+        if counting.0.load(Ordering::SeqCst) > 0 {
+            break;
+        }
+        std::thread::sleep(Duration::from_millis(500));
+    }
+    query.stop().expect("stop the query");
+    let added = failing
+        .result
+        .lock()
+        .unwrap()
+        .take()
+        .expect("the failing listener reported its stream error");
+    assert!(added.is_ok(), "the re-add succeeds: {added:?}");
+    assert_eq!(
+        manager.listeners().len(),
+        1,
+        "only the re-added listener remains"
+    );
+    assert!(
+        counting.0.load(Ordering::SeqCst) > 0,
+        "the re-added listener receives the events of the query"
+    );
+    manager.close().expect("close the listener bus");
+}
+
+/// A session progress handler that panics on the reported removal of the 
listener bus does not
+/// leave the bus in its lifecycle phase: the first close reports the panic, 
and the next close
+/// returns rather than waiting for the phase.
+#[test]
+fn streaming_listener_close_returns_after_a_panicking_progress_handler() {
+    if !should_run() {
+        return;
+    }
+    use spark_connect::streaming::{StreamingQueryListener, 
StreamingQueryListenerEvent};
+    use std::panic::{catch_unwind, AssertUnwindSafe};
+    use std::sync::atomic::{AtomicBool, Ordering};
+    use std::sync::{mpsc, Arc};
+    use std::time::Duration;
+
+    struct Quiet;
+    impl StreamingQueryListener for Quiet {
+        fn on_event(&self, _: &StreamingQueryListenerEvent) {}
+    }
+
+    let spark = session();
+    let manager = spark.streams();
+    manager
+        .add_listener(Arc::new(Quiet))
+        .expect("add the listener");
+    let panicked = Arc::new(AtomicBool::new(false));
+    let fired = Arc::clone(&panicked);
+    let handler = spark.register_progress_handler(move |_| {
+        if !fired.swap(true, Ordering::SeqCst) {
+            panic!("the progress handler panics");
+        }
+    });
+
+    let first = catch_unwind(AssertUnwindSafe(|| manager.close()));
+    spark.remove_progress_handler(handler);
+    assert!(
+        first.is_err(),
+        "the first close reports the panic of the handler"
+    );
+    assert!(panicked.load(Ordering::SeqCst));
+
+    let (returned, done) = mpsc::channel();
+    let retry = spark.clone();
+    std::thread::spawn(move || {
+        let _ = returned.send(retry.streams().close());
+    });
+    done.recv_timeout(Duration::from_secs(60))
+        .expect("the next close returns")
+        .expect("the next close removes the listener");
+    assert!(manager.listeners().is_empty());
+}


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

Reply via email to