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 fd522d42 [SPARK-61481][CONNECT][PYTHON][FOLLOWUP] Make getOrCreate and 
the stops of all sessions share one stop lock, and let a signal end the joins 
of listener workers, as PySpark does
fd522d42 is described below

commit fd522d424188e52bfcd583eeda28a76ba9676a9d
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 19:28:19 2026 +0900

    [SPARK-61481][CONNECT][PYTHON][FOLLOWUP] Make getOrCreate and the stops of 
all sessions share one stop lock, and let a signal end the joins of listener 
workers, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    A follow-up of #539 (SPARK-61481), from a review of it. Three of its parts 
did not match PySpark 4.3.0.
    
    1. **One stop lock for the process.** #539's `StopLock` was shared by the 
clones of one session. PySpark's `stop()` runs under `SparkSession._lock`, one 
class-wide `RLock` (pyspark/sql/connect/session.py:122 and :948). So in PySpark 
the stops of all sessions run one at a time, and here a second session's 
release could overlap the first's.
       - The lock is now one static lock of the process 
(`crates/spark-connect/src/session.rs`), and the per-session field is gone.
       - It stays reentrant on the same thread, and its wait still ends at a 
signal in the Python client.
       - A hold of it (`StopLockHold`) leaves the entry of the thread that took 
it.
    2. **`getOrCreate` waits for a stop in progress.** #539 sets `stopped` once 
the release has ended, as PySpark's `is_stopped` follows `client.close()`. But 
the drop-in's `getOrCreate` did not take the lock that `stop()` holds. So 
during a slow release on another thread it returned the session being stopped, 
whose next call then raised NO_ACTIVE_SESSION. PySpark's `getOrCreate` holds 
`SparkSession._lock` (session.py:256), so it waits for the stop and then 
creates a new session.
       - The drop-in's `getOrCreate` now enters the stop lock before its 
lookup, through `spark_connect::session::enter_stop_lock`, a new public 
function of the core. The wait releases the GIL, and a signal ends it.
       - The drop-in's `stop()` without a release (`release_session_on_close = 
False`) holds the lock too, as PySpark's `stop()` does.
       - `getActiveSession` takes no lock, as in PySpark.
    3. **A signal ends the join of a listener worker.** Removing the last 
listener, `streams.close()`, and an `addListener` that joins an earlier worker 
sent the REMOVE and then joined the worker with a blocking `JoinHandle::join`. 
While a listener callback ran, a Ctrl-C did nothing until it returned. 
PySpark's `remove()` sends the REMOVE, then joins the bus thread 
(`self._execution_thread.join()`, a Python join that a signal interrupts on the 
main thread), and only then drops the listener.
       - The joins now wait for the worker to finish through 
`block_on_abortable`.
       - On a signal, the worker and the listeners stay in the bus, as 
PySpark's bus keeps them, and the call raises `KeyboardInterrupt`. An 
interrupted add puts the bus back as it was before the add.
    
    `docs/streaming.md` also says now that `streams.close()` removes every 
listener. PySpark's `close()` iterates its list while `remove()` shortens it, 
so with listeners `[a, b, c]` it leaves `[b]` registered. The drop-in does not 
mirror that.
    
    ### Why are the changes needed?
    
    To match PySpark 4.3.0, with the repo's mock server:
    - Thread 1 stops a session whose ReleaseSession the mock holds, and thread 
2 calls `getOrCreate()` meanwhile. Before, `getOrCreate()` returned the session 
being stopped, at once. Now it returns a new, open session after the release, 
as PySpark's does.
    - `spark.stop()` and `spark.newSession().stop()` on two threads: before, 
both ReleaseSessions were in flight at once. Now the second waits for the first.
    - A listener whose `onQueryIdle` blocks for 10 s, then `removeListener` (or 
`streams.close()`) and a SIGINT at 0.5 s: before, the `KeyboardInterrupt` came 
at 10 s. Now it comes at once, as PySpark's at 0.51 s, and the listener stays 
registered.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, on unreleased changes:
    - In both clients, the stops of all sessions run one at a time.
    - In the Python client, `getOrCreate` waits for a stop in progress, and 
Ctrl-C ends `removeListener`, `streams.close()` and `addListener` while a 
listener callback runs.
    - The Rust API has a new public function, 
`spark_connect::session::enter_stop_lock`, and its type `StopLockHold`.
    
    ### How was this patch tested?
    
    Each new test fails without the change and passes with it:
    - Rust:
      - 
`session::tests::stops_of_different_sessions_run_one_at_a_time_as_pyspark`;
      - 
`streaming::tests::an_interrupted_join_of_a_removed_worker_keeps_the_bus_and_the_worker`.
    - Python (`python/tests/test_dropin_offline.py`):
      - 
`test_get_or_create_waits_for_a_stop_in_progress_and_creates_a_new_session_as_pyspark`;
      - `test_stops_of_two_sessions_run_one_at_a_time_as_pyspark`;
      - 
`test_sigint_during_the_join_of_a_busy_listener_worker_raises_keyboard_interrupt`
 (`removeListener` and `close`);
      - 
`test_sigint_during_the_add_that_joins_a_failing_listener_worker_raises_keyboard_interrupt`.
    
    Also run:
    - `cargo test -p apache-spark-connect --release --lib` (624 passed) and 
`cargo test -p apache-spark-connect -p apache-spark-connect-core --release 
--no-run`;
    - the offline drop-in and ML suites (2021 passed);
    - against a Spark 4.3.0 server: `e2e_streaming`, the session-stop test of 
`e2e_new_methods`, and the listener, stop, stream and interrupt tests of 
`test_dropin_e2e.py`;
    - `cargo fmt --all -- --check`, `ruff 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 #558 from HyukjinKwon/SPARK-61481-followup-stop-lock.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/interrupt.rs    |  36 ++++++
 crates/pyspark-rs/src/session.rs      |  23 +++-
 crates/spark-connect/src/session.rs   | 170 ++++++++++++++++++++++-----
 crates/spark-connect/src/streaming.rs | 126 ++++++++++++++++++--
 docs/streaming.md                     |   4 +
 python/tests/test_dropin_offline.py   | 211 ++++++++++++++++++++++++++++++++++
 6 files changed, 523 insertions(+), 47 deletions(-)

diff --git a/crates/pyspark-rs/src/interrupt.rs 
b/crates/pyspark-rs/src/interrupt.rs
index 3e2090b1..46641eac 100644
--- a/crates/pyspark-rs/src/interrupt.rs
+++ b/crates/pyspark-rs/src/interrupt.rs
@@ -101,6 +101,42 @@ pub(crate) fn interruptible<T: Send, E: Send + 
Into<Box<SparkError>>>(
     interruptible_outcome(py, session, f)?.to_pyerr()
 }
 
+/// Run `f`, a wait that no session stands behind, without the GIL, on the 
calling thread: a
+/// wait of `block_on_abortable` that a signal of the process ends, as the 
acquire of PySpark's
+/// lock is interrupted by one. `f` returns None then, and the exception of 
the signal is raised.
+/// Without a signal, `f` returns its output.
+pub(crate) fn abortable_without_session<T: Send>(
+    py: Python<'_>,
+    f: impl FnOnce() -> Option<T> + Send,
+) -> PyResult<T> {
+    let signal: Arc<Mutex<Option<PyErr>>> = Arc::default();
+    let poll: Arc<WaitWatch> = {
+        let signal = Arc::clone(&signal);
+        Arc::new(move || {
+            let mut error = signal.lock().unwrap_or_else(|e| e.into_inner());
+            if error.is_some() {
+                return Watch::Abort;
+            }
+            // Takes the GIL for the check only, as the wait runs without it.
+            match Python::attach(|py| py.check_signals()) {
+                Ok(()) => Watch::Continue,
+                Err(raised) => {
+                    *error = Some(raised);
+                    Watch::Abort
+                }
+            }
+        })
+    };
+    match py.detach(|| with_wait_watch(poll, f)) {
+        Some(output) => Ok(output),
+        None => Err(signal
+            .lock()
+            .unwrap_or_else(|e| e.into_inner())
+            .take()
+            .unwrap_or_else(|| 
pyo3::exceptions::PyKeyboardInterrupt::new_err(()))),
+    }
+}
+
 /// As [`interruptible`], but a failure of `f` is the inner result, which the 
caller handles, as
 /// a warning. The outer error is the exception of a signal handler only, 
which is never handled
 /// as a failure of the call: as PySpark's `except Exception` does not catch 
it.
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index 0d315ef9..16cb2018 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -197,6 +197,13 @@ impl PySparkSessionBuilder {
     #[pyo3(name = "getOrCreate")]
     fn get_or_create(&self, py: Python<'_>) -> PyResult<Py<PySparkSession>> {
         let (session, created) = {
+            // As PySpark's getOrCreate, which holds `SparkSession._lock` for 
its lookup: a stop in
+            // progress, on any session, is waited for, so that the lookup 
does not return a session
+            // that it stops. A signal ends the wait, as it interrupts the 
acquire of that lock.
+            let _stopping = crate::interrupt::abortable_without_session(
+                py,
+                spark_connect::session::enter_stop_lock,
+            )?;
             let _creating = session_lock();
             match active_session(py).or_else(|| default_session(py)) {
                 Some(session) => (session, false),
@@ -2425,14 +2432,18 @@ impl PySparkSession {
         {
             // As PySpark's stop, whose sleeps between the retries of the 
release a signal
             // interrupts: the exception of the signal is raised at once, and 
leaves the session
-            // open, so nothing below runs. The core runs the stops of other 
threads one at a
-            // time, as PySpark's `SparkSession._lock`, whose acquire a signal 
interrupts too;
-            // the resets below are idempotent, and run with the GIL, after 
the core's stop.
+            // open, so nothing below runs. The core runs the stops of all 
sessions one at a time,
+            // as PySpark's `SparkSession._lock`, whose acquire a signal 
interrupts too; the resets
+            // below are idempotent, and run with the GIL, after the core's 
stop.
             crate::interrupt::interruptible_outcome(py, &self.session, || {
                 self.session.stop().map_err(Box::new)
             })?
         } else {
-            // As PySpark's stop: without the release, the client is closed 
all the same.
+            // As PySpark's stop, which closes the client under 
`SparkSession._lock` all the same.
+            let _stopping = crate::interrupt::abortable_without_session(
+                py,
+                spark_connect::session::enter_stop_lock,
+            )?;
             py.detach(|| self.session.close());
             Ok(())
         };
@@ -2806,8 +2817,8 @@ impl PySparkSession {
     }
 
     /// The class attribute `_lock`, PySpark's `threading.RLock` of the 
session registry, for the
-    /// Python code that takes it. The drop-in serializes the creation of 
sessions with its own
-    /// lock, as `getOrCreate` does with `_lock`.
+    /// Python code that takes it. The drop-in's `getOrCreate` and `stop()` 
serialize through the
+    /// stop lock of the core and their own session lock, not through this 
object.
     #[classattr]
     fn _lock(py: Python<'_>) -> PyResult<Py<PyAny>> {
         Ok(py.import("threading")?.call_method0("RLock")?.unbind())
diff --git a/crates/spark-connect/src/session.rs 
b/crates/spark-connect/src/session.rs
index fc116897..8d08c056 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -135,10 +135,10 @@ impl ThreadTags {
     }
 }
 
-/// The lock that `stop()` holds, shared by the clones of a session, as 
PySpark's `stop()` holds
-/// `SparkSession._lock`, an `RLock`: a `stop()` of another thread waits for 
the one in progress,
-/// and a `stop()` of the thread that holds it, as from a signal handler that 
runs while the
-/// release waits, enters it again.
+/// The lock that `stop()` holds, one for all sessions of the process, as 
PySpark's `stop()` holds
+/// `SparkSession._lock`, a class-wide `RLock`: a `stop()` of another thread 
waits for the one in
+/// progress, whichever session it stops, and a `stop()` of the thread that 
holds it, as from a
+/// signal handler that runs while the release waits, enters it again.
 #[derive(Default)]
 struct StopLock {
     /// The thread that holds the lock, and how many times it entered it.
@@ -147,6 +147,12 @@ struct StopLock {
     left: tokio::sync::Notify,
 }
 
+/// The lock that `stop()` holds.
+fn stop_lock() -> &'static StopLock {
+    static LOCK: std::sync::OnceLock<StopLock> = std::sync::OnceLock::new();
+    LOCK.get_or_init(StopLock::default)
+}
+
 impl StopLock {
     /// Enter the lock for `thread`, unless another thread holds it.
     fn try_enter(&self, thread: std::thread::ThreadId) -> bool {
@@ -163,7 +169,7 @@ impl StopLock {
     /// acquire of PySpark's lock, which a signal of the process interrupts, 
the wait ends with
     /// None when a signal ends it in the Python client (see
     /// 
[`block_on_abortable`](spark_connect_core::runtime::block_on_abortable)).
-    fn enter(&self) -> Option<StopGuard<'_>> {
+    fn enter(&self) -> Option<StopLockHold> {
         let thread = spark_connect_core::runtime::calling_thread_id();
         if !self.try_enter(thread) {
             spark_connect_core::runtime::block_on_abortable(async {
@@ -177,27 +183,49 @@ impl StopLock {
                 }
             })?;
         }
-        Some(StopGuard(self))
+        Some(StopLockHold { thread })
     }
-}
 
-/// The hold of a [`StopLock`] by a `stop()`, which leaves the lock when it 
drops.
-struct StopGuard<'a>(&'a StopLock);
-
-impl Drop for StopGuard<'_> {
-    fn drop(&mut self) {
-        let mut holder = self.0.holder.lock().unwrap_or_else(|e| 
e.into_inner());
-        if let Some((_, depth)) = holder.as_mut() {
-            *depth -= 1;
-            if *depth == 0 {
-                *holder = None;
+    /// Leave the lock by one entry of `thread`, waking the waits for it. A 
hold exists only while
+    /// its thread holds the lock, so the entry is that of the hold, on 
whichever thread it drops.
+    fn leave(&self, thread: std::thread::ThreadId) {
+        let mut holder = self.holder.lock().unwrap_or_else(|e| e.into_inner());
+        if let Some((owner, depth)) = holder.as_mut() {
+            if *owner == thread {
+                *depth -= 1;
+                if *depth == 0 {
+                    *holder = None;
+                }
             }
         }
         drop(holder);
-        self.0.left.notify_waiters();
+        self.left.notify_waiters();
     }
 }
 
+/// A hold of the lock that `stop()` takes, which is left when it drops. See
+/// [`enter_stop_lock`].
+pub struct StopLockHold {
+    /// The thread that entered the lock, whose entry the hold leaves.
+    thread: std::thread::ThreadId,
+}
+
+impl Drop for StopLockHold {
+    fn drop(&mut self) {
+        stop_lock().leave(self.thread);
+    }
+}
+
+/// Enter the lock that `stop()` holds, for as long as the returned hold 
lives, as PySpark's
+/// `getOrCreate` takes `SparkSession._lock` while it looks up or creates a 
session. A `stop()` in
+/// progress on another thread, of any session, is waited for, so that the 
lookup sees a session
+/// that it stops as stopped; one on the calling thread is entered within, as 
the lock is reentrant.
+/// The wait ends with None when a signal of the process ends it in the Python 
client, as the
+/// acquire of PySpark's lock is interrupted; without that, it waits for the 
stop.
+pub fn enter_stop_lock() -> Option<StopLockHold> {
+    stop_lock().enter()
+}
+
 /// A Spark Connect session for interacting with a remote Spark cluster.
 ///
 /// Mirrors `pyspark.sql.SparkSession`.
@@ -225,8 +253,6 @@ pub struct SparkSession {
     /// Whether this session was stopped, by `stop()` once its release ended, 
or by `close()`
     /// (shared across clones). Backs `is_stopped`.
     stopped: Arc<AtomicBool>,
-    /// The lock that `stop()` holds (shared across clones), as PySpark's 
`SparkSession._lock`.
-    stop_lock: Arc<StopLock>,
     /// Successful server version, shared by handles for this session only.
     server_version: Arc<Mutex<Option<String>>>,
     /// The client-side listener bus of the streaming queries of this session 
(shared across
@@ -248,7 +274,6 @@ impl SparkSession {
             python_accumulators: PythonAccumulators::default(),
             observation_metrics_check: Arc::default(),
             stopped: Arc::new(AtomicBool::new(false)),
-            stop_lock: Arc::default(),
             server_version: Arc::new(Mutex::new(None)),
             listener_bus: Arc::default(),
         }
@@ -464,7 +489,6 @@ impl SparkSession {
             python_accumulators: PythonAccumulators::default(),
             observation_metrics_check: Arc::default(),
             stopped: Arc::new(AtomicBool::new(false)),
-            stop_lock: Arc::default(),
             server_version: Arc::new(Mutex::new(None)),
             listener_bus: Arc::default(),
         }
@@ -1384,12 +1408,13 @@ impl SparkSession {
     /// Idempotent, mirroring pyspark: the session is marked stopped even if 
releasing it
     /// on the server fails, and stopping an already stopped session is a 
no-op.
     ///
-    /// As PySpark's `stop()`, which runs under `SparkSession._lock`, the 
`stop()`s of a session
-    /// and of its clones run one at a time: a `stop()` of another thread 
waits for the one in
-    /// progress, and releases the session itself if that one was interrupted 
before it closed
-    /// the session; a `stop()` of the thread that runs one (a signal handler 
of the Python
-    /// client) runs within it. The session is stopped once its release has 
ended, as PySpark's
-    /// `is_stopped` is the client's `is_closed`, which its `stop()` sets 
after the release.
+    /// As PySpark's `stop()`, which runs under `SparkSession._lock`, the 
`stop()`s of all the
+    /// sessions of the process run one at a time: a `stop()` of another 
thread waits for the one
+    /// in progress, whichever session it stops, and releases the session 
itself if that one was
+    /// interrupted before it closed the session; a `stop()` of the thread 
that runs one (a signal
+    /// handler of the Python client) runs within it. The session is stopped 
once its release has
+    /// ended, as PySpark's `is_stopped` is the client's `is_closed`, which 
its `stop()` sets after
+    /// the release.
     ///
     /// Release the server session first, then cancel local listener 
registration/dispatch and
     /// close the client even if release fails. ReleaseSession makes the 
server send the
@@ -1402,7 +1427,7 @@ impl SparkSession {
     pub fn stop(&self) -> Result<()> {
         // A signal of the process ends the wait for another thread's `stop()` 
in the Python
         // client, as it interrupts the acquire of PySpark's lock.
-        let Some(_stopping) = self.stop_lock.enter() else {
+        let Some(_stopping) = enter_stop_lock() else {
             return Err(SparkError::connect_msg(
                 "the wait for the stop of the session on another thread was 
interrupted",
             ));
@@ -1487,7 +1512,6 @@ impl Clone for SparkSession {
             python_accumulators: self.python_accumulators.clone(),
             observation_metrics_check: 
Arc::clone(&self.observation_metrics_check),
             stopped: Arc::clone(&self.stopped),
-            stop_lock: Arc::clone(&self.stop_lock),
             server_version: Arc::clone(&self.server_version),
             listener_bus: Arc::clone(&self.listener_bus),
         }
@@ -3445,6 +3469,92 @@ mod tests {
         assert!(spark.is_stopped());
     }
 
+    /// As PySpark's `stop()`, whose `SparkSession._lock` is one lock of the 
class: the `stop()` of
+    /// another session waits for the release of the one in progress, sends 
its own release only
+    /// after it, and is not stopped until that release has ended.
+    #[test]
+    fn stops_of_different_sessions_run_one_at_a_time_as_pyspark() {
+        use spark_connect_core::runtime::{with_wait_watch, WaitWatch, Watch};
+        use std::sync::mpsc::{channel, RecvTimeoutError};
+        use std::time::{Duration, Instant};
+
+        let server = UnansweringServer::start();
+        let builder =
+            ChannelBuilder::parse(&format!("sc://127.0.0.1:{}", 
server.port)).expect("valid URL");
+        let new_session = || {
+            let mut client =
+                block_on(SparkConnectClient::connect(&builder)).expect("failed 
to build client");
+            // The release fails at once when its connection closes.
+            
client.set_retry_policy(spark_connect_core::retries::RetryPolicy::no_retries());
+            SparkSession::new(client)
+        };
+        let first_session = new_session();
+        let second_session = new_session();
+        let aborted = Arc::new(AtomicBool::new(false));
+        let watch: Arc<WaitWatch> = {
+            let aborted = Arc::clone(&aborted);
+            Arc::new(move || {
+                if aborted.load(Ordering::SeqCst) {
+                    Watch::Abort
+                } else {
+                    Watch::Continue
+                }
+            })
+        };
+        let (first_ended, first) = channel();
+        let interrupted = first_session.clone();
+        std::thread::spawn(move || {
+            let _ = first_ended.send(with_wait_watch(watch, || 
interrupted.stop()));
+        });
+        let deadline = Instant::now() + Duration::from_secs(5);
+        while server.connections.lock().unwrap().is_empty() {
+            assert!(
+                Instant::now() < deadline,
+                "the release of the first stop connects"
+            );
+            std::thread::sleep(Duration::from_millis(5));
+        }
+        let (second_ended, second) = channel();
+        let waiting = second_session.clone();
+        std::thread::spawn(move || {
+            let _ = second_ended.send(waiting.stop());
+        });
+        assert!(
+            matches!(
+                second.recv_timeout(Duration::from_millis(300)),
+                Err(RecvTimeoutError::Timeout)
+            ),
+            "a stop of another session returned while the release of the first 
was in progress"
+        );
+        let connected = server.connections.lock().unwrap().len();
+        assert_eq!(
+            connected, 1,
+            "the release of the other session was sent while the first stop 
was in progress"
+        );
+        aborted.store(true, Ordering::SeqCst);
+        first
+            .recv_timeout(Duration::from_secs(5))
+            .expect("the watch ends the first stop")
+            .expect_err("the first stop is interrupted");
+        // The second stop releases its session once the first one has left 
the lock.
+        let deadline = Instant::now() + Duration::from_secs(5);
+        while server.connections.lock().unwrap().len() < 2 {
+            assert!(
+                Instant::now() < deadline,
+                "the second stop sends its release once the first has left the 
lock"
+            );
+            std::thread::sleep(Duration::from_millis(5));
+        }
+        assert!(!second_session.is_stopped());
+        drop(server);
+        second
+            .recv_timeout(Duration::from_secs(5))
+            .expect("the second stop ends with its release")
+            .expect_err("the release of the second stop fails as its 
connection closes");
+        assert!(second_session.is_stopped());
+        assert!(!first_session.is_stopped());
+    }
+
     #[test]
     fn forward_to_fs_artifact_name_is_the_prefix_and_the_absolute_path() {
         // As the reference's `FORWARD_TO_FS_PREFIX + dest_path`, with no 
separator added.
diff --git a/crates/spark-connect/src/streaming.rs 
b/crates/spark-connect/src/streaming.rs
index 42d3ae6c..aa74f232 100644
--- a/crates/spark-connect/src/streaming.rs
+++ b/crates/spark-connect/src/streaming.rs
@@ -1158,9 +1158,7 @@ impl ListenerBus {
         let changed = self.changed.0.notified();
         drop(state);
         if spark_connect_core::runtime::block_on_abortable(changed).is_none() {
-            return Err(SparkError::connect_msg(
-                "the wait for the streaming query listener bus was 
interrupted",
-            ));
+            return Err(interrupted_wait());
         }
         Ok(self.lock())
     }
@@ -1209,6 +1207,11 @@ impl ListenerBus {
     }
 }
 
+/// The error of a wait of the bus that a signal of the process ended in the 
Python client.
+fn interrupted_wait() -> SparkError {
+    SparkError::connect_msg("the wait for the streaming query listener bus was 
interrupted")
+}
+
 /// Drop listeners that left the bus, or the snapshot of a delivery, one by 
one and never under
 /// the state lock: the last reference to a listener runs its `Drop`, which is 
code of the user
 /// as its callbacks are. It may call back into the bus, and its panic is 
reported and isolated
@@ -1437,6 +1440,7 @@ impl StreamingQueryManager {
         // 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);
+        let previous_generation = state.generation;
         state.phase = ListenerBusPhase::Starting;
         // An earlier worker must not clear this registration's cancellation 
sender.
         state.generation = state.generation.wrapping_add(1);
@@ -1445,8 +1449,23 @@ impl StreamingQueryManager {
         state.cancel = Some(cancel);
         let previous = state.thread.take();
         drop(state);
+        if let Some(previous) = previous {
+            if let Some(previous) = Self::join_listener_thread(previous) {
+                // A signal ended the wait for the earlier worker to exit. 
Nothing of this add has
+                // been sent, so the bus is as it was before it: the 
registrations, the generation
+                // and the server registration of the earlier worker, which it 
joins later.
+                let mut state = self.bus.lock();
+                state.listeners = stale;
+                state.generation = previous_generation;
+                state.thread = Some(previous);
+                state.server_registration_held |= release_server;
+                state.cancel.take();
+                state.phase = ListenerBusPhase::Idle;
+                self.bus.changed.notify_all();
+                return Err(interrupted_wait());
+            }
+        }
         drop_isolated(stale);
-        Self::join_listener_thread(previous);
         if release_server {
             if let Err(error) = self.remove_server_listener(false) {
                 // Without the removal, the server would answer the add below 
with no response,
@@ -1689,7 +1708,20 @@ impl StreamingQueryManager {
             // Keep worker_id and Stopping until after the join: callbacks 
must still be
             // able to recognize their worker and coalesce a concurrent 
remove/close.
             drop(state);
-            Self::join_listener_thread(worker);
+            if let Some(worker) = worker {
+                if let Some(worker) = Self::join_listener_thread(worker) {
+                    // A signal ended the wait for the worker to exit, after 
the removal was
+                    // sent. As PySpark's removal, which the REMOVE precedes, 
the listeners stay
+                    // in the bus; the worker is kept, so that a later 
removal, close or add
+                    // joins it, and the wait is the error of the call.
+                    let mut state = self.bus.lock();
+                    state.thread = Some(worker);
+                    state.phase = ListenerBusPhase::Idle;
+                    self.bus.changed.notify_all();
+                    drop(state);
+                    return removal.and(Err(interrupted_wait()));
+                }
+            }
             state = self.bus.lock();
             removed = std::mem::take(&mut state.listeners);
             state.cancel.take();
@@ -1747,14 +1779,30 @@ impl StreamingQueryManager {
         drop(worker);
     }
 
-    /// Join the event worker unless called from that worker itself.
-    fn join_listener_thread(handle: Option<std::thread::JoinHandle<()>>) {
-        if let Some(handle) = handle {
-            // A listener may remove itself from its callback. It cannot join 
itself;
-            // after the callback returns the stopped stream lets its worker 
exit.
-            if handle.thread().id() != std::thread::current().id() {
+    /// Join the event worker, after waiting for it to exit, unless called 
from that worker
+    /// itself. A worker cannot join itself, and after its callback returns 
the stopped stream
+    /// lets it exit. A signal that ends the wait in the Python client (see
+    /// 
[`block_on_abortable`](spark_connect_core::runtime::block_on_abortable)) gives 
the worker
+    /// back, unjoined, as `Some`, so that a later removal, close or add joins 
it.
+    fn join_listener_thread(
+        handle: std::thread::JoinHandle<()>,
+    ) -> Option<std::thread::JoinHandle<()>> {
+        // A listener may remove itself from its callback. Its handle is 
dropped, which detaches it.
+        if handle.thread().id() == std::thread::current().id() {
+            return None;
+        }
+        let exited = spark_connect_core::runtime::block_on_abortable(async {
+            let mut ticks = 
tokio::time::interval(std::time::Duration::from_millis(5));
+            while !handle.is_finished() {
+                ticks.tick().await;
+            }
+        });
+        match exited {
+            Some(()) => {
                 let _ = handle.join();
+                None
             }
+            None => Some(handle),
         }
     }
 
@@ -3075,6 +3123,62 @@ mod tests {
         }
     }
 
+    /// As PySpark's removal, whose join of the listener thread follows the 
REMOVE: a signal that
+    /// ends the join in the Python client ends the call with an error, and 
leaves the bus with
+    /// its listeners and its worker, which a later removal joins once the 
worker has exited.
+    #[test]
+    fn an_interrupted_join_of_a_removed_worker_keeps_the_bus_and_the_worker() {
+        use spark_connect_core::runtime::{with_wait_watch, WaitWatch, Watch};
+
+        struct Listener;
+        impl StreamingQueryListener for Listener {
+            fn on_event(&self, _: &StreamingQueryListenerEvent) {}
+        }
+
+        let spark = unreachable_session_without_retries();
+        let manager = spark.streams();
+        // A worker that stays in its callback until the test lets it exit.
+        let (exit, exited) = std::sync::mpsc::channel::<()>();
+        let worker = std::thread::spawn(move || {
+            // Exits on its own, so that a join that ignores the signal fails 
rather than hangs.
+            let _ = exited.recv_timeout(std::time::Duration::from_secs(5));
+        });
+        let generation = {
+            let mut state = manager.bus.lock();
+            state
+                .listeners
+                .push(("only".to_string(), Arc::new(Listener)));
+            state.phase = ListenerBusPhase::Stopping;
+            state.worker_id = Some(worker.thread().id());
+            state.generation
+        };
+        // The REMOVE has been sent, so the removal succeeded; only the join 
is interrupted.
+        let abort: Arc<WaitWatch> = Arc::new(|| Watch::Abort);
+        with_wait_watch(abort, || {
+            manager.finish_listener_removal(generation, Some(worker), Ok(()))
+        })
+        .expect_err("the signal ends the join");
+        {
+            let state = manager.bus.lock();
+            assert_eq!(state.listeners.len(), 1);
+            assert_eq!(state.phase, ListenerBusPhase::Idle);
+            assert!(
+                state.thread.is_some(),
+                "the worker is kept to be joined later"
+            );
+            assert!(state.worker_id.is_some());
+        }
+        exit.send(()).unwrap();
+        let worker = manager.bus.lock().thread.take();
+        manager
+            .finish_listener_removal(generation, worker, Ok(()))
+            .expect("a later removal joins the worker");
+        let state = manager.bus.lock();
+        assert!(state.listeners.is_empty());
+        assert!(state.thread.is_none());
+        assert!(state.worker_id.is_none());
+    }
+
     #[test]
     fn stream_writer_partition_by() {
         let spark = session();
diff --git a/docs/streaming.md b/docs/streaming.md
index a144537c..920e1008 100644
--- a/docs/streaming.md
+++ b/docs/streaming.md
@@ -136,6 +136,10 @@ clears the subscription's listeners. Add the listeners 
again to open a subscript
 A server-side end of the event stream also clears registrations without a 
warning;
 reference PySpark retains them after a normal stream end.
 
+`streams.close()` removes every listener. Reference PySpark's `close()` 
removes the listeners
+while it iterates over its list, which each removal shortens, so with three 
listeners it leaves
+the second one registered, with the server's listener. The drop-in does not 
mirror that.
+
 Callback exceptions derived from `Exception` produce per-listener warnings and
 dispatch continues. An uncaught `BaseException`, or a callback warning 
promoted to
 an error by Python's warning filters, terminates the native subscription and 
clears
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index bee87ee0..4c0760ae 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -19434,6 +19434,80 @@ def 
test_a_stop_from_a_signal_handler_while_stop_releases_runs_within_it_as_pysp
     assert spark.is_stopped
 
 
+def 
test_get_or_create_waits_for_a_stop_in_progress_and_creates_a_new_session_as_pyspark(
+    mock_connect,
+):
+    # As PySpark's getOrCreate, which takes SparkSession._lock, the lock that 
stop() holds through
+    # its release: a getOrCreate during the release waits for it, finds the 
session stopped, and
+    # creates a new session, which is open.
+    import threading
+
+    from pyspark.sql import SparkSession
+
+    spark, service = mock_connect
+    service.release_session_blocked = True
+    stopper = threading.Thread(target=spark.stop, daemon=True)
+    stopper.start()
+    deadline = time.monotonic() + 5
+    while service.release_session_calls < 1 and time.monotonic() < deadline:
+        time.sleep(0.01)
+    outcome = {}
+
+    def get_or_create():
+        outcome["session"] = 
SparkSession.builder.remote(service.remote).getOrCreate()
+        outcome["returned"] = time.monotonic()
+
+    getter = threading.Thread(target=get_or_create, daemon=True)
+    getter.start()
+    try:
+        getter.join(0.5)
+        assert getter.is_alive(), "getOrCreate returned during the release of 
stop"
+    finally:
+        released = time.monotonic()
+        service.release_session_blocked = False
+        service.release_session_release()
+    stopper.join(5)
+    getter.join(5)
+    created = outcome["session"]
+    try:
+        assert outcome["returned"] >= released
+        assert created is not spark
+        assert spark.is_stopped
+        assert not created.is_stopped
+    finally:
+        created.stop()
+
+
+def test_stops_of_two_sessions_run_one_at_a_time_as_pyspark(mock_connect):
+    # As PySpark's stop, whose SparkSession._lock is one lock of the class: 
the stop of another
+    # session waits for the release of the one in progress, and sends its own 
release after it.
+    import threading
+
+    spark, service = mock_connect
+    other = spark.newSession()
+    service.release_session_blocked = True
+    stopper = threading.Thread(target=spark.stop, daemon=True)
+    stopper.start()
+    deadline = time.monotonic() + 5
+    while service.release_session_calls < 1 and time.monotonic() < deadline:
+        time.sleep(0.01)
+    other_stopper = threading.Thread(target=other.stop, daemon=True)
+    other_stopper.start()
+    try:
+        other_stopper.join(0.5)
+        assert other_stopper.is_alive(), "the stop of another session did not 
wait"
+        assert service.release_session_calls == 1
+        assert not other.is_stopped
+    finally:
+        service.release_session_blocked = False
+        service.release_session_release()
+    stopper.join(5)
+    other_stopper.join(5)
+    assert service.release_session_calls == 2
+    assert spark.is_stopped
+    assert other.is_stopped
+
+
 def 
test_sigint_during_the_removal_of_the_last_listener_raises_keyboard_interrupt_as_pyspark(
     mock_connect,
 ):
@@ -19498,6 +19572,143 @@ def 
test_sigint_during_the_removal_of_the_last_listener_raises_keyboard_interrup
     assert service.wait_listener_removal(1)
 
 
+def _blocking_idle_listener(entered, release):
+    from pyspark.sql.streaming.listener import StreamingQueryListener
+
+    class Blocking(StreamingQueryListener):
+        def onQueryStarted(self, event):
+            pass
+
+        def onQueryProgress(self, event):
+            pass
+
+        def onQueryIdle(self, event):
+            entered.set()
+            release.wait(10)
+
+        def onQueryTerminated(self, event):
+            pass
+
+    return Blocking()
+
+
[email protected]("interrupted_call", ["removeListener", "close"])
+def 
test_sigint_during_the_join_of_a_busy_listener_worker_raises_keyboard_interrupt(
+    mock_connect,
+    interrupted_call,
+):
+    # As PySpark's remove, which sends the REMOVE and then joins the thread of 
the listener, a
+    # thread that the join waits for on a callback that does not return: a 
signal raises
+    # KeyboardInterrupt at once, the REMOVE stays sent, and the listener stays 
in the bus. A
+    # later removal or close joins the worker and empties the bus.
+    import signal
+    import threading
+
+    entered, release = threading.Event(), threading.Event()
+    spark, service = mock_connect
+    service.listener_bus_enabled = True
+    listener = _blocking_idle_listener(entered, release)
+    spark.streams.addListener(listener)
+    service.listener_event(
+        spark.session_id,
+        3,
+        {
+            "id": "00000000-0000-4000-8000-000000000001",
+            "runId": "00000000-0000-4000-8000-000000000002",
+            "timestamp": "idle",
+        },
+    )
+    try:
+        assert entered.wait(5)
+        timer = threading.Timer(0.5, os.kill, (os.getpid(), signal.SIGINT))
+        started = time.monotonic()
+        timer.start()
+        try:
+            with pytest.raises(KeyboardInterrupt):
+                if interrupted_call == "close":
+                    spark.streams.close()
+                else:
+                    spark.streams.removeListener(listener)
+        finally:
+            timer.cancel()
+        assert time.monotonic() - started < 3
+        assert service.listener_removals == 1
+        assert spark.streams._sqlb._listener_bus == [listener]
+    finally:
+        release.set()
+    spark.streams.removeListener(listener)
+    assert spark.streams._sqlb._listener_bus == []
+
+
+def 
test_sigint_during_the_add_that_joins_a_failing_listener_worker_raises_keyboard_interrupt(
+    mock_connect,
+):
+    # As PySpark's add, whose bus takes the new listener only once the failed 
one is gone: a
+    # signal ends the wait for a worker whose terminal notification (a 
warning) does not return.
+    # The add sends nothing, the bus keeps its listeners, and the next add 
removes the server's
+    # listener of the failed subscription before its own ADD.
+    import signal
+    import threading
+    import warnings
+
+    from pyspark.sql.streaming.listener import StreamingQueryListener
+
+    class Plain(StreamingQueryListener):
+        def onQueryStarted(self, event):
+            pass
+
+        def onQueryProgress(self, event):
+            pass
+
+        def onQueryIdle(self, event):
+            pass
+
+        def onQueryTerminated(self, event):
+            pass
+
+    warning_entered, warning_release = threading.Event(), threading.Event()
+    previous_showwarning = warnings.showwarning
+
+    def blocking_showwarning(*args, **kwargs):
+        warning_entered.set()
+        warning_release.wait(10)
+
+    spark, service = mock_connect
+    service.listener_bus_enabled = True
+    first = Plain()
+    second = Plain()
+    spark.streams.addListener(first)
+    warnings.showwarning = blocking_showwarning
+    try:
+        with warnings.catch_warnings():
+            warnings.simplefilter("always")
+            service.end_listener_stream(spark.session_id, failure=True)
+            assert warning_entered.wait(5)
+            timer = threading.Timer(0.5, os.kill, (os.getpid(), signal.SIGINT))
+            started = time.monotonic()
+            timer.start()
+            try:
+                with pytest.raises(KeyboardInterrupt):
+                    spark.streams.addListener(second)
+            finally:
+                timer.cancel()
+            assert time.monotonic() - started < 3
+            assert service.listener_subscriptions == 1
+            assert service.listener_removals == 0
+            warning_release.set()
+            deadline = time.monotonic() + 5
+            while spark.streams._sqlb._listener_bus and time.monotonic() < 
deadline:
+                time.sleep(0.01)
+            spark.streams.addListener(second)
+            assert service.listener_removals == 1
+            assert service.wait_listener_registration(2)
+            assert spark.streams._sqlb._listener_bus == [second]
+            spark.streams.removeListener(second)
+    finally:
+        warning_release.set()
+        warnings.showwarning = previous_showwarning
+
+
 def 
test_sigint_during_a_native_kmeans_fit_raises_keyboard_interrupt(mock_connect):
     # As the other native estimators of pyspark.ml.connect: the fit waits for 
the server as an
     # execution, which a signal interrupts on the server.


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

Reply via email to