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 80293ad6 [SPARK-61443][CONNECT][PYTHON][FOLLOWUP] Keep a listener that 
a signal interrupts removable, and stop removeListener at the first match, as 
PySpark does
80293ad6 is described below

commit 80293ad60c3e491e0ba13b163a2484185fc2aa99
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 09:49:17 2026 +0900

    [SPARK-61443][CONNECT][PYTHON][FOLLOWUP] Keep a listener that a signal 
interrupts removable, and stop removeListener at the first match, as PySpark 
does
    
    ### What changes were proposed in this pull request?
    
    A follow-up of #511 (SPARK-61443), from a review of it 
(`crates/pyspark-rs/src/streaming.rs`):
    
    - **`addListener` keeps the id of its registration as soon as the bus has 
it**, inside the call that adds it, so a `KeyboardInterrupt` raised while the 
server acknowledges the listener leaves a registration that `removeListener` 
can remove. Before, the signal's error returned before the id was set, so the 
listener stayed in the bus and `removeListener` skipped it forever.
    - **`removeListener` stops at the first registration that is the listener 
or equal to it**, in the order of the bus, as PySpark's `listener in 
self._listener_bus` and `list.remove` do. Before, it compared every 
registration, so a listener whose `__eq__` raises broke the removal of an 
earlier one.
    - The test of a `toLocalIterator` that another thread is running waits 
until that thread is inside `next()`, instead of a fixed 0.5 s, after which the 
main thread's `next()` could become the fetch and wait for the mock server.
    
    ### Why are the changes needed?
    
    In PySpark 4.3.0 the listener is appended to the bus before it is 
registered with the server, and `KeyboardInterrupt` is not an `Exception`, so a 
Ctrl-C during `addListener` leaves a listener that a later `removeListener` 
removes. Here it could never be removed. And `removeListener(a)` with a bus 
`[a, b]` where `b.__eq__` raises removes `a` in PySpark, while it raised `b`'s 
error here and removed nothing.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, in the Python client, on unreleased behavior: a listener whose 
`addListener` a Ctrl-C interrupted can be removed, and `removeListener` 
compares the listeners as `list.remove` does.
    
    ### How was this patch tested?
    
    - `test_sigint_during_add_listener_keeps_the_registration_removable` in 
`python/tests/test_dropin_offline.py` (SIGINT while the mock server holds the 
registration): it fails without the change.
    - `test_streaming_listener_removal_stops_at_the_first_match_as_pyspark` in 
`python/tests/streaming_listener_cases.py`: it fails without the change with 
the error of the second listener's `__eq__`.
    - The local iterator test, run with a 1 s delay before the thread's 
`next()`: the old form fails after 30 s, the new one passes.
    - The offline drop-in suites (1947 passed), the listener and local iterator 
tests of `test_dropin_e2e.py` against a Spark 4.3.0 server, `cargo test 
--no-run` of the Rust crates, `cargo fmt --all -- --check`, `ruff check 
python/tests` 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 #524 from HyukjinKwon/SPARK-61443-followup-listeners.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/streaming.rs       | 64 ++++++++++++++++--------------
 python/tests/streaming_listener_cases.py | 23 +++++++++++
 python/tests/test_dropin_offline.py      | 68 +++++++++++++++++++++++++++++---
 3 files changed, 120 insertions(+), 35 deletions(-)

diff --git a/crates/pyspark-rs/src/streaming.rs 
b/crates/pyspark-rs/src/streaming.rs
index 3f5c470f..f52bc57d 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -1399,13 +1399,17 @@ impl PyStreamingQueryManager {
         });
         let registration = Arc::clone(&adapter);
         match interruptible_outcome(py, &self.inner.spark_session(), || {
-            self.inner.add_listener(registration).map_err(Box::new)
+            self.inner
+                .add_listener(registration)
+                .map(|id| {
+                    // Set once, by the only call that adds this adapter, as 
soon as the bus has
+                    // the registration: a signal that ends the wait below 
then leaves it
+                    // removable, as PySpark's append leaves the listener in 
its bus.
+                    let _ = adapter.id.set(id);
+                })
+                .map_err(Box::new)
         })? {
-            Ok(id) => {
-                // Set once, by the only call that adds this adapter.
-                let _ = adapter.id.set(id);
-                Ok(())
-            }
+            Ok(()) => Ok(()),
             Err(error) => warn(
                 py,
                 format!(
@@ -1433,7 +1437,10 @@ impl PyStreamingQueryManager {
         // or their removal is left to the caller that is closing the bus.
         let mut tried: Vec<String> = Vec::new();
         loop {
-            let mut registered = Vec::new();
+            // The first registration in the order of the bus that is the 
listener or equal to
+            // it. The entries after it are not compared, as PySpark's `in` 
and `list.remove`
+            // stop at the first match.
+            let mut first = None;
             for candidate in self.inner.listeners() {
                 let Some(adapter) = candidate
                     .as_any()
@@ -1451,31 +1458,30 @@ impl PyStreamingQueryManager {
                 }
                 let found = adapter.listener.bind(py);
                 if found.is(listener) || found.eq(listener)? {
-                    registered.push(id.clone());
+                    first = Some(id.clone());
+                    break;
                 }
             }
-            if registered.is_empty() {
+            let Some(id) = first else {
                 return Ok(());
-            }
-            for id in registered {
-                match interruptible_outcome(py, &self.inner.spark_session(), 
|| {
-                    self.inner.remove_listener_found(&id).map_err(Box::new)
-                })? {
-                    // The bus is read again once these are tried: a call that 
removed this
-                    // registration first leaves its own to this one, which 
may have been
-                    // added since the bus was read.
-                    Ok(false) => tried.push(id),
-                    Ok(true) => return Ok(()),
-                    Err(error) => {
-                        return warn(
-                            py,
-                            format!(
-                                "Failed to remove the listener because of 
exception: {}\n\
-                                 The listener is not removed, please remove it 
again.",
-                                spark_error_to_py_exception(*error).value(py)
-                            ),
-                        );
-                    }
+            };
+            match interruptible_outcome(py, &self.inner.spark_session(), || {
+                self.inner.remove_listener_found(&id).map_err(Box::new)
+            })? {
+                // The bus is read again once this is tried: a call that 
removed this
+                // registration first leaves the next match to this one, which 
may have been
+                // added since the bus was read.
+                Ok(false) => tried.push(id),
+                Ok(true) => return Ok(()),
+                Err(error) => {
+                    return warn(
+                        py,
+                        format!(
+                            "Failed to remove the listener because of 
exception: {}\n\
+                             The listener is not removed, please remove it 
again.",
+                            spark_error_to_py_exception(*error).value(py)
+                        ),
+                    );
                 }
             }
         }
diff --git a/python/tests/streaming_listener_cases.py 
b/python/tests/streaming_listener_cases.py
index 7da24931..1b0c084c 100644
--- a/python/tests/streaming_listener_cases.py
+++ b/python/tests/streaming_listener_cases.py
@@ -570,6 +570,29 @@ class TestStreamingListenerLifecycle:
         finally:
             spark.streams.close()
 
+    def 
test_streaming_listener_removal_stops_at_the_first_match_as_pyspark(self, 
mock_connect):
+        # As the `in` and list.remove of PySpark's bus: the entries are 
compared in order, and
+        # the first one that is the listener, or equal to it, is removed, so 
the entries after
+        # it are not compared with it.
+        spark, service = mock_connect
+        service.listener_bus_enabled = True
+
+        class Angry(IdleListener):
+            def __eq__(self, other):
+                raise RuntimeError("Angry.__eq__ called")
+
+            __hash__ = None
+
+        first, second = IdleListener(), Angry()
+        try:
+            spark.streams.addListener(first)
+            spark.streams.addListener(second)
+            spark.streams.removeListener(first)
+            assert spark.streams._sqlb._listener_bus == [second]
+            assert service.listener_removals == 0
+        finally:
+            spark.streams.close()
+
     def 
test_streaming_listener_added_and_removed_by_many_threads_at_once(self, 
mock_connect):
         # The registrations of one listener that several threads add and 
remove at once are
         # each removed once: none is lost, and none is left in the bus.
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 0f1afd35..f7a57d08 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -14216,6 +14216,7 @@ def 
test_a_local_iterator_that_a_thread_is_running_raises_as_a_generator_does(mo
     # As PySpark's toLocalIterator, a generator: while a thread waits in it 
for the next row,
     # the next or close of another thread raises the ValueError of a generator 
that is already
     # executing, and the iterator goes on for the thread that runs it.
+    import sys
     import threading
 
     spark, service = mock_connect
@@ -14223,22 +14224,34 @@ def 
test_a_local_iterator_that_a_thread_is_running_raises_as_a_generator_does(mo
     service.block_result_complete = True
     rows = spark.range(2).toLocalIterator()
     assert [next(rows).id, next(rows).id] == [0, 1]
-    entering = threading.Event()
     outcome = []
 
+    def wait_for_the_row():
+        return next(rows)
+
     def wait_for_the_end():
-        entering.set()
         try:
-            outcome.append(next(rows))
+            outcome.append(wait_for_the_row())
         except BaseException as error:  # noqa: BLE001
             outcome.append(error)
 
+    def in_the_fetch():
+        # The thread is in the call to next once a frame that wait_for_the_row 
called, that of
+        # the generator, is on its stack: the generator is then executing.
+        frame = sys._current_frames().get(waiting.ident)
+        while frame is not None:
+            if frame.f_back is not None and frame.f_back.f_code.co_name == 
"wait_for_the_row":
+                return True
+            frame = frame.f_back
+        return False
+
     waiting = threading.Thread(target=wait_for_the_end)
     waiting.start()
     try:
-        assert entering.wait(5)
-        # The thread is in the fetch, without the GIL, once it has not ended 
for a while.
-        waiting.join(0.5)
+        deadline = time.monotonic() + 5
+        while not in_the_fetch() and time.monotonic() < deadline:
+            time.sleep(0.001)
+        assert in_the_fetch()
         assert waiting.is_alive()
         for call in (lambda: next(rows), rows.close):
             with pytest.raises(ValueError, match="generator already 
executing"):
@@ -18812,6 +18825,49 @@ def 
test_sigint_during_stop_with_a_registered_listener_raises_at_once(mock_conne
     assert spark.is_stopped
 
 
+def 
test_sigint_during_add_listener_keeps_the_registration_removable(mock_connect):
+    # As PySpark's append: a signal that ends the wait for the server's 
acknowledgement raises
+    # KeyboardInterrupt, and the listener stays in the bus, while the server 
still adds its
+    # listener once it answers. A removeListener then removes that 
registration.
+    import signal
+    import threading
+
+    from pyspark.sql.streaming.listener import StreamingQueryListener
+
+    class Listener(StreamingQueryListener):
+        def onQueryStarted(self, event):
+            pass
+
+        def onQueryProgress(self, event):
+            pass
+
+        def onQueryIdle(self, event):
+            pass
+
+        def onQueryTerminated(self, event):
+            pass
+
+    spark, service = mock_connect
+    service.listener_bus_enabled = True
+    service.listener_register_blocked = True
+    listener = Listener()
+    release = threading.Timer(2.5, service.release_listener_registration)
+    timer = threading.Timer(0.5, os.kill, (os.getpid(), signal.SIGINT))
+    release.start()
+    timer.start()
+    try:
+        with pytest.raises(KeyboardInterrupt):
+            spark.streams.addListener(listener)
+    finally:
+        timer.cancel()
+    release.join(5)
+    assert service.wait_listener_registration(1)
+    assert spark.streams._sqlb._listener_bus == [listener]
+    spark.streams.removeListener(listener)
+    assert spark.streams._sqlb._listener_bus == []
+    assert service.listener_removals == 1
+
+
 def 
test_sigint_during_the_plan_compression_lookup_raises_keyboard_interrupt_at_once(mock_connect):
     # As PySpark's: the Config lookup of the plan compression of the first 
plan is a blocked call
     # with no execution in flight, which a signal ends at once, so no 
execution is started.


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

Reply via email to