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 5e018c5d [SPARK-61353][CONNECT][PYTHON] Raise KeyboardInterrupt
promptly on SIGINT during SparkSession.stop and the native KMeans fit, in the
Python client as PySpark does
5e018c5d is described below
commit 5e018c5db52f4c09b27511192bd2fcc93b8ed90b
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 16:47:17 2026 +0900
[SPARK-61353][CONNECT][PYTHON] Raise KeyboardInterrupt promptly on SIGINT
during SparkSession.stop and the native KMeans fit, in the Python client as
PySpark does
### What changes were proposed in this pull request?
[SPARK-61353](https://issues.apache.org/jira/browse/SPARK-61353): Raise
`KeyboardInterrupt` promptly on SIGINT during `SparkSession.stop()` and the
native KMeans fit, in the Python client as PySpark does. This is a follow-up of
SPARK-61259 (#455).
- `crates/spark-connect-core/src/runtime.rs`: a new `Watch::Abort`, and
`block_on_abortable`, a `block_on` whose wait ends at once with `None` when its
watch returns `Watch::Abort`; the future is dropped, unfinished. Any other wait
treats `Watch::Abort` as `Watch::Continue`, so the waits of SPARK-61259 are
unchanged.
- `crates/pyspark-rs/src/interrupt.rs`: when a signal handler raises and no
execution is in flight to interrupt on the server, the signal watch returns
`Watch::Abort` (it returned `Watch::Continue`).
- `crates/spark-connect/src/session.rs`: `SparkSession::stop` waits for the
release of the session with `block_on_abortable`. An interrupted release leaves
the session open (not stopped, client not closed), as PySpark's `stop()` does
when the exception of the signal leaves it, so a later `stop()` releases it.
- `crates/pyspark-rs/src/session.rs`: `stop()` runs the release first,
through `interruptible_outcome`, so the exception of the signal is raised
before anything of the session is torn down.
- `crates/pyspark-rs/src/ml.rs`: the fit of the native KMeans of
SPARK-61229, which merged after SPARK-61259 was written, waits through
`interruptible`, as the other native fits do.
### Why are the changes needed?
- `stop()` waits for the release of the session and for its retries.
Against an unreachable server that is about 10 minutes with the default retry
policy (since SPARK-61319), and a SIGINT did not end it: the release has no
execution on the server to interrupt, so the wait of SPARK-61259 kept waiting
until the release ended. PySpark's `stop()` raises `KeyboardInterrupt` at once
from its sleep between the retries.
- The native `KMeans().fit(df)` waited without polling the signals, unlike
the other native fits.
### Does this PR introduce _any_ user-facing change?
Yes. A SIGINT during `SparkSession.stop()` raises `KeyboardInterrupt` at
once and leaves the session open, as PySpark does, and a SIGINT during a native
KMeans fit raises it and interrupts the fit on the server, as for the other
fits. Nothing changes without a signal.
### How was this patch tested?
-
`runtime::tests::test_an_abortable_wait_ends_when_its_watch_aborts_and_another_keeps_waiting`
(offline, placed before `test_with_wait_watch_restores_the_enclosing_watch`):
an abortable wait ends with `None` when its watch aborts, and gives the output
of its future otherwise; a `block_on` wait keeps waiting for its future
whatever the watch returns.
-
`test_sigint_during_the_release_of_stop_raises_keyboard_interrupt_and_keeps_the_session`
(mock server holding the release, placed before
`test_exception_of_a_signal_handler_is_raised_by_collect_as_pyspark`): `stop()`
raises `KeyboardInterrupt` within 3 s of a SIGINT, `is_stopped` is false, and a
later `stop()` stops the session.
- `test_sigint_during_a_native_kmeans_fit_raises_keyboard_interrupt` (mock
server holding the execution, same place): the fit raises `KeyboardInterrupt`
within 3 s, and one `Interrupt` of its operation is sent.
- The lib tests of both crates (723 passed), the build of all tests, also
with `wasm-udf`, with no warnings, the offline Python suites (2993 passed, 8
skipped) with the rebuilt extension, and the live drop-in and Arrow suites (259
passed) and live cases (15 passed) against a local Spark 4.3.0 server. Clippy
reports no diagnostics in the changed lines.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5
This pull request and its description were written by Isaac.
Closes #457 from HyukjinKwon/SPARK-61353-interruptible-stop.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/interrupt.rs | 6 ++-
crates/pyspark-rs/src/ml.rs | 6 +--
crates/pyspark-rs/src/session.rs | 11 +++--
crates/spark-connect-core/src/runtime.rs | 78 ++++++++++++++++++++++++++++++++
crates/spark-connect/src/session.rs | 13 +++++-
python/tests/test_dropin_offline.py | 49 ++++++++++++++++++++
6 files changed, 154 insertions(+), 9 deletions(-)
diff --git a/crates/pyspark-rs/src/interrupt.rs
b/crates/pyspark-rs/src/interrupt.rs
index 114f3e14..fd34cdf2 100644
--- a/crates/pyspark-rs/src/interrupt.rs
+++ b/crates/pyspark-rs/src/interrupt.rs
@@ -44,7 +44,9 @@ impl SignalWatch {
let _ =
session.interrupt_operation_async(&operation_id).await;
}))
}
- None => Watch::Continue,
+ // No execution to interrupt: a wait that can end before its
future, such as the
+ // release of `stop()`, ends now; another keeps waiting.
+ None => Watch::Abort,
}
}
}
@@ -56,7 +58,7 @@ impl SignalWatch {
///
/// The execution is interrupted only when `f` has started one; a request that
is still waiting
/// for its response (such as an analysis) ends when the response arrives, and
the exception is
-/// raised then.
+/// raised then. A wait of `block_on_abortable` (the release of `stop()`) ends
at once instead.
pub(crate) fn interruptible<T: Send, E: Send + Into<Box<SparkError>>>(
py: Python<'_>,
session: &SparkSession,
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 312a2f19..08651bfd 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -674,9 +674,9 @@ impl PyKMeans {
fn fit(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<PyMLModel> {
let mut estimator = self.inner.clone();
- let model = py
- .detach(|| estimator.fit(&df.dataframe).map_err(Box::new))
- .to_pyerr()?;
+ let model = interruptible(py, &df.dataframe.spark_session(), || {
+ estimator.fit(&df.dataframe).map_err(Box::new)
+ })?;
Ok(PyMLModel { model })
}
}
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index 8ab0032c..f3bc44e6 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -2436,18 +2436,23 @@ impl PySparkSession {
/// active session and the cached `SQLContext` if they belong to this
session. Listener
/// callbacks are not joined; the current event's listener snapshot may
finish afterward.
fn stop(&self, py: Python<'_>) -> PyResult<()> {
- crate::progress::forget_session(&self.session);
- crate::profiler::forget_session(&self.session);
let released = if self
.release_session_on_close
.load(std::sync::atomic::Ordering::SeqCst)
{
- py.detach(|| self.session.stop().map_err(Box::new))
+ // 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.
+ 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.
py.detach(|| self.session.close());
Ok(())
};
+ crate::progress::forget_session(&self.session);
+ crate::profiler::forget_session(&self.session);
if let Err(e) = released {
let logger = py
.import("logging")?
diff --git a/crates/spark-connect-core/src/runtime.rs
b/crates/spark-connect-core/src/runtime.rs
index d1ec1fae..860b7c4a 100644
--- a/crates/spark-connect-core/src/runtime.rs
+++ b/crates/spark-connect-core/src/runtime.rs
@@ -64,6 +64,10 @@ pub enum Watch {
/// Interrupt the execution that the wait is for, by this future, which
the wait drives to its
/// end. The wait then ends with the server's cancellation of the
execution.
Interrupt(Pin<Box<dyn Future<Output = ()> + Send>>),
+ /// Stop waiting, when no execution is in flight to interrupt. A wait of
+ /// [`block_on_abortable`] ends at once, without the output of its future;
any other wait
+ /// keeps waiting, as for [`Watch::Continue`].
+ Abort,
}
/// The poll of the signals of the process of a wait, which the wait calls
every
@@ -96,6 +100,54 @@ pub fn with_wait_watch<R>(watch: Arc<WaitWatch>, f: impl
FnOnce() -> R) -> R {
/// How often a wait for the server polls its [`WaitWatch`].
pub const POLL_INTERVAL: std::time::Duration =
std::time::Duration::from_millis(200);
+/// As [`block_on`], but the wait ends at once, with `None`, when the
[`WaitWatch`] of the thread
+/// returns [`Watch::Abort`]: the future is dropped, unfinished. For a wait
that nothing on the
+/// server stands behind, such as the retries of a session release, which a
signal of the
+/// process stops as it stops PySpark's sleep between the retries.
+pub fn block_on_abortable<F>(f: F) -> Option<F::Output>
+where
+ F: std::future::Future + Send,
+ F::Output: Send,
+{
+ let watch = WAIT_WATCH.with(|watch| watch.borrow().clone());
+ let drive = |f: F| match watch {
+ Some(watch) => get_runtime().block_on(watched_abortable(f, watch)),
+ None => Some(get_runtime().block_on(f)),
+ };
+ match tokio::runtime::Handle::try_current() {
+ Ok(handle) if handle.runtime_flavor() ==
tokio::runtime::RuntimeFlavor::MultiThread => {
+ tokio::task::block_in_place(|| drive(f))
+ }
+ // The wait runs on another thread, which does not poll the watch (see
`block_on`).
+ Ok(_) => Some(block_on_other_thread(f)),
+ _ => drive(f),
+ }
+}
+
+/// `f`, polled as it is, and `watch` called every [`POLL_INTERVAL`]: `None`
at once when it
+/// returns [`Watch::Abort`], else the output of `f`. An interrupt is spawned
once and awaited
+/// with `f`, as in [`watched`].
+async fn watched_abortable<F: Future>(f: F, watch: Arc<WaitWatch>) ->
Option<F::Output> {
+ tokio::pin!(f);
+ let mut ticks = tokio::time::interval(POLL_INTERVAL);
+ let mut interrupt: Option<tokio::task::JoinHandle<()>> = None;
+ loop {
+ tokio::select! {
+ output = &mut f => {
+ if let Some(interrupt) = interrupt {
+ let _ = interrupt.await;
+ }
+ return Some(output);
+ }
+ _ = ticks.tick(), if interrupt.is_none() => match watch() {
+ Watch::Abort => return None,
+ Watch::Interrupt(sent) => interrupt = Some(tokio::spawn(sent)),
+ Watch::Continue => {}
+ },
+ }
+ }
+}
+
/// Drive `f` on the shared runtime, polling `watch` (if any) as the wait goes
on.
fn drive<F: Future>(f: F, watch: Option<Arc<WaitWatch>>) -> F::Output {
match watch {
@@ -326,6 +378,32 @@ mod tests {
assert!(interrupted.load(Ordering::SeqCst));
}
+ #[test]
+ fn
test_an_abortable_wait_ends_when_its_watch_aborts_and_another_keeps_waiting() {
+ // A watch that aborts ends an abortable wait at once, without the
output of its future.
+ let aborted = with_wait_watch(Arc::new(|| Watch::Abort), || {
+ block_on_abortable(std::future::pending::<u8>())
+ });
+ assert_eq!(aborted, None);
+ // Without an abort, an abortable wait gives the output of its future.
+ let ended = with_wait_watch(Arc::new(|| Watch::Continue), || {
+ block_on_abortable(async {
+ tokio::time::sleep(POLL_INTERVAL * 2).await;
+ 7
+ })
+ });
+ assert_eq!(ended, Some(7));
+ assert_eq!(block_on_abortable(async { 8 }), Some(8));
+ // Any other wait keeps waiting for its future, whatever the watch
returns.
+ let waited = with_wait_watch(Arc::new(|| Watch::Abort), || {
+ block_on(async {
+ tokio::time::sleep(POLL_INTERVAL * 2).await;
+ 9
+ })
+ });
+ assert_eq!(waited, 9);
+ }
+
#[test]
fn test_with_wait_watch_restores_the_enclosing_watch() {
let outer: Arc<WaitWatch> = Arc::new(|| Watch::Continue);
diff --git a/crates/spark-connect/src/session.rs
b/crates/spark-connect/src/session.rs
index aeb95946..e4489786 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -1273,7 +1273,18 @@ impl SparkSession {
let released = if self.client.is_closed() {
Ok(())
} else {
- block_on(self.client.release_session())
+ match
spark_connect_core::runtime::block_on_abortable(self.client.release_session()) {
+ Some(released) => released,
+ // The wait was stopped, by a signal of the process in the
Python client: as
+ // 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",
+ ));
+ }
+ }
};
self.streams().cancel_listener_bus();
// As PySpark's `stop()`, close the client even if server cleanup
fails, so its
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index da487539..bc3f6363 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -16213,6 +16213,55 @@ def
test_sigint_while_the_transport_waits_raises_keyboard_interrupt(mock_connect
assert time.monotonic() - started < 3
+def
test_sigint_during_the_release_of_stop_raises_keyboard_interrupt_and_keeps_the_session(
+ mock_connect,
+):
+ # As PySpark's stop, whose wait for the release of the session (and the
sleeps between its
+ # retries) a signal interrupts: KeyboardInterrupt is raised at once, it
leaves the session
+ # open, and a later stop releases it.
+ import signal
+ import threading
+
+ spark, service = mock_connect
+ service.release_session_blocked = True
+ timer = threading.Timer(0.3, os.kill, (os.getpid(), signal.SIGINT))
+ started = time.monotonic()
+ timer.start()
+ try:
+ with pytest.raises(KeyboardInterrupt):
+ spark.stop()
+ finally:
+ timer.cancel()
+ assert time.monotonic() - started < 3
+ assert not spark.is_stopped
+ service.release_session_blocked = False
+ service.release_session_release()
+ spark.stop()
+ assert spark.is_stopped
+
+
+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.
+ import signal
+ import threading
+
+ from pyspark.ml.connect.clustering import KMeans
+
+ spark, service = mock_connect
+ service.block_execute = True
+ timer = threading.Timer(0.3, os.kill, (os.getpid(), signal.SIGINT))
+ started = time.monotonic()
+ timer.start()
+ try:
+ with pytest.raises(KeyboardInterrupt):
+ KMeans(k=2).fit(spark.range(3))
+ finally:
+ timer.cancel()
+ assert time.monotonic() - started < 3
+ assert len(service.interrupt_requests) == 1
+
+
def
test_exception_of_a_signal_handler_is_raised_by_collect_as_pyspark(mock_connect):
# As PySpark's: an exception that the handler of the signal raises is the
one that the
# waiting call raises, and the operation is interrupted.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]