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 673ed1e6 [SPARK-61481][CONNECT][PYTHON] Let a second stop() release
the session after an interrupted one, and let a signal end the waits of the
streaming listener bus, in the Python client as PySpark does
673ed1e6 is described below
commit 673ed1e6866836303fa3773bb89e5faca260a669
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 16:07:57 2026 +0900
[SPARK-61481][CONNECT][PYTHON] Let a second stop() release the session
after an interrupted one, and let a signal end the waits of the streaming
listener bus, in the Python client as PySpark does
### What changes were proposed in this pull request?
[SPARK-61481](https://issues.apache.org/jira/browse/SPARK-61481): Two fixes
to how signals end the waits of `SparkSession.stop()` and of the streaming
listener bus. Both are in the Rust API (`crates/spark-connect`), so the Python
client gets them too.
1. `SparkSession::stop` (`crates/spark-connect/src/session.rs`) now runs
under a lock of the session that its clones share (`StopLock`). PySpark's
`stop()` does the same under `SparkSession._lock`, an `RLock`
(`pyspark/sql/connect/session.py:122, 948`).
- A `stop()` on another thread waits for the one in progress. If a
signal interrupts that one before it closes the session, the waiting `stop()`
finds the session open, releases it and closes it. PySpark's second `stop()`
does this once the first one's `KeyboardInterrupt` leaves the lock.
- The wait goes through `block_on_abortable`, so in the Python client a
signal ends it, as a signal interrupts the acquire of PySpark's lock on POSIX.
The Rust API installs no signal watch, so it waits as for any lock.
- The lock is reentrant, as an `RLock` is. A `stop()` on the thread that
holds it runs inside the first one instead of deadlocking. That happens when a
signal handler calls `spark.stop()` while the release of `stop()` waits.
- `stopped` is now set once the release has ended (still before the
listener bus is cancelled), not when `stop()` starts. So `is_stopped` is false
while the release is in flight. PySpark's `is_stopped` is `client.is_closed`
(`session.py:1048`), which its `stop()` sets after the release. An interrupted
`stop()` no longer has to reset the flag.
- While the lock is held, the following run: the release RPC (in the
Python client, also the signal handlers that the wait's polls run),
`cancel_listener_bus` (a short lock of the bus, no join) and `client.close()`
(a flag). None of them waits for another thread's `stop()`.
- The drop-in's resets run after the core's `stop()` returns, with the
GIL: `forget_session`, the default and active session, and the cached
SQLContext. They are idempotent, so a second `stop()` that finds the session
stopped runs them again, as PySpark's second `stop()` does.
- `close()` (`client.close()`, and `stop()` with
`release_session_on_close = False`) still takes no lock. It closes at once, as
PySpark's `client.close()` does.
2. The listener bus (`crates/spark-connect/src/streaming.rs`) waited on a
`std::sync::Condvar`, which no signal can end. It now wakes its waits with a
`tokio::sync::Notify` (`BusChanged`, which keeps the existing `notify_all`
calls). `ListenerBus::wait` waits on it through `block_on_abortable`, then
locks the state again through `ListenerBus::lock`, so it stays poison-tolerant
as SPARK-61441 made it. Without a watch (the Rust API) it waits for the change
as before. In the Python clien [...]
- the removal of the last listener, and `close()`, waiting for a started
event that another thread is delivering (the wait of the finding);
- the removal of one of several listeners, waiting for the deliveries in
flight;
- a removal or an add, waiting for another thread's add or last removal
(`idle_state`).
An interrupted wait leaves the bus as it was:
- The first and the third wait happen before anything changes.
- The second removes the listener before it waits. It now puts the
listener back at its place, unless its subscription ended meanwhile (for
example, its worker failed and cleared the bus); then the listener is dropped
after the lock is released, as the bus drops the listeners that leave it
(`drop_isolated`).
The drop-in's `removeListener`, `addListener` and `streams.close()` then
raise the `KeyboardInterrupt`, and the listener stays registered, as after
PySpark's interrupted `with self._lock`.
3. `add_listener` (`crates/spark-connect/src/streaming.rs`) marks the
server registration held (`server_registration_held`) when the wait for the
server's acknowledgement fails after the stream that sends the ADD was opened.
The failure is a signal in the Python client or a transport error. The next
subscription then sends a REMOVE before its ADD. At worst, that REMOVE finds no
listener on the server.
4. As a consequence of item 1, a native model or a cached remote relation
released while the release of `stop()` waits is now released on the server.
PySpark's `del_remote_cache` and `CachedRemoteRelation.__del__` do the same,
since they check only that the session is active and its client open.
`test_ml_offline.py`'s
`test_native_models_released_while_their_session_stops_send_no_delete` checked
the old behavior; it is now
`test_native_models_released_while_their_session_stops_send_th [...]
### Why are the changes needed?
- Concurrent `stop()`:
- Core `stop()` set `stopped` before the release, so a `stop()` on
another thread returned at once and its caller was told that the session was
stopped.
- When a signal then interrupted the first `stop()`, it reset `stopped`,
and the session stayed open.
- Probe on the repo's mock server (`stop_probe.py two_stops`): the server
holds ReleaseSession, the main thread calls `stop()`, another thread calls
`stop()`, then a SIGINT. Official PySpark 4.3.0 prints:
```
main KeyboardInterrupt after 0.4s
other before the signal: still waiting
release calls=2 (second reached: True); is_stopped while held=False;
other alive=True
other: returned after 0.5s, is_stopped=True; is_stopped=True; release
calls=2
```
- With this change, the Python client prints the same four lines.
- Before it, the second `stop()` returned at once and only one
ReleaseSession was sent. The new test fails with `assert 1 == 2` on the release
count.
- A `stop()` from a signal handler (`reentrant_probe.py`): a SIGINT handler
calls `spark.stop()` while the release of `stop()` is held.
- Official PySpark 4.3.0 and the Python client with this change behave
the same: the handler sees `is_stopped` False, its `stop()` sends a second
ReleaseSession and leaves the session stopped, and the first `stop()` returns
after 0.2 s.
- Before the change, the handler saw `is_stopped` True, and its `stop()`
returned without releasing the session.
- The listener bus:
- PySpark 4.3.0's `StreamingQueryListenerBus` was probed directly,
without a server (`official_bus_probe.py`): a started event in delivery on
another thread, and `remove` of the last listener on the main thread. It raises
KeyboardInterrupt 0.3 s after the SIGINT and keeps the listener.
- The official client cannot add a listener on the mock server: it checks
the session ID of the listener-bus responses, which the mock leaves empty. So
the bus was probed directly.
- Before the change, the Python client's `removeListener` ignored the
signal and returned only once `onQueryStarted` returned (5 s in the test).
- With the change, it raises KeyboardInterrupt after 0.4 s, sends no
REMOVE and keeps the listener. A later `removeListener` removes it and sends
the REMOVE.
- An add whose acknowledgement wait fails (found by a post-hoc review of
this PR):
- Spark 4.3.0's listener-bus handler keeps the listener that an ADD
registered until a REMOVE, or a failed event send. It does not answer a second
ADD of the session.
- With the signals of item 2, a second Ctrl-C ends the acknowledgement
wait of `addListener`; before, a transport error could. The server may have
added its listener by then, and the bus did not mark it held.
- So the next `addListener` sent an ADD that the server never answers,
and waited forever.
- On the repo's mock server, which does answer that ADD, the next add
sent no REMOVE before it (`listener_removals` 0).
### Does this PR introduce _any_ user-facing change?
Yes.
- A `stop()` of a session (or of a clone) waits while another thread's
`stop()` of it is in progress. If that one is interrupted, the waiting `stop()`
releases and closes the session itself. Before, it returned at once.
- `is_stopped` is false while the release of `stop()` is in flight. It was
true.
- In the Python client, Ctrl-C raises `KeyboardInterrupt` from:
- a `stop()` that waits for another thread's `stop()`;
- `removeListener`, `addListener` and `streams.close()` while they wait
for another thread's delivery or listener add/removal. The listener stays
registered.
- In the Rust API, which installs no signal watch, the waits are unchanged.
- After a failed acknowledgement wait of an add, the next add removes the
server's listener first, where it waited forever.
- A native model or a cached DataFrame released while the release of
`stop()` waits is released on the server, as in PySpark.
### How was this patch tested?
New tests. Each fails with the source changes reverted by hand (keeping the
test code), and passes with them:
- Python, offline, in `python/tests/test_dropin_offline.py`, after
`test_sigint_during_the_release_of_stop_raises_keyboard_interrupt_and_keeps_the_session`,
on the mock server that holds ReleaseSession:
-
`test_a_stop_that_waits_for_an_interrupted_stop_releases_the_session_as_pyspark`:
two threads stop one session and a SIGINT ends the first `stop()`. The second
sends the second ReleaseSession, and `is_stopped` stays false until that
release ends. Without the fix: `assert 1 == 2` (one ReleaseSession). With it:
0.42 s.
-
`test_a_stop_from_a_signal_handler_while_stop_releases_runs_within_it_as_pyspark`:
a SIGINT handler stops the session while the release is held. Its `stop()`
runs inside the first one, releases and closes. Without the fix: `assert [True,
True] == [False, True]`. With it: 0.23 s.
-
`test_sigint_during_the_removal_of_the_last_listener_raises_keyboard_interrupt_as_pyspark`:
`onQueryStarted` blocks on another thread while the main thread calls
`removeListener` of the last listener. A SIGINT raises KeyboardInterrupt within
3 s, the listener stays and no REMOVE is sent; a later removal sends it.
Without the fix, `removeListener` returned after 5.0 s. With it: 0.41 s.
- Rust:
-
`session::tests::a_stop_that_waits_for_an_interrupted_stop_releases_the_session_as_pyspark`,
after
`release_session_of_a_stopped_session_raises_no_active_session_as_pyspark`. A
local port that accepts connections and never answers holds the releases, and a
watch that aborts ends the first `stop()`. The second `stop()` waits, then
releases, and the session is not stopped until that release ends. Without the
fix it fails with "a stop returned while another one released the session".
-
`streaming::tests::an_interrupted_wait_of_a_removal_leaves_the_bus_as_it_was_as_pyspark`,
after `the_listener_event_stream_reports_no_progress_to_the_handlers`. It
covers three cases: the last listener, one of two, and an add in progress on
another thread. After the interrupted wait the bus is unchanged, and a later
removal goes through. Without the fix it fails with "the watch ends the wait of
the removal: Timeout".
- Both pass in 1.2 s.
- Commands and results (release builds, on top of SPARK-61441's
poison-tolerant bus lock):
- `cargo test -p apache-spark-connect-core --release --lib`: 197 passed,
including the 16 `runtime::` tests.
- `cargo test -p apache-spark-connect --release --lib`: 610 passed,
including SPARK-61441's four bus tests
(`a_panicking_callback_does_not_break_later_add_remove_and_dispatch`,
`a_poisoned_state_lock_does_not_fail_later_calls_on_the_bus`,
`the_guards_of_the_bus_do_not_abort_when_a_panic_unwinds_them_with_a_poisoned_lock`,
`a_listener_removed_from_the_bus_is_dropped_without_the_state_lock`).
- `cargo test -p apache-spark-connect --release --no-run`, and the same
with `--features wasm-udf`: built without warnings.
- `cargo fmt --all --check`: clean.
- `cargo clippy -p apache-spark-connect --release --all-targets` and
`cargo clippy -p pyspark-rs --release --all-targets`: no diagnostics on the
changed lines.
- `ruff check python/tests/test_dropin_offline.py`: passed.
- Offline Python, `pytest tests/test_dropin_offline.py -k "sigint or stop
or listener or streaming or interrupt or signal or Streaming"`: 96 passed. This
includes the listener lifecycle cases of `streaming_listener_cases.py`, with
SPARK-61443's three new ones.
- Live, against a local Spark Connect 4.3.0 server
(`SPARK_REMOTE=sc://localhost:15014`):
- `pytest tests/test_dropin_e2e.py -k "listener or stop or stream or
interrupt or sigint or Streaming"`: 15 passed.
- `cargo test -p apache-spark-connect --release --test e2e_streaming`:
5 passed.
- `--test e2e_new_methods session_stop`: 1 passed.
- `--test e2e_integration`: 20 passed.
- Official `pyspark/sql/tests/connect/streaming/test_parity_listener.py`
of 4.3.0, run on the Python client against the same server: 9 passed.
- Added after the post-hoc review:
-
`test_a_second_sigint_during_add_listener_removes_the_server_listener_before_the_next_add`
(`test_dropin_offline.py`, after
`test_sigint_during_add_listener_keeps_the_registration_removable`):
- Two SIGINTs end the acknowledgement wait of `addListener` after the
mock server added its listener.
- The next `addListener` sends a REMOVE before its ADD.
- Without the change it fails with `assert 0 == 1` on
`listener_removals`.
-
`test_native_models_released_while_their_session_stops_send_their_delete_as_pyspark`
(`test_ml_offline.py`):
- A model released while ReleaseSession waits sends its Delete, and
`is_stopped` is False meanwhile.
- A model released once the session is stopped sends none.
- Rebased onto master f27e2333. The conflicts with SPARK-61426 in
`crates/pyspark-rs/src/interrupt.rs` and `crates/spark-connect/src/session.rs`
are resolved by keeping both sides' lines.
- Checks on the rebase:
- the lib tests of both crates (834 passed);
- the build of all tests, also with `wasm-udf` and `datafusion,polars`,
without warnings;
- `cargo fmt --all --check`, and clippy with no diagnostics on the
changed lines;
- a full trial before the merge.
### 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 #539 from HyukjinKwon/SPARK-61481-stop-lock-and-bus-waits.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/interrupt.rs | 5 +-
crates/pyspark-rs/src/session.rs | 4 +-
crates/spark-connect/src/session.rs | 215 ++++++++++++++++++++++++++++++++--
crates/spark-connect/src/streaming.rs | 186 +++++++++++++++++++++++++++--
python/tests/test_dropin_offline.py | 207 ++++++++++++++++++++++++++++++++
python/tests/test_ml_offline.py | 38 ++++--
6 files changed, 622 insertions(+), 33 deletions(-)
diff --git a/crates/pyspark-rs/src/interrupt.rs
b/crates/pyspark-rs/src/interrupt.rs
index cd0964d4..3e2090b1 100644
--- a/crates/pyspark-rs/src/interrupt.rs
+++ b/crates/pyspark-rs/src/interrupt.rs
@@ -89,7 +89,10 @@ impl SignalWatch {
/// answer): the retries and the RPCs of `f` that are not answered when the
first signal arrives
/// during an execution, and all of them when no execution is in flight, or
after a second
/// signal. A streaming execution is still read after the first one, until the
server cancels it.
-/// A wait of `block_on_abortable` (the release of `stop()`) ends at once as
well.
+/// A wait of `block_on_abortable` ends at once as well: the release of
`stop()`, the wait of a
+/// `stop()` for that of another thread, and the waits of the listener bus for
the deliveries and
+/// the lifecycle operations of other threads, as a signal interrupts the
acquire of PySpark's
+/// locks.
pub(crate) fn interruptible<T: Send, E: Send + Into<Box<SparkError>>>(
py: Python<'_>,
session: &SparkSession,
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index effcb265..dd24a4c9 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -2423,7 +2423,9 @@ 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.
+ // 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.
crate::interrupt::interruptible_outcome(py, &self.session, || {
self.session.stop().map_err(Box::new)
})?
diff --git a/crates/spark-connect/src/session.rs
b/crates/spark-connect/src/session.rs
index ecd0c93e..fc116897 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -135,6 +135,69 @@ 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.
+#[derive(Default)]
+struct StopLock {
+ /// The thread that holds the lock, and how many times it entered it.
+ holder: Mutex<Option<(std::thread::ThreadId, usize)>>,
+ /// Wakes the waits for the lock when it is left.
+ left: tokio::sync::Notify,
+}
+
+impl StopLock {
+ /// Enter the lock for `thread`, unless another thread holds it.
+ fn try_enter(&self, thread: std::thread::ThreadId) -> bool {
+ let mut holder = self.holder.lock().unwrap_or_else(|e| e.into_inner());
+ match holder.as_mut() {
+ None => *holder = Some((thread, 1)),
+ Some((owner, depth)) if *owner == thread => *depth += 1,
+ Some(_) => return false,
+ }
+ true
+ }
+
+ /// Enter the lock for the calling thread, waiting while another thread
holds it. As the
+ /// 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<'_>> {
+ let thread = spark_connect_core::runtime::calling_thread_id();
+ if !self.try_enter(thread) {
+ spark_connect_core::runtime::block_on_abortable(async {
+ loop {
+ // Made before the check, so that the lock left after it
wakes the wait.
+ let left = self.left.notified();
+ if self.try_enter(thread) {
+ return;
+ }
+ left.await;
+ }
+ })?;
+ }
+ Some(StopGuard(self))
+ }
+}
+
+/// 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;
+ }
+ }
+ drop(holder);
+ self.0.left.notify_waiters();
+ }
+}
+
/// A Spark Connect session for interacting with a remote Spark cluster.
///
/// Mirrors `pyspark.sql.SparkSession`.
@@ -159,9 +222,11 @@ pub struct SparkSession {
python_accumulators: PythonAccumulators,
/// The check of the metrics of the Observations of its executions (shared
across clones).
observation_metrics_check: Arc<Mutex<Option<ObservationMetricsCheck>>>,
- /// Whether `stop()` has been called on this session (shared across
clones).
- /// Backs `is_stopped`.
+ /// 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
@@ -183,6 +248,7 @@ 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(),
}
@@ -398,6 +464,7 @@ 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(),
}
@@ -1317,6 +1384,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.
+ ///
/// 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
/// terminated events of the queries still running, which the listeners
must still receive.
@@ -1326,7 +1400,14 @@ impl SparkSession {
/// Teardown does not wait for listener callbacks; the current event's
listener snapshot
/// may finish after stop returns, while no later event is dispatched.
pub fn stop(&self) -> Result<()> {
- if self.stopped.swap(true, Ordering::SeqCst) {
+ // 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 {
+ return Err(SparkError::connect_msg(
+ "the wait for the stop of the session on another thread was
interrupted",
+ ));
+ };
+ if self.stopped.load(Ordering::SeqCst) {
return Ok(());
}
let released = if self.client.is_closed() {
@@ -1338,13 +1419,15 @@ impl SparkSession {
// PySpark's `stop()`, which the exception of the signal
leaves before it closes
// the client, the session stays open, and a later `stop()`
releases it.
None => {
- self.stopped.store(false, Ordering::SeqCst);
return Err(SparkError::connect_msg(
"the release of the session was interrupted; the
session is still open",
));
}
}
};
+ // Before the listener bus is cancelled: an add of a listener that the
cancellation ends
+ // finds the session stopped.
+ self.stopped.store(true, Ordering::SeqCst);
self.streams().cancel_listener_bus();
// As PySpark's `stop()`, close the client even if server cleanup
fails, so its
// future requests raise `NO_ACTIVE_SESSION`.
@@ -1377,9 +1460,10 @@ impl SparkSession {
self.client.close();
}
- /// Whether `stop()` has been called on this session, or its client is
closed, as after a
- /// server-side session change. Mirrors
`pyspark.sql.connect.session.SparkSession.is_stopped`,
- /// which is the client's `is_closed`.
+ /// Whether this session was stopped by `stop()`, once its release ended,
or by `close()`, or
+ /// its client is closed, as after a server-side session change. Mirrors
+ /// `pyspark.sql.connect.session.SparkSession.is_stopped`, which is the
client's `is_closed`:
+ /// a session whose release is in flight is not stopped yet.
pub fn is_stopped(&self) -> bool {
self.stopped.load(Ordering::SeqCst) || self.client.is_closed()
}
@@ -1403,6 +1487,7 @@ 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),
}
@@ -3244,6 +3329,122 @@ mod tests {
}
}
+ /// A port that takes connections and never answers them, so an RPC to it
waits until the
+ /// connections close, when this drops.
+ struct UnansweringServer {
+ port: u16,
+ connections: Arc<Mutex<Vec<std::net::TcpStream>>>,
+ done: Arc<AtomicBool>,
+ }
+
+ impl UnansweringServer {
+ fn start() -> Self {
+ let listener =
std::net::TcpListener::bind("127.0.0.1:0").expect("a local port");
+ listener
+ .set_nonblocking(true)
+ .expect("a nonblocking listener");
+ let port = listener.local_addr().expect("the local
address").port();
+ let connections: Arc<Mutex<Vec<std::net::TcpStream>>> =
Arc::default();
+ let done = Arc::new(AtomicBool::new(false));
+ let (taken, ended) = (Arc::clone(&connections), Arc::clone(&done));
+ std::thread::spawn(move || {
+ while !ended.load(Ordering::SeqCst) {
+ match listener.accept() {
+ Ok((connection, _)) =>
taken.lock().unwrap().push(connection),
+ Err(_) =>
std::thread::sleep(std::time::Duration::from_millis(5)),
+ }
+ }
+ });
+ UnansweringServer {
+ port,
+ connections,
+ done,
+ }
+ }
+ }
+
+ impl Drop for UnansweringServer {
+ fn drop(&mut self) {
+ self.done.store(true, Ordering::SeqCst);
+ self.connections.lock().unwrap().clear();
+ }
+ }
+
+ /// As PySpark's `stop()`, which runs under `SparkSession._lock`: the
`stop()` of another
+ /// thread waits for the one in progress, and when a signal ends that one
(in the Python
+ /// client; here a watch that aborts its wait), it releases the session
itself. The session
+ /// is stopped once that release has ended, as PySpark's `is_stopped` is
the client's
+ /// `is_closed`, which its `stop()` sets after the release.
+ #[test]
+ fn
a_stop_that_waits_for_an_interrupted_stop_releases_the_session_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 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());
+ let spark = SparkSession::new(client);
+ 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 = spark.clone();
+ std::thread::spawn(move || {
+ let _ = first_ended.send(with_wait_watch(watch, ||
interrupted.stop()));
+ });
+ // The release of the first stop has connected, so that stop holds the
lock.
+ 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 = spark.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 returned while another one released the session"
+ );
+ 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 the session now; until that release ends,
it is not stopped.
+ assert!(matches!(
+ second.recv_timeout(Duration::from_millis(300)),
+ Err(RecvTimeoutError::Timeout)
+ ));
+ assert!(!spark.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!(spark.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 aa7a6d1a..bc4671c2 100644
--- a/crates/spark-connect/src/streaming.rs
+++ b/crates/spark-connect/src/streaming.rs
@@ -4,7 +4,7 @@
//! for building and executing streaming workloads.
use std::collections::HashMap;
-use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError, Weak};
+use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use uuid;
use spark_connect_core::error::{Result, SparkError, SparkErrorKind};
@@ -1011,7 +1011,19 @@ pub trait StreamingQueryListener: Send + Sync {
#[derive(Default)]
pub(crate) struct ListenerBus {
state: Mutex<ListenerBusState>,
- changed: Condvar,
+ changed: BusChanged,
+}
+
+/// The changes of the state of a listener bus, which wake its waits (see
[`ListenerBus::wait`])
+/// as the `notify_all` of a `Condvar` wakes those of the `Condvar`.
+#[derive(Default)]
+struct BusChanged(tokio::sync::Notify);
+
+impl BusChanged {
+ /// Wake the waits of the bus, which then check its state again.
+ fn notify_all(&self) {
+ self.0.notify_waiters();
+ }
}
/// The fields are of two groups, which one lock guards because a removal
reads them together:
@@ -1116,15 +1128,25 @@ impl ListenerBus {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
- /// Wait for a change of the state, releasing the lock meanwhile; as
[`lock`](Self::lock)
- /// for a poisoned lock.
+ /// Wait for a change of the state of the bus, with `state` unlocked
meanwhile, as the wait of
+ /// a `Condvar` does, and lock it again as [`lock`](Self::lock) does, for
a poisoned lock
+ /// too. As the acquire of the lock of PySpark's bus, which a signal of
the process
+ /// interrupts, the wait ends with an error when a signal ends it in the
Python client (see
+ ///
[`block_on_abortable`](spark_connect_core::runtime::block_on_abortable));
without that,
+ /// it waits for the change.
fn wait<'a>(
- &self,
+ &'a self,
state: MutexGuard<'a, ListenerBusState>,
- ) -> MutexGuard<'a, ListenerBusState> {
- self.changed
- .wait(state)
- .unwrap_or_else(PoisonError::into_inner)
+ ) -> Result<MutexGuard<'a, ListenerBusState>> {
+ // Made while the state is locked, so that the change that the caller
waits for wakes it.
+ 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",
+ ));
+ }
+ Ok(self.lock())
}
/// Clear only the registrations of the worker that has finished this
generation.
@@ -1347,6 +1369,8 @@ impl StreamingQueryManager {
/// Wait for another caller's start/stop operation without holding a lock
needed by
/// callbacks. A callback during shutdown may remove/close the bus as a
no-op, but
/// cannot wait for its own worker to finish in order to start a new
subscription.
+ /// A signal ends the wait in the Python client, as it interrupts the
acquire of the lock of
+ /// PySpark's bus, with an error and the bus unchanged.
fn idle_state(&self, removing: bool) -> Result<Option<MutexGuard<'_,
ListenerBusState>>> {
let mut state = self.bus.lock();
while state.phase != ListenerBusPhase::Idle {
@@ -1359,7 +1383,7 @@ impl StreamingQueryManager {
lifecycle operation is in progress",
));
}
- state = self.bus.wait(state);
+ state = self.bus.wait(state)?;
}
Ok(Some(state))
}
@@ -1416,7 +1440,11 @@ impl StreamingQueryManager {
return Err(error);
}
}
+ // Whether the stream that sends the ADD was opened: the server may
then hold its
+ // listener, whatever ends the wait for its acknowledgement.
+ let mut opened = false;
let stream = self.listener_event_stream().and_then(|mut stream| {
+ opened = true;
// Cancel a pending acknowledgement once the RPC stream exists.
Establishing
// the stream above still follows the transport's deadline and
retry policy.
stream.cancel = Some(receiver);
@@ -1466,6 +1494,13 @@ impl StreamingQueryManager {
}
}
Err(error) => {
+ // A wait for the acknowledgement that failed, by a transport
error or by a
+ // signal in the Python client, after the ADD was sent: the
server may have added
+ // its listener, and would answer the next ADD with no
response, so the next
+ // subscription removes it first. That REMOVE finds none at
worst.
+ if opened {
+ state.server_registration_held = true;
+ }
state.cancel.take();
Err(error)
}
@@ -1476,6 +1511,10 @@ impl StreamingQueryManager {
/// the server event stream before returning, as PySpark's removeListener
does.
/// A callback during another caller's shutdown returns without waiting
for its own
/// worker; that caller owns the final result and may retry a failed
removal.
+ /// In the Python client, a signal ends the waits of the removal for the
deliveries and the
+ /// lifecycle operations of other threads, as it interrupts the acquire of
the lock of
+ /// PySpark's bus: the removal then fails as if it had not started, so the
listener stays
+ /// registered.
pub fn remove_listener(&self, id: &str) -> Result<()> {
self.remove_listener_found(id).map(|_| ())
}
@@ -1524,7 +1563,25 @@ impl StreamingQueryManager {
.iter()
.any(|thread| *thread != current)
{
- state = self.bus.wait(state);
+ state = match self.bus.wait(state) {
+ Ok(state) => state,
+ Err(interrupted) => {
+ // As PySpark's removal, whose acquire of
the lock of the bus
+ // a signal interrupts before it removes
the listener: the
+ // listener stays, unless its subscription
ended meanwhile,
+ // when it is dropped without the lock.
+ let mut state = self.bus.lock();
+ if state.generation == generation &&
!state.listeners.is_empty()
+ {
+ let index =
index.min(state.listeners.len());
+ state.listeners.insert(index, removed);
+ } else {
+ drop(state);
+ drop_isolated([removed]);
+ }
+ return Err(interrupted);
+ }
+ };
}
}
drop(state);
@@ -1536,7 +1593,9 @@ impl StreamingQueryManager {
// 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.
+ // waiting, so the bus is checked again after it. A signal ends
the wait in the
+ // Python client, as it interrupts the acquire of the lock of
PySpark's bus, before
+ // anything is removed.
let current = std::thread::current().id();
if state.worker_id != Some(current)
&& state
@@ -1544,7 +1603,7 @@ impl StreamingQueryManager {
.iter()
.any(|thread| *thread != current)
{
- drop(self.bus.wait(state));
+ drop(self.bus.wait(state)?);
continue;
}
return self.stop_listener_bus(state);
@@ -2884,6 +2943,107 @@ mod tests {
assert_eq!(calls.load(Ordering::SeqCst), 0);
}
+ /// As PySpark's removal, whose acquire of the lock of the bus a signal
interrupts while
+ /// another thread holds it, to deliver a started event or to add a
listener: a watch that
+ /// aborts the wait of a removal (as a signal does in the Python client)
ends it with an
+ /// error, and leaves the bus as it was, which a later removal then
changes.
+ #[test]
+ fn an_interrupted_wait_of_a_removal_leaves_the_bus_as_it_was_as_pyspark() {
+ use spark_connect_core::runtime::{with_wait_watch, WaitWatch, Watch};
+ use std::sync::atomic::{AtomicBool, Ordering};
+ use std::sync::mpsc;
+ use std::time::Duration;
+
+ struct Listener;
+ impl StreamingQueryListener for Listener {
+ fn on_event(&self, _: &StreamingQueryListenerEvent) {}
+ }
+ /// Ends an add in progress, also when an assertion fails.
+ struct AddEnds<'a>(&'a StreamingQueryManager);
+ impl Drop for AddEnds<'_> {
+ fn drop(&mut self) {
+ self.0.bus.lock().phase = ListenerBusPhase::Idle;
+ self.0.bus.changed.notify_all();
+ }
+ }
+ let ids = |manager: &StreamingQueryManager| -> Vec<String> {
+ let state = manager.bus.lock();
+ state.listeners.iter().map(|(id, _)| id.clone()).collect()
+ };
+
+ // The removal of the last listener, and of one of two, waits for a
started event in
+ // delivery on another thread; a removal waits for an add of another
thread too.
+ for (registered, removed, add_in_progress) in [
+ (&["only"][..], "only", false),
+ (&["first", "second"][..], "first", false),
+ (&["only"][..], "only", true),
+ ] {
+ // No server: the REMOVE of the last listener fails at once, which
keeps it.
+ let spark = unreachable_session_without_retries();
+ let manager = spark.streams();
+ {
+ let mut state = manager.bus.lock();
+ for id in registered {
+ state.listeners.push((id.to_string(), Arc::new(Listener)));
+ }
+ if add_in_progress {
+ state.phase = ListenerBusPhase::Starting;
+ }
+ }
+ 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 dispatch = (!add_in_progress).then(||
manager.started_dispatch());
+ let (sent, removal) = mpsc::channel();
+ std::thread::scope(|scope| {
+ // End what the removal waits for even if an assertion fails,
so the scoped
+ // remover is released before the scope joins it.
+ let dispatch = dispatch;
+ let add = AddEnds(&manager);
+ let manager = &manager;
+ scope.spawn(move || {
+ let removal = with_wait_watch(watch, ||
manager.remove_listener_found(removed));
+ sent.send(removal).unwrap();
+ });
+ assert!(
+ matches!(
+ removal.recv_timeout(Duration::from_millis(300)),
+ Err(mpsc::RecvTimeoutError::Timeout)
+ ),
+ "the removal of {removed} of {registered:?} did not wait"
+ );
+ aborted.store(true, Ordering::SeqCst);
+ removal
+ .recv_timeout(Duration::from_secs(2))
+ .expect("the watch ends the wait of the removal")
+ .expect_err("the removal is interrupted");
+ assert_eq!(ids(manager), registered);
+ drop(dispatch);
+ drop(add);
+ });
+ let state = manager.bus.lock();
+ assert_eq!(state.phase, ListenerBusPhase::Idle);
+ assert!(state.started_dispatches.is_empty());
+ drop(state);
+ let removal = manager.remove_listener_found(removed);
+ if registered.len() > 1 {
+ assert!(removal.expect("a later removal of one of two
listeners"));
+ assert_eq!(ids(&manager), ["second"]);
+ } else {
+ removal.expect_err("no server removes the listener of the
server");
+ assert_eq!(ids(&manager), registered);
+ }
+ }
+ }
+
#[test]
fn stream_writer_partition_by() {
let spark = session();
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index d85e08a4..85cb7722 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -19229,6 +19229,163 @@ def
test_sigint_during_the_release_of_stop_raises_keyboard_interrupt_and_keeps_t
assert spark.is_stopped
+def
test_a_stop_that_waits_for_an_interrupted_stop_releases_the_session_as_pyspark(mock_connect):
+ # As PySpark's stop, which runs under SparkSession._lock: the stop of
another thread waits for
+ # the one in progress, and when a signal interrupts that one, it releases
and closes the
+ # session itself. The session is stopped only once that release has ended,
as PySpark's
+ # is_stopped is the client's is_closed, which its stop sets after the
release.
+ import signal
+ import threading
+
+ spark, service = mock_connect
+ service.release_session_blocked = True
+ outcome = {}
+
+ def stop():
+ try:
+ spark.stop()
+ outcome["stopped"] = spark.is_stopped
+ except BaseException as error:
+ outcome["error"] = error
+
+ other = threading.Thread(target=stop, daemon=True)
+
+ def stop_meanwhile_and_signal():
+ # The server holds the release of the first stop: the other stop waits
for it, and the
+ # signal interrupts the first one.
+ deadline = time.monotonic() + 5
+ while service.release_session_calls < 1 and time.monotonic() <
deadline:
+ time.sleep(0.01)
+ other.start()
+ time.sleep(0.3)
+ os.kill(os.getpid(), signal.SIGINT)
+
+ signaller = threading.Thread(target=stop_meanwhile_and_signal, daemon=True)
+ signaller.start()
+ try:
+ with pytest.raises(KeyboardInterrupt):
+ spark.stop()
+ signaller.join(5)
+ # The other stop releases the session, which the server holds again.
+ deadline = time.monotonic() + 5
+ while service.release_session_calls < 2 and time.monotonic() <
deadline:
+ time.sleep(0.01)
+ assert service.release_session_calls == 2
+ assert other.is_alive()
+ assert not spark.is_stopped
+ finally:
+ service.release_session_blocked = False
+ service.release_session_release()
+ other.join(5)
+ assert outcome == {"stopped": True}
+ assert spark.is_stopped
+
+
+def
test_a_stop_from_a_signal_handler_while_stop_releases_runs_within_it_as_pyspark(mock_connect):
+ # As PySpark's stop, whose SparkSession._lock is an RLock: a signal
handler that stops the
+ # session while the release of stop() waits runs its stop within the first
one, which it does
+ # not wait for. That stop releases the session too and closes it, then the
first one ends.
+ import signal
+ import threading
+
+ spark, service = mock_connect
+ service.release_session_blocked = True
+ seen = []
+
+ def handler(signum, frame):
+ seen.append(spark.is_stopped)
+ spark.stop()
+ seen.append(spark.is_stopped)
+
+ def signal_then_release():
+ deadline = time.monotonic() + 5
+ while service.release_session_calls < 1 and time.monotonic() <
deadline:
+ time.sleep(0.01)
+ os.kill(os.getpid(), signal.SIGINT)
+ # The server answers both releases once that of the handler's stop
arrives.
+ deadline = time.monotonic() + 3
+ while service.release_session_calls < 2 and time.monotonic() <
deadline:
+ time.sleep(0.01)
+ service.release_session_blocked = False
+ service.release_session_release()
+
+ previous = signal.signal(signal.SIGINT, handler)
+ signaller = threading.Thread(target=signal_then_release, daemon=True)
+ try:
+ signaller.start()
+ spark.stop()
+ finally:
+ signal.signal(signal.SIGINT, previous)
+ signaller.join(10)
+ assert seen == [False, True]
+ assert service.release_session_calls == 2
+ assert spark.is_stopped
+
+
+def
test_sigint_during_the_removal_of_the_last_listener_raises_keyboard_interrupt_as_pyspark(
+ mock_connect,
+):
+ # As PySpark's removeListener, whose wait for the lock of the listener
bus, which the delivery
+ # of a started event on another thread holds, a signal interrupts:
KeyboardInterrupt is raised
+ # at once, the listener stays registered, and a later removal removes it.
+ import signal
+ import threading
+
+ from pyspark.sql.streaming.listener import StreamingQueryListener
+
+ entered, release = threading.Event(), threading.Event()
+
+ class Blocking(StreamingQueryListener):
+ def onQueryStarted(self, event):
+ entered.set()
+ release.wait(5)
+
+ def onQueryProgress(self, event):
+ pass
+
+ def onQueryIdle(self, event):
+ pass
+
+ def onQueryTerminated(self, event):
+ pass
+
+ spark, service = mock_connect
+ service.listener_bus_enabled = True
+ # ExecutePlanResponse.write_stream_operation_start_result=8: query_id=1
(id=1, run_id=2),
+ # query_started_event_json=3.
+ service.execute_payload = message_field(8, message_field(
+ 1, message_field(1, "q") + message_field(2, "r")) + message_field(3,
json.dumps({
+ "id": "00000000-0000-4000-8000-000000000001",
+ "runId": "00000000-0000-4000-8000-000000000002",
+ "name": "query", "timestamp": "started", "jobTags": [],
+ })))
+ listener = Blocking()
+ spark.streams.addListener(listener)
+ starter = threading.Thread(
+ target=lambda:
spark.readStream.format("rate").load().writeStream.start(), daemon=True)
+ starter.start()
+ try:
+ assert entered.wait(5)
+ timer = threading.Timer(0.3, os.kill, (os.getpid(), signal.SIGINT))
+ started = time.monotonic()
+ timer.start()
+ try:
+ with pytest.raises(KeyboardInterrupt):
+ spark.streams.removeListener(listener)
+ finally:
+ timer.cancel()
+ assert time.monotonic() - started < 3
+ assert spark.streams._sqlb._listener_bus == [listener]
+ assert service.listener_removals == 0
+ finally:
+ release.set()
+ starter.join(5)
+ # The bus is usable: a removal removes the listener, and the listener of
the server.
+ spark.streams.removeListener(listener)
+ assert spark.streams._sqlb._listener_bus == []
+ assert service.wait_listener_removal(1)
+
+
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.
@@ -19442,6 +19599,56 @@ def
test_sigint_during_add_listener_keeps_the_registration_removable(mock_connec
assert service.listener_removals == 1
+def
test_a_second_sigint_during_add_listener_removes_the_server_listener_before_the_next_add(
+ mock_connect):
+ # A second signal ends the wait for the server's acknowledgement of
addListener, after the
+ # server added its listener. The server answers a later ADD of the session
with no response
+ # while it holds that listener, so the next addListener removes it first.
+ 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
+ # A wait that the signals do not end is released after 10 s, so the test
fails, not hangs.
+ release = threading.Timer(10, service.release_listener_registration)
+ timers = [threading.Timer(delay, os.kill, (os.getpid(), signal.SIGINT))
for delay in (0.5, 1.0)]
+ release.start()
+ for timer in timers:
+ timer.start()
+ try:
+ with pytest.raises(KeyboardInterrupt):
+ spark.streams.addListener(Listener())
+ finally:
+ for timer in timers:
+ timer.cancel()
+ release.cancel()
+ service.release_listener_registration()
+ assert service.wait_listener_registration(1)
+ assert service.listener_removals == 0
+ service.listener_register_blocked = False
+ listener = Listener()
+ spark.streams.addListener(listener)
+ assert service.listener_removals == 1
+ assert service.listener_subscriptions == 2
+ spark.streams.removeListener(listener)
+
+
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.
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index 8c9d4439..ced21483 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -693,18 +693,28 @@ def
test_ml_connect_setters_run_while_a_fit_or_an_evaluate_waits_as_pyspark(ml_m
}
-def
test_native_models_released_while_their_session_stops_send_no_delete(ml_mock):
- # As the release of a cached remote relation: a native model that goes
once its session is
- # stopped, here while its ReleaseSession waits for the server, sends no
Delete, since
- # stopping the session releases its ML cache on the server.
+def
test_native_models_released_while_their_session_stops_send_their_delete_as_pyspark(ml_mock):
+ # As PySpark's del_remote_cache, which deletes through the active session,
whose client is
+ # closed only once its ReleaseSession ends: a native model that goes while
that release waits
+ # for the server sends its Delete, and the session is not stopped yet. One
that goes once the
+ # session is stopped sends none: stopping the session released its ML
cache on the server.
import threading
import time
from pyspark.ml.connect import KMeans
+ def deleted():
+ # The IDs that the Deletes since the fits name. A Delete of a model
that an earlier test
+ # released can arrive meanwhile, so the models of this test have IDs
of their own.
+ return [ref.id for command in _commands(service)[sent:]
+ if command.ml_command.HasField("delete")
+ for ref in command.ml_command.delete.obj_refs]
+
spark, service = ml_mock
- service.execute_payload = _operator_info("model-1")
- model = KMeans(k=2).fit(spark.range(1))
+ service.execute_payload = _operator_info("model-released-while-stopping")
+ during = KMeans(k=2).fit(spark.range(1))
+ service.execute_payload = _operator_info("model-released-once-stopped")
+ after = KMeans(k=2).fit(spark.range(1))
sent = len(service.execute_requests)
service.release_session_blocked = True
stopper = threading.Thread(target=spark.stop)
@@ -714,16 +724,22 @@ def
test_native_models_released_while_their_session_stops_send_no_delete(ml_mock
while service.release_session_calls == 0 and time.time() < deadline:
time.sleep(0.01)
assert service.release_session_calls == 1
- del model
+ assert not spark.is_stopped
+ del during
gc.collect()
- # The release is sent without waiting for it: give one the time to
arrive.
- time.sleep(0.5)
- commands = _commands(service)[sent:]
- assert not [c for c in commands if c.ml_command.HasField("delete")]
+ # The release is sent without waiting for it.
+ deadline = time.time() + 5
+ while "model-released-while-stopping" not in deleted() and time.time()
< deadline:
+ time.sleep(0.05)
+ assert "model-released-while-stopping" in deleted()
finally:
service.release_session_release()
stopper.join(10)
assert spark.is_stopped
+ del after
+ gc.collect()
+ time.sleep(0.5)
+ assert "model-released-once-stopped" not in deleted()
@pytest.mark.parametrize(
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]