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 49c97690 [SPARK-61315][CONNECT][PYTHON] Keep the listener bus 
consistent when a listener fails, is removed or is re-added, as PySpark does
49c97690 is described below

commit 49c9769053525f106af9900dfca30d6fd291e3b6
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 10:22:23 2026 +0900

    [SPARK-61315][CONNECT][PYTHON] Keep the listener bus consistent when a 
listener fails, is removed or is re-added, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61315](https://issues.apache.org/jira/browse/SPARK-61315): Keep the 
Spark Connect listener bus consistent when a listener fails, is removed or is 
re-added, as PySpark does.
    
    The native listener bus of the Rust client 
(`crates/spark-connect/src/streaming.rs`) gets five fixes:
    
    - A native listener that panics on the started event no longer unwinds 
`start()` or `toTable()`. Each listener is isolated: the panic is reported on 
stderr, and the other listeners still get the event. The query is returned, as 
PySpark's `post_to_all` does (it warns and goes on). The asynchronous path is 
unchanged.
    - Removing the last listener (and `close()`) waits for a started event that 
another thread is delivering, before the server's listener is removed. A 
removal of a non-last listener already waited for it. PySpark's bus holds its 
lock for that delivery, so its removal waits too. A worker's own event is not 
awaited, as before.
    - A failed server REMOVE before a new subscription is no longer ignored. 
`add_listener` returns the error without sending the ADD, and the registration 
stays marked as held, so that a retry removes it first. Previously the ADD was 
sent, and the server answers an ADD for a listener it still holds with no 
response (`SparkConnectStreamingQueryListenerHandler`, v4.3.0), so the add 
waited forever.
    - Any failure of the listener stream marks the server registration as held, 
transport failures included. The server drops a registration only on a later 
failed event send or on REMOVE, so after a transport failure on an idle session 
the next subscription now sends REMOVE first. Previously only callback and 
decoding failures marked it, and such a re-add could hang.
    - The listener stream no longer calls the session's progress handlers. 
PySpark's listener bus has no `Progress`, so each listener-bus stream that 
ended gave the handlers an extra `done` call. `execute_plan_unreported` 
(`session.rs`) carries the stream without handlers.
    
    The Python mock tests in `python/tests/streaming_listener_cases.py` now 
expect the REMOVE sent before the re-add after a failed stream.
    
    ### Why are the changes needed?
    
    - A native listener that panics on the started event made `start()` or 
`toTable()` raise while the query was already running on the server, so the 
caller got neither a handle nor a way to stop it.
    - `removeListener` of the last listener returned while the started callback 
of another thread was still running.
    - After a failed removal or a transport failure of the listener stream, 
`addListener` waited for ever for a response that the server never sends, and 
the later adds hung too.
    - After `close()` or `removeListener` of the last listener, the progress 
handlers saw one more `done` than PySpark's listener bus gives.
    
    The PySpark behaviour is taken from the official 4.3.0 source: 
`post_to_all` in `pyspark/sql/connect/streaming/query.py` (isolates each 
listener), the bus lock in `removeListener` in the same file, and 
`execute_command_as_iterator` in `pyspark/sql/connect/client/core.py` (no 
`Progress`). The server behaviour is taken from the `v4.3.0` tag of 
`SparkConnectStreamingQueryListenerHandler.scala`, 
`SparkConnectListenerBusListener`, and 
`ExecuteThreadRunner.shouldDelegateCompleteResponse`. T [...]
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. A native listener that panics on the started event no longer makes 
`start()` or `toTable()` raise: the query is returned and the panic is reported 
on stderr. A failed server removal before a new subscription makes 
`addListener` raise, where it previously made the add hang. A re-add after a 
failed listener stream sends one extra REMOVE. The progress handlers are no 
longer called with an extra `done` for listener-bus streams.
    
    ### How was this patch tested?
    
    - Five new unit tests in `mod tests` of `streaming.rs`, before 
`stream_writer_partition_by`: 
`a_panicking_listener_on_the_started_event_does_not_unwind_the_start`, 
`last_removal_waits_for_a_started_event_in_delivery_from_another_thread`, 
`a_failed_removal_before_a_new_subscription_keeps_the_registration_held`, 
`a_transport_failure_marks_the_server_registration_held`, and 
`the_listener_event_stream_reports_no_progress_to_the_handlers`. Each of them 
fails when its fix is reverted (relea [...]
    - `test_streaming_bus_errors_warn_once_clear_all_and_allow_reregistration` 
(`[transport]` case) and 
`test_streaming_listener_ended_stream_clears_registry_and_reopens[error]` now 
expect one REMOVE on the re-add. Both fail with the transport-failure fix 
reverted.
    - The offline Python suites (`test_dropin_offline.py`, 
`test_arrow_handoff.py`, `test_ml_offline.py`): 2927 passed, 8 skipped; the 
listener subset passes under pytest 9.2 too (57 passed).
    - Live: `e2e_streaming` (5 passed) and `test_dropin_e2e.py -k listener` (2 
passed) against a Spark Connect 4.3.0 server.
    - The live Rust tests `e2e_streaming` (5 passed) and `e2e_integration` (19 
passed) against a local Spark 4.3.0 server.
    - The lib tests of both crates (684 passed), the build of all tests, also 
with `wasm-udf`, the offline Python suites (2937 passed, 8 skipped), and the 
live drop-in and Arrow suites (241 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 #440 from HyukjinKwon/SPARK-61315-listener-bus.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/spark-connect/src/progress.rs     |  16 +-
 crates/spark-connect/src/session.rs      |  22 ++-
 crates/spark-connect/src/streaming.rs    | 302 ++++++++++++++++++++++++++-----
 python/tests/streaming_listener_cases.py |  12 +-
 4 files changed, 299 insertions(+), 53 deletions(-)

diff --git a/crates/spark-connect/src/progress.rs 
b/crates/spark-connect/src/progress.rs
index 03b954ef..c1a20eae 100644
--- a/crates/spark-connect/src/progress.rs
+++ b/crates/spark-connect/src/progress.rs
@@ -9,7 +9,7 @@ use spark_connect_core::error::Result;
 use spark_connect_core::runtime::CallbackGuard;
 use spark_connect_proto as proto;
 
-use crate::session::{FallibleProgressHandler, ProgressHandlers, SparkSession};
+use crate::session::{FallibleProgressHandler, ProgressHandlers};
 
 /// The progress of a stage of an execution, as PySpark's `StageInfo`.
 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -54,9 +54,18 @@ pub(crate) struct ProgressTracker {
 }
 
 impl ProgressTracker {
-    pub(crate) fn new(session: &SparkSession, operation_id: Option<String>) -> 
Self {
+    #[cfg(test)]
+    pub(crate) fn new(
+        session: &crate::session::SparkSession,
+        operation_id: Option<String>,
+    ) -> Self {
+        Self::with_handlers(session.progress_handlers(), operation_id)
+    }
+
+    /// A tracker that calls `handlers`, which is empty for an execution that 
reports no progress.
+    pub(crate) fn with_handlers(handlers: ProgressHandlers, operation_id: 
Option<String>) -> Self {
         ProgressTracker {
-            handlers: session.progress_handlers(),
+            handlers,
             operation_id,
             stages: Vec::new(),
             inflight_tasks: 0,
@@ -156,6 +165,7 @@ mod tests {
     use std::sync::{Arc, Mutex};
 
     use super::*;
+    use crate::session::SparkSession;
 
     fn progress(
         stages: &[(i64, i64)],
diff --git a/crates/spark-connect/src/session.rs 
b/crates/spark-connect/src/session.rs
index 63cd1f96..b450b133 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -165,7 +165,7 @@ pub struct SparkSession {
 
 impl SparkSession {
     /// Create a new SparkSession with a client.
-    fn new(client: SparkConnectClient) -> Self {
+    pub(crate) fn new(client: SparkConnectClient) -> Self {
         SparkSession {
             client: Arc::new(client),
             plan_ids: Arc::new(PlanIds::new()),
@@ -300,8 +300,26 @@ impl SparkSession {
     /// handlers. Its operation ID is that of the request, or a new one, which 
the client
     /// assigns before it sends the request, as PySpark's `Progress` of the 
request has it.
     pub(crate) fn execute_plan(
+        &self,
+        request: proto::ExecutePlanRequest,
+    ) -> Result<ExecutionStream> {
+        self.execute_plan_with_handlers(request, self.progress_handlers())
+    }
+
+    /// As [`execute_plan`](Self::execute_plan), but the progress of the 
execution, and its done
+    /// notification, does not reach the progress handlers: PySpark's listener 
bus has no
+    /// `Progress`, so its long-running stream reports none.
+    pub(crate) fn execute_plan_unreported(
+        &self,
+        request: proto::ExecutePlanRequest,
+    ) -> Result<ExecutionStream> {
+        self.execute_plan_with_handlers(request, ProgressHandlers::default())
+    }
+
+    fn execute_plan_with_handlers(
         &self,
         mut request: proto::ExecutePlanRequest,
+        handlers: ProgressHandlers,
     ) -> Result<ExecutionStream> {
         let operation_id = request
             .operation_id
@@ -309,7 +327,7 @@ impl SparkSession {
             .clone();
         // Before the request: an execution that fails to start ends, as done, 
too.
         check_callback_depth()?;
-        let progress = ProgressTracker::new(self, Some(operation_id));
+        let progress = ProgressTracker::with_handlers(handlers, 
Some(operation_id));
         let stream = 
block_on(self.client().execute_plan_reattachable(request))?;
         Ok(ExecutionStream::new(stream, progress))
     }
diff --git a/crates/spark-connect/src/streaming.rs 
b/crates/spark-connect/src/streaming.rs
index e72549a5..2128a315 100644
--- a/crates/spark-connect/src/streaming.rs
+++ b/crates/spark-connect/src/streaming.rs
@@ -1009,9 +1009,9 @@ 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.
+    /// Set when the worker of the current generation failed, so the server 
may still hold its
+    /// 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,
 }
 
@@ -1071,8 +1071,7 @@ 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).
+    /// Record that the server may still hold the listener of `generation`, 
whose worker failed.
     fn mark_server_registration_held(&self, generation: u64) {
         let mut state = self.state.lock().unwrap();
         if state.generation == generation {
@@ -1080,7 +1079,9 @@ impl ListenerBus {
         }
     }
 
-    /// Post a synchronous start event without holding the state lock across 
callbacks.
+    /// Post a synchronous start event without holding the state lock across 
callbacks. A panic
+    /// of one listener is reported and isolated, as PySpark's `post_to_all` 
isolates an exception
+    /// of one listener: the query is still returned, and the other listeners 
still get the event.
     fn post_to_all(&self, event: &StreamingQueryListenerEvent) {
         let listeners: Vec<Arc<dyn StreamingQueryListener>> = self
             .state
@@ -1091,7 +1092,14 @@ impl ListenerBus {
             .map(|(_, listener)| Arc::clone(listener))
             .collect();
         for listener in listeners {
-            listener.on_event(event);
+            let posted =
+                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| 
listener.on_event(event)));
+            if let Err(payload) = posted {
+                eprintln!(
+                    "WARNING: a streaming query listener threw an 
exception\n{}",
+                    panic_message(payload.as_ref())
+                );
+            }
         }
     }
 }
@@ -1114,12 +1122,19 @@ impl Drop for FinishGeneration {
 /// 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
+    SparkError::connect_msg(format!(
+        "a streaming query listener panicked: {}",
+        panic_message(payload)
+    ))
+}
+
+/// The message of a panic payload, or a placeholder for a payload that is not 
a string.
+fn panic_message(payload: &(dyn std::any::Any + Send)) -> &str {
+    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}"))
+        .unwrap_or("a non-string payload")
 }
 
 /// The worker retains neither the session nor its bus. The stream owns only 
transport
@@ -1181,15 +1196,18 @@ fn run_listener_event_loop(
         }))
         .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;
         }
         drop(dispatch);
     }
     if let Some((listeners, error, dispatch)) = failure {
+        // Any failure of the subscription, transport included, may leave the 
server's
+        // 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);
+        }
         // 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
         // held across either callback path; the worker can still remove 
itself.
@@ -1282,9 +1300,16 @@ impl StreamingQueryManager {
         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();
+            if let Err(error) = self.remove_server_listener() {
+                // Without the removal, the server would answer the add below 
with no response,
+                // and the add would wait for ever. Keep the flag, so that a 
retry removes first.
+                let mut state = self.bus.state.lock().unwrap();
+                state.server_registration_held = true;
+                state.cancel.take();
+                state.phase = ListenerBusPhase::Idle;
+                self.bus.changed.notify_all();
+                return Err(error);
+            }
         }
         let stream = self.listener_event_stream().and_then(|mut stream| {
             // Cancel a pending acknowledgement once the RPC stream exists. 
Establishing
@@ -1343,40 +1368,62 @@ impl StreamingQueryManager {
     }
 
     fn remove_listeners(&self, id: Option<&str>) -> Result<bool> {
-        let Some(mut state) = self.idle_state(true)? else {
-            // Another caller waits for this callback. It owns the shutdown 
result; keep
-            // the registration token until that caller has actually removed 
the listener.
-            return Ok(false);
-        };
-        if let Some(id) = id {
-            let Some(index) = state
-                .listeners
-                .iter()
-                .position(|(listener_id, _)| listener_id == id)
-            else {
+        loop {
+            let Some(mut state) = self.idle_state(true)? else {
+                // Another caller waits for this callback. It owns the 
shutdown result; keep
+                // the registration token until that caller has actually 
removed the listener.
                 return Ok(false);
             };
-            if state.listeners.len() > 1 {
-                state.listeners.remove(index);
-                // As in PySpark's bus, a removal waits for delivery to the 
snapshot,
-                // including the removed listener, to finish. This also covers 
a
-                // terminal error notification. A callback of the bus does not 
wait,
-                // as it would wait for its own delivery.
-                let current = std::thread::current().id();
-                if state.worker_id != Some(current) {
-                    let generation = state.generation;
-                    while state.dispatching == Some(generation)
-                        || state
-                            .started_dispatches
-                            .iter()
-                            .any(|thread| *thread != current)
-                    {
-                        state = self.bus.changed.wait(state).unwrap();
+            if let Some(id) = id {
+                let Some(index) = state
+                    .listeners
+                    .iter()
+                    .position(|(listener_id, _)| listener_id == id)
+                else {
+                    return Ok(false);
+                };
+                if state.listeners.len() > 1 {
+                    state.listeners.remove(index);
+                    // As in PySpark's bus, a removal waits for delivery to 
the snapshot,
+                    // including the removed listener, to finish. This also 
covers a
+                    // terminal error notification. A callback of the bus does 
not wait,
+                    // as it would wait for its own delivery.
+                    let current = std::thread::current().id();
+                    if state.worker_id != Some(current) {
+                        let generation = state.generation;
+                        while state.dispatching == Some(generation)
+                            || state
+                                .started_dispatches
+                                .iter()
+                                .any(|thread| *thread != current)
+                        {
+                            state = self.bus.changed.wait(state).unwrap();
+                        }
                     }
+                    return Ok(true);
                 }
-                return Ok(true);
             }
+            // The removal of the last listener waits for a started event that 
another thread
+            // delivers, before it removes the server's listener, as PySpark's 
bus holds its lock
+            // for that delivery. A worker's own event is not awaited: its 
callbacks may remove
+            // or stop the bus while the removal is in flight. The lock is 
released while
+            // waiting, so the bus is checked again after it.
+            let current = std::thread::current().id();
+            if state.worker_id != Some(current)
+                && state
+                    .started_dispatches
+                    .iter()
+                    .any(|thread| *thread != current)
+            {
+                drop(self.bus.changed.wait(state).unwrap());
+                continue;
+            }
+            return self.stop_listener_bus(state);
         }
+    }
+
+    /// Remove the last listener of the bus: the server's listener, then the 
worker.
+    fn stop_listener_bus(&self, mut state: MutexGuard<'_, ListenerBusState>) 
-> Result<bool> {
         let had_listeners = !state.listeners.is_empty();
         let generation = state.generation;
         state.phase = ListenerBusPhase::Stopping;
@@ -1672,7 +1719,7 @@ impl StreamingQueryManager {
             ..Default::default()
         };
 
-        let response_stream = self.session.execute_plan(request)?;
+        let response_stream = self.session.execute_plan_unreported(request)?;
 
         Ok(ListenerEventStream {
             stream: response_stream,
@@ -1724,6 +1771,19 @@ mod tests {
             .expect("failed to build session")
     }
 
+    /// A session with no server behind it whose requests fail at once: the 
default retry policy
+    /// would retry them for a minute, so a test that needs a failing request 
uses this one.
+    fn unreachable_session_without_retries() -> SparkSession {
+        let builder = 
spark_connect_core::channel::ChannelBuilder::parse("sc://127.0.0.1:1")
+            .expect("valid URL");
+        let mut client = 
block_on(spark_connect_core::client::SparkConnectClient::connect(
+            &builder,
+        ))
+        .expect("failed to build client");
+        
client.set_retry_policy(spark_connect_core::retries::RetryPolicy::no_retries());
+        SparkSession::new(client)
+    }
+
     #[test]
     fn progress_tracker_does_not_keep_listener_bus_alive() {
         let session = session();
@@ -2383,6 +2443,158 @@ mod tests {
         assert_eq!(writer.output_mode, Some("append".to_string()));
     }
 
+    /// A panic of a native listener on the started event is reported and 
isolated, as PySpark's
+    /// `post_to_all` isolates an exception of one listener: the other 
listeners still get the
+    /// event, and `start` (which posts it) does not unwind, so it still 
returns the query.
+    #[test]
+    fn a_panicking_listener_on_the_started_event_does_not_unwind_the_start() {
+        use std::sync::atomic::{AtomicUsize, Ordering};
+
+        struct Panicking;
+        impl StreamingQueryListener for Panicking {
+            fn on_event(&self, _: &StreamingQueryListenerEvent) {
+                panic!("started listener panic");
+            }
+        }
+        struct Counting(AtomicUsize);
+        impl StreamingQueryListener for Counting {
+            fn on_event(&self, _: &StreamingQueryListenerEvent) {
+                self.0.fetch_add(1, Ordering::SeqCst);
+            }
+        }
+
+        let spark = session();
+        let manager = spark.streams();
+        let counting = Arc::new(Counting(AtomicUsize::new(0)));
+        {
+            let mut state = manager.bus.state.lock().unwrap();
+            state
+                .listeners
+                .push(("panicking".to_string(), Arc::new(Panicking)));
+            state
+                .listeners
+                .push(("counting".to_string(), counting.clone()));
+        }
+        manager.post_to_all(&StreamingQueryListenerEvent {
+            event_type: QUERY_STARTED_EVENT,
+            event_json: "{}".to_string(),
+        });
+        assert_eq!(counting.0.load(Ordering::SeqCst), 1);
+        assert_eq!(manager.listeners().len(), 2);
+    }
+
+    /// The removal of the last listener waits for a started event in delivery 
on another thread,
+    /// as the removal of a non-last listener does. It is checked with `close` 
on an empty bus,
+    /// which takes the same branch but sends no server request, so it returns 
at once.
+    #[test]
+    fn 
last_removal_waits_for_a_started_event_in_delivery_from_another_thread() {
+        use std::sync::mpsc;
+        use std::time::Duration;
+
+        let spark = session();
+        let manager = spark.streams();
+        let dispatch = manager.started_dispatch();
+        let (closed, close) = mpsc::channel();
+        std::thread::scope(|scope| {
+            // Drop the delivery guard even if an assertion fails, so the 
scoped remover
+            // is released before the scope joins it.
+            let dispatch = dispatch;
+            let manager = &manager;
+            scope.spawn(move || {
+                closed.send(manager.close()).unwrap();
+            });
+            assert!(
+                matches!(
+                    close.recv_timeout(Duration::from_millis(300)),
+                    Err(mpsc::RecvTimeoutError::Timeout)
+                ),
+                "the removal of the last listener returned while a started 
event was in delivery"
+            );
+            drop(dispatch);
+            close
+                .recv_timeout(Duration::from_secs(5))
+                .expect("removal finishes once the started event is delivered")
+                .unwrap();
+        });
+        assert!(manager
+            .bus
+            .state
+            .lock()
+            .unwrap()
+            .started_dispatches
+            .is_empty());
+    }
+
+    /// A failed server removal before a new subscription keeps the 
registration marked as held,
+    /// and the add fails without sending its own request: the server would 
answer that request
+    /// with no response, so the add would wait for ever.
+    #[test]
+    fn 
a_failed_removal_before_a_new_subscription_keeps_the_registration_held() {
+        struct Listener;
+        impl StreamingQueryListener for Listener {
+            fn on_event(&self, _: &StreamingQueryListenerEvent) {}
+        }
+
+        let spark = unreachable_session_without_retries();
+        let manager = spark.streams();
+        manager.bus.state.lock().unwrap().server_registration_held = true;
+        // No server is reachable here, so the removal fails and the add 
reports it.
+        manager
+            .add_listener(Arc::new(Listener))
+            .expect_err("a failed removal fails the add");
+        assert!(manager.listeners().is_empty());
+        let state = manager.bus.state.lock().unwrap();
+        assert!(state.server_registration_held);
+        assert_eq!(state.phase, ListenerBusPhase::Idle);
+        assert!(state.cancel.is_none());
+    }
+
+    /// A transport failure of the listener stream marks the server 
registration as held, since
+    /// the server may still hold its listener until a REMOVE or a failed 
event send drops it.
+    #[test]
+    fn a_transport_failure_marks_the_server_registration_held() {
+        struct Listener;
+        impl StreamingQueryListener for Listener {
+            fn on_event(&self, _: &StreamingQueryListenerEvent) {}
+        }
+
+        let bus = Arc::new(ListenerBus::default());
+        {
+            let mut state = bus.state.lock().unwrap();
+            state.generation = 4;
+            state
+                .listeners
+                .push(("only".to_string(), Arc::new(Listener)));
+        }
+        run_listener_event_loop(
+            vec![Err(SparkError::connect_msg("transport failed"))],
+            Arc::downgrade(&bus),
+            4,
+        );
+        let state = bus.state.lock().unwrap();
+        assert!(state.listeners.is_empty());
+        assert!(state.server_registration_held);
+    }
+
+    /// The listener bus has no `Progress` in PySpark, so its stream never 
calls the progress
+    /// handlers of the session, not even with the done notification when the 
stream ends.
+    #[test]
+    fn the_listener_event_stream_reports_no_progress_to_the_handlers() {
+        use std::sync::atomic::{AtomicUsize, Ordering};
+
+        let spark = unreachable_session_without_retries();
+        let calls = Arc::new(AtomicUsize::new(0));
+        let counter = Arc::clone(&calls);
+        spark.register_progress_handler(move |_| {
+            counter.fetch_add(1, Ordering::SeqCst);
+        });
+        // No server is reachable here, so the stream does not start: an 
execution that fails
+        // to start used to end as done. A stream that starts ends with its 
drop, which is
+        // the same notification.
+        drop(spark.streams().listener_event_stream());
+        assert_eq!(calls.load(Ordering::SeqCst), 0);
+    }
+
     #[test]
     fn stream_writer_partition_by() {
         let spark = session();
diff --git a/python/tests/streaming_listener_cases.py 
b/python/tests/streaming_listener_cases.py
index f7ed976f..ec223adc 100644
--- a/python/tests/streaming_listener_cases.py
+++ b/python/tests/streaming_listener_cases.py
@@ -255,7 +255,9 @@ class TestStreamingListenerLifecycle:
             assert service.wait_listener_streams_finished(1)
             assert service.listener_removals == 0
 
+            # The failed stream leaves the server's registration held, so the 
add removes it first.
             manager.addListener(second)
+            assert service.listener_removals == 1
             assert service.listener_subscriptions == 2
             emit_idle(service, spark, "after-error")
             second.wait_for("after-error")
@@ -1139,8 +1141,12 @@ def ended_stream_case(termination):
             assert service.listener_removals == 0
 
             # Reuse the same manager and object: stale tokens must not match 
the new
-            # generation or prevent removal of its one active registration.
+            # generation or prevent removal of its one active registration. A 
failed stream
+            # leaves the server's registration held, so the add removes it 
first; a normal
+            # end leaves none.
+            removals = 1 if termination == "error" else 0
             manager.addListener(listener)
+            assert service.listener_removals == removals
             assert listener._rust_listener_ids[:-1] == stale_ids
             assert listener._rust_listener_ids[-1] not in stale_ids
             assert service.listener_subscriptions == 2
@@ -1151,11 +1157,11 @@ def ended_stream_case(termination):
             manager.removeListener(listener)
             assert manager._sqlb._listener_bus == []
             assert listener._rust_listener_ids == stale_ids
-            assert service.listener_removals == 1
+            assert service.listener_removals == removals + 1
             assert service.wait_listener_streams_finished(2)
             manager.removeListener(listener)
             assert listener._rust_listener_ids == stale_ids
-            assert service.listener_removals == 1
+            assert service.listener_removals == removals + 1
         finally:
             manager.close()
 


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

Reply via email to