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 87e9a096 [SPARK-61532][CONNECT][PYTHON] Keep the listener of an add
that a signal ends before the server answers, and warn of a failed interrupt of
the listener bus, as PySpark does
87e9a096 is described below
commit 87e9a096b41ad7c5795689f9bd423408d67807c5
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 20:31:30 2026 +0900
[SPARK-61532][CONNECT][PYTHON] Keep the listener of an add that a signal
ends before the server answers, and warn of a failed interrupt of the listener
bus, as PySpark does
### What changes were proposed in this pull request?
Follow-ups from a review of #535 (SPARK-61470) and #552, on top of #558
(SPARK-61481 follow-up). The listener bus of the Python client still differed
from PySpark's in two cases of a signal.
1. **An add that a signal ends before the server answers.** This happens
before the server's response headers come: an unreachable or slow server, or
the plan compression lookup. #552 kept the listener only for a signal during
the wait for the acknowledgement, which comes after the headers. PySpark's
`append` puts the listener in the bus before it registers it (`query.py:289`).
- An add whose stream establishment ends with `wait_aborted` now keeps
the listener and its id too (`crates/spark-connect/src/streaming.rs`).
- It also marks the server's registration held, since the ADD may have
been sent, so the next removal or subscription removes it.
2. **A failed interrupt during the waits of `addListener`, `removeListener`
and `close`** was raised as `SparkConnectGrpcException`. PySpark raises the
interrupt's error out of its `except KeyboardInterrupt`, and then the `except
Exception` of `append` and `remove` catches it: they warn and return, and
`append` removes the listener from its bus.
- `interruptible_caught`, new in `crates/pyspark-rs/src/interrupt.rs`,
returns that error as the inner result. These three calls now warn "Failed to
add/remove the listener because of exception: ..." and return.
- `addListener` then drops the registration that the interrupted add
kept, with `StreamingQueryManager::discard_listener`, new and `#[doc(hidden)]`.
It leaves the server's listener for the next subscription to remove.
- `interruptible_outcome` is unchanged for its other callers, which do
not catch.
Not in this PR: PySpark's `remove` blocks on the lock that its
`post_to_all` holds while a callback runs. So a Ctrl-C during the removal of
the last listener while a callback runs sends no REMOVE in PySpark, while ours
sends it and then the interrupted join keeps the listener (#558). Making the
removal wait for the delivery first, as PySpark does, changes the drop-in's
deliberate ordering for listener lifecycle calls from a callback during an
external close. Seven cases of `test_strea [...]
### Why are the changes needed?
To match PySpark 4.3.0, from the review's probes against a gRPC stub:
- `addListener` held without headers, or to an unreachable server: PySpark
kept the listener (`[True]`), and ours dropped it.
- A failed Interrupt during `addListener` or `removeListener`: PySpark
warned and returned. Ours raised `SparkConnectGrpcException` (context
`KeyboardInterrupt`).
### Does this PR introduce _any_ user-facing change?
Yes, in the Python client:
- An add interrupted before the server answers leaves the listener
removable.
- A failed interrupt of these calls warns instead of raising.
### How was this patch tested?
New in `python/tests/test_dropin_offline.py`:
-
`test_sigint_during_an_add_listener_that_reaches_no_server_keeps_the_listener_as_pyspark`
(a subprocess, `sc://127.0.0.1:1`).
-
`test_a_failed_interrupt_during_add_listener_warns_and_drops_the_listener_as_pyspark`:
the warning, the listener not in the bus, and the next add removes the
server's listener first.
-
`test_a_failed_interrupt_during_remove_listener_warns_and_keeps_the_listener_as_pyspark`.
All three fail on master without this change. Also run:
- the listener SIGINT tests and
`test_streaming_listener_callback_lifecycle_calls_during_external_close` (18
passed);
- `cargo test -p apache-spark-connect --release --lib`;
- a trial of the earlier head with #560 and #562 on master: Rust e2e 967
passed, live 304 passed. Its only offline failures were the seven lifecycle
cases above, which came from the removal change that this head drops.
- `cargo build -p pyspark-rs --release`, `cargo fmt --all --check` and
`ruff check`.
### 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 #564 from HyukjinKwon/SPARK-61532-listener-ctrlc.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/interrupt.rs | 25 ++++++++
crates/pyspark-rs/src/streaming.rs | 33 ++++++----
crates/spark-connect/src/streaming.rs | 41 ++++++++++--
python/tests/test_dropin_offline.py | 114 ++++++++++++++++++++++++++++++++++
4 files changed, 195 insertions(+), 18 deletions(-)
diff --git a/crates/pyspark-rs/src/interrupt.rs
b/crates/pyspark-rs/src/interrupt.rs
index 46641eac..b1ee06f9 100644
--- a/crates/pyspark-rs/src/interrupt.rs
+++ b/crates/pyspark-rs/src/interrupt.rs
@@ -144,6 +144,28 @@ pub(crate) fn interruptible_outcome<T: Send, E: Send +
Into<Box<SparkError>>>(
py: Python<'_>,
session: &SparkSession,
f: impl FnOnce() -> Result<T, E> + Send,
+) -> PyResult<Result<T, Box<SparkError>>> {
+ run_interruptible(py, session, f, false)
+}
+
+/// As [`interruptible_outcome`], for a call that PySpark makes in a `try`
whose `except Exception`
+/// warns, as its listener bus does: the error of an interrupt that the server
failed, which
+/// replaces the KeyboardInterrupt of the signal, is caught there, so it is
the inner result too.
+pub(crate) fn interruptible_caught<T: Send, E: Send + Into<Box<SparkError>>>(
+ py: Python<'_>,
+ session: &SparkSession,
+ f: impl FnOnce() -> Result<T, E> + Send,
+) -> PyResult<Result<T, Box<SparkError>>> {
+ run_interruptible(py, session, f, true)
+}
+
+/// The wait of [`interruptible_outcome`], of whose results a failed interrupt
is the inner one
+/// when `catch_interrupt_failure`.
+fn run_interruptible<T: Send, E: Send + Into<Box<SparkError>>>(
+ py: Python<'_>,
+ session: &SparkSession,
+ f: impl FnOnce() -> Result<T, E> + Send,
+ catch_interrupt_failure: bool,
) -> PyResult<Result<T, Box<SparkError>>> {
let watch = Arc::new(SignalWatch {
session: session.clone(),
@@ -180,6 +202,9 @@ pub(crate) fn interruptible_outcome<T: Send, E: Send +
Into<Box<SparkError>>>(
// As PySpark's: the error of the interrupt replaces the
KeyboardInterrupt, which
// becomes its context, as `interrupt_operation` raises out of the
`except` clause.
if let Some(failure) = interrupt_failure {
+ if catch_interrupt_failure {
+ return Ok(Err(Box::new(failure)));
+ }
let failure =
crate::errors::spark_error_to_py_exception(failure);
return Err(crate::errors::with_context(py, failure, error));
}
diff --git a/crates/pyspark-rs/src/streaming.rs
b/crates/pyspark-rs/src/streaming.rs
index 14664aa6..f29ca539 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -13,7 +13,7 @@ use std::sync::Arc;
use crate::dataframe::{PyDataFrame, WriterState};
use crate::errors::spark_error_to_py_exception;
-use crate::interrupt::{interruptible, interruptible_outcome};
+use crate::interrupt::{interruptible, interruptible_caught};
use crate::options::{set_stream_option_skip_none,
set_stream_options_skip_none, DefaultedOption};
/// Adapts Python listeners to the native bus: deserialize one typed event for
the whole
@@ -1443,7 +1443,9 @@ impl PyStreamingQueryManager {
id: std::sync::OnceLock::new(),
});
let registration = Arc::clone(&adapter);
- match interruptible_outcome(py, &self.inner.spark_session(), || {
+ // As PySpark's append, whose `except Exception` also catches the
error of an interrupt
+ // that the server failed, which replaces the KeyboardInterrupt of a
signal.
+ match interruptible_caught(py, &self.inner.spark_session(), || {
self.inner
.add_listener(registration)
.map(|id| {
@@ -1455,14 +1457,21 @@ impl PyStreamingQueryManager {
.map_err(Box::new)
})? {
Ok(()) => Ok(()),
- Err(error) => warn(
- py,
- format!(
- "Failed to add the listener because of exception: {}\n\
- The listener is not added, please add it again.",
- spark_error_to_py_exception(*error).value(py)
- ),
- ),
+ Err(error) => {
+ // As PySpark's append, which then removes the listener from
its bus: the
+ // registration that an add that a signal ended keeps.
+ if let Some(id) = adapter.id.get() {
+ self.inner.discard_listener(id);
+ }
+ warn(
+ py,
+ format!(
+ "Failed to add the listener because of exception: {}\n\
+ The listener is not added, please add it again.",
+ spark_error_to_py_exception(*error).value(py)
+ ),
+ )
+ }
}
}
@@ -1510,7 +1519,7 @@ impl PyStreamingQueryManager {
let Some(id) = first else {
return Ok(());
};
- match interruptible_outcome(py, &self.inner.spark_session(), || {
+ match interruptible_caught(py, &self.inner.spark_session(), || {
self.inner.remove_listener_found(&id).map_err(Box::new)
})? {
// The bus is read again once this is tried: a call that
removed this
@@ -1544,7 +1553,7 @@ impl PyStreamingQueryManager {
/// `StreamingQueryManager.close`. A server removal failure warns and
keeps the
/// listeners registered, as PySpark Connect's does, so close can be
retried.
fn close(&self, py: Python<'_>) -> PyResult<()> {
- if let Err(error) = interruptible_outcome(py,
&self.inner.spark_session(), || {
+ if let Err(error) = interruptible_caught(py,
&self.inner.spark_session(), || {
self.inner.close().map_err(Box::new)
})? {
return warn(
diff --git a/crates/spark-connect/src/streaming.rs
b/crates/spark-connect/src/streaming.rs
index aa74f232..a278d8ca 100644
--- a/crates/spark-connect/src/streaming.rs
+++ b/crates/spark-connect/src/streaming.rs
@@ -1538,14 +1538,18 @@ impl StreamingQueryManager {
// 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 {
+ // subscription removes it first. That REMOVE finds none at
worst. A signal that
+ // ended the wait for the stream itself, before the server's
headers came, may
+ // have come after the ADD was sent too.
+ let aborted = !opened &&
spark_connect_core::client::is_wait_aborted(&error);
+ if opened || aborted {
state.server_registration_held = true;
}
- if interrupted {
- // As PySpark's append, a signal that ends the wait for
the acknowledgement
- // leaves the listener in the bus, and returns its id, so
a removal finds it.
- // The registration held above is removed by the next
removal or subscription.
+ if interrupted || aborted {
+ // As PySpark's append, which puts the listener in the bus
before it registers
+ // it, a signal that ends the registration leaves the
listener in the bus, and
+ // returns its id, so a removal finds it. The registration
held above is
+ // removed by the next removal or subscription.
state.listeners.push((id.clone(), listener));
state.cancel.take();
return Ok(id);
@@ -1745,6 +1749,31 @@ impl StreamingQueryManager {
.collect()
}
+ /// Drop the registration `id` from the bus without removing the server's
listener, as
+ /// PySpark's append drops a listener whose registration failed: for the
Python client, whose
+ /// add that a signal ended keeps its registration until the interrupt of
the signal fails.
+ /// The server may hold its listener, which the next subscription removes
first. Returns
+ /// whether the registration was there.
+ #[doc(hidden)]
+ pub fn discard_listener(&self, id: &str) -> bool {
+ let removed = {
+ let mut state = self.bus.lock();
+ let Some(index) = state
+ .listeners
+ .iter()
+ .position(|(listener_id, _)| listener_id == id)
+ else {
+ return false;
+ };
+ if state.listeners.len() == 1 {
+ state.server_registration_held = true;
+ }
+ state.listeners.remove(index)
+ };
+ drop_isolated([removed]);
+ true
+ }
+
/// Mark the calling thread as delivering a synchronous started event
until the returned
/// guard drops. Take it before the listener snapshot of the delivery.
fn started_dispatch(&self) -> StartedDispatch {
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 0a8fd960..aa9c1cbf 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -19969,6 +19969,120 @@ def
test_sigint_during_the_add_that_joins_a_failing_listener_worker_raises_keybo
warnings.showwarning = previous_showwarning
+def
test_sigint_during_an_add_listener_that_reaches_no_server_keeps_the_listener_as_pyspark():
+ # As PySpark's append, which puts the listener in its bus before it
registers it: a signal
+ # that ends the registration before the server answers, here a server that
cannot be
+ # reached, leaves the listener in the bus, as a signal during the wait for
the server's
+ # acknowledgement does.
+ import subprocess
+ import sys
+
+ code = """
+import os, signal, threading
+from pyspark.sql import SparkSession
+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 = SparkSession.builder.remote("sc://127.0.0.1:1").getOrCreate()
+listener = Listener()
+threading.Timer(1.0, lambda: os.kill(os.getpid(), signal.SIGINT)).start()
+try:
+ spark.streams.addListener(listener)
+ print("returned")
+except KeyboardInterrupt:
+ print("interrupted, in the bus:", spark.streams._sqlb._listener_bus ==
[listener])
+"""
+ result = subprocess.run(
+ [sys.executable, "-c", code], env=dict(os.environ, TZ="UTC"),
+ capture_output=True, text=True, timeout=60)
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.splitlines()[-1] == "interrupted, in the bus: True",
result.stdout
+
+
+def
test_a_failed_interrupt_during_add_listener_warns_and_drops_the_listener_as_pyspark(
+ mock_connect,
+):
+ # As PySpark's append, whose `except Exception` catches the error of an
interrupt that the
+ # server failed, which replaces the KeyboardInterrupt of the signal: the
add warns, returns,
+ # and removes the listener from the bus. The server may hold its listener,
which the next
+ # add removes first.
+ import signal
+ import threading
+ import warnings
+
+ spark, service = mock_connect
+ service.listener_bus_enabled = True
+ service.listener_register_blocked = True
+ service.interrupt_failure = ("INTERNAL", "interrupt failed on the server")
+ listener = _blocking_idle_listener(threading.Event(), threading.Event())
+ timer = threading.Timer(0.5, os.kill, (os.getpid(), signal.SIGINT))
+ started = time.monotonic()
+ timer.start()
+ try:
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ assert spark.streams.addListener(listener) is None
+ finally:
+ timer.cancel()
+ service.interrupt_failure = None
+ assert time.monotonic() - started < 3
+ messages = [str(w.message) for w in caught]
+ assert len(messages) == 1, messages
+ assert messages[0].startswith("Failed to add the listener because of
exception: ")
+ assert "interrupt failed on the server" in messages[0]
+ assert spark.streams._sqlb._listener_bus == []
+ service.release_listener_registration()
+ service.listener_register_blocked = False
+ spark.streams.addListener(listener)
+ assert service.listener_removals == 1
+ assert spark.streams._sqlb._listener_bus == [listener]
+ spark.streams.removeListener(listener)
+
+
+def
test_a_failed_interrupt_during_remove_listener_warns_and_keeps_the_listener_as_pyspark(
+ mock_connect,
+):
+ # As PySpark's remove, whose `except Exception` catches the error of an
interrupt of the
+ # REMOVE that the server failed, which replaces the KeyboardInterrupt of
the signal: the
+ # removal warns, returns, and the listener stays in the bus, to be removed
again.
+ import signal
+ import threading
+ import warnings
+
+ spark, service = mock_connect
+ service.listener_bus_enabled = True
+ listener = _blocking_idle_listener(threading.Event(), threading.Event())
+ spark.streams.addListener(listener)
+ service.listener_remove_blocked = True
+ service.interrupt_failure = ("INTERNAL", "interrupt failed on the server")
+ timer = threading.Timer(0.5, os.kill, (os.getpid(), signal.SIGINT))
+ started = time.monotonic()
+ timer.start()
+ try:
+ try:
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ assert spark.streams.removeListener(listener) is None
+ finally:
+ timer.cancel()
+ service.interrupt_failure = None
+ assert time.monotonic() - started < 3
+ messages = [str(w.message) for w in caught]
+ assert len(messages) == 1, messages
+ assert messages[0].startswith("Failed to remove the listener because
of exception: ")
+ assert "interrupt failed on the server" in messages[0]
+ assert spark.streams._sqlb._listener_bus == [listener]
+ finally:
+ # The held REMOVE then ends the server's stream, which may clear the
bus first.
+ service.listener_remove_blocked = False
+ service.release_listener_removal()
+ spark.streams.removeListener(listener)
+ assert spark.streams._sqlb._listener_bus == []
+
+
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]