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 e411ec60 [SPARK-61470][CONNECT][PYTHON][FOLLOWUP] Let a signal end the
wait of addListener for the server's acknowledgement, as PySpark does
e411ec60 is described below
commit e411ec608d819e8b787965e333c5abd1a830bc3c
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 17:00:14 2026 +0900
[SPARK-61470][CONNECT][PYTHON][FOLLOWUP] Let a signal end the wait of
addListener for the server's acknowledgement, as PySpark does
### What changes were proposed in this pull request?
A follow-up of #535 (SPARK-61470), from a review of it, on top of #539
(SPARK-61481). #535 says that in the Python client, Ctrl-C ends every call that
waits for the server. One wait did not end: `addListener`'s wait for the
server's acknowledgement of the listener's registration.
- `ListenerEventStream::message` (`crates/spark-connect/src/streaming.rs`)
read the response with `block_on`, and only the cancellation of the bus's
teardown ended that read. A signal did nothing until the server answered. The
read is now under `until_abort(ABORT_RETRIES)`, as the other reads of a wait
are. So the signal that a wait of the calling thread polls ends it at once, and
the stream is marked interrupted. The listener bus's worker and the event
iterator read with no signal wa [...]
- When a signal ends the acknowledgement wait, `add_listener` keeps the
listener in the bus, with its ID, and returns that ID. PySpark's `addListener`
appends the listener to its bus before it registers it with the server, so the
listener stays there after the `KeyboardInterrupt`. The Python client then
raises the `KeyboardInterrupt`, and a `removeListener` finds the listener. #539
already marks the server registration held when the acknowledgement wait fails,
so the next removal or s [...]
### Why are the changes needed?
To match PySpark 4.3.0. A probe with the repo's mock server holds the
registration of the listener for 15 seconds, and sends a SIGINT at 0.5 seconds:
```
PySpark 4.3.0 before
after
KeyboardInterrupt after the signal at 0.51 s 15.01 s
0.61 s
the listener in the bus afterwards yes no
yes
```
With the setup of the existing test, where the registration is answered at
2.5 seconds, the `KeyboardInterrupt` came at 2.5 seconds, when the server
answered, and now comes at the signal.
Two differences remain:
- After an interrupted `addListener(l1)`, PySpark appends a later
`addListener(l2)` without registering it, so neither listener gets events. This
client removes the server's listener and subscribes again with `l2`, and `l1`
leaves the bus.
- A concurrent `removeListener` of a listener whose add still waits does
not see it, as its ID is set when the add returns.
### Does this PR introduce _any_ user-facing change?
Yes, on unreleased changes. In the Python client, a Ctrl-C during
`addListener`'s wait for the server raises `KeyboardInterrupt` at once, instead
of when the server answers, and the listener stays registered, as in PySpark.
### How was this patch tested?
- `test_sigint_during_add_listener_keeps_the_registration_removable`
(`python/tests/test_dropin_offline.py`) now asserts that the
`KeyboardInterrupt` comes before the registration is answered at 2.5 seconds.
Before the change it came at 2.5 seconds.
-
`test_sigint_during_add_listener_with_the_acknowledgement_held_raises_at_once`,
new: the registration is not answered, the `KeyboardInterrupt` comes within 5
seconds, not at the mock's 15, the listener is in the bus, and a removal sends
one REMOVE. It failed without the change, at 15 seconds.
- #539's
`test_a_second_sigint_during_add_listener_removes_the_server_listener_before_the_next_add`
passes, unchanged.
- `cargo test -p apache-spark-connect --release --lib` (618 passed), `cargo
test -p apache-spark-connect -p apache-spark-connect-core --release --no-run`,
`cargo build -p pyspark-rs --release`, the offline drop-in and ML suites (2010
passed), the listener tests of `test_dropin_e2e.py` against a Spark 4.3.0
server, `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 #552 from HyukjinKwon/SPARK-61470-followup-listener-ack-signal.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/spark-connect/src/streaming.rs | 47 ++++++++++++++++++++++++++++------
python/tests/test_dropin_offline.py | 48 +++++++++++++++++++++++++++++++++--
2 files changed, 85 insertions(+), 10 deletions(-)
diff --git a/crates/spark-connect/src/streaming.rs
b/crates/spark-connect/src/streaming.rs
index bc4671c2..42d3ae6c 100644
--- a/crates/spark-connect/src/streaming.rs
+++ b/crates/spark-connect/src/streaming.rs
@@ -8,7 +8,7 @@ use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use uuid;
use spark_connect_core::error::{Result, SparkError, SparkErrorKind};
-use spark_connect_core::runtime::block_on;
+use spark_connect_core::runtime::{block_on, until_abort, ABORT_RETRIES};
use spark_connect_proto as proto;
use crate::dataframe::DataFrame;
@@ -799,39 +799,55 @@ pub struct ListenerEventStream {
buffered_events: std::vec::IntoIter<(i32, String)>,
done: bool,
cancel: Option<tokio::sync::oneshot::Receiver<()>>,
+ /// Whether a signal of the process ended a read, as it ends the
acknowledgement wait of
+ /// `add_listener`. The stream is then done, and the server is not awaited
for its cancellation.
+ interrupted: bool,
}
impl ListenerEventStream {
/// Read the next response unless canceled, checking cancellation before a
ready response.
/// Cancellation consumes its oneshot receiver and ends the stream like
EOF; once done,
- /// the transport is never polled again.
+ /// the transport is never polled again. A signal that a wait of this
thread polls ends the
+ /// read at once, as PySpark's wait for the acknowledgement does, and
marks the stream
+ /// interrupted. Only a wait of the caller reaches that: the reads of the
listener bus's
+ /// worker and of the iterator run with no signal watch.
fn message(&mut self) -> Result<Option<proto::ExecutePlanResponse>> {
if self.done {
return Ok(None);
}
+ // None: canceled. Some(None): interrupted by a signal.
Some(Some(..)): the read.
let response = block_on(async {
+ let read = until_abort(ABORT_RETRIES, self.stream.message());
if let Some(cancel) = &mut self.cancel {
tokio::select! {
biased;
_ = cancel => None,
- response = self.stream.message() => Some(response),
+ response = read => Some(response),
}
} else {
- Some(self.stream.message().await)
+ Some(read.await)
}
});
match response {
- None | Some(Ok(None)) => {
+ None | Some(Some(Ok(None))) => {
// A completed oneshot must never be polled again.
self.cancel.take();
self.done = true;
Ok(None)
}
- Some(Err(error)) => {
+ Some(None) => {
+ self.cancel.take();
+ self.done = true;
+ self.interrupted = true;
+ Err(SparkError::connect_msg(
+ "the wait for the streaming query listener acknowledgement
was interrupted",
+ ))
+ }
+ Some(Some(Err(error))) => {
self.done = true;
Err(error)
}
- Some(response) => response,
+ Some(Some(response)) => response,
}
}
@@ -1399,6 +1415,9 @@ impl StreamingQueryManager {
/// again to open a new subscription. Terminal teardown cancels
acknowledgement waits
/// once the RPC stream is established. Establishing the stream itself
follows the
/// transport's deadline and retry policy; a stopped session then reports
NO_ACTIVE_SESSION.
+ /// A signal of the process that a wait of this thread polls ends the
acknowledgement wait
+ /// at once: the listener then stays in the bus, with its id, and the
server's listener is
+ /// removed by the next removal, as PySpark's append leaves its listener
in the bus.
pub fn add_listener(&self, listener: Arc<dyn StreamingQueryListener>) ->
Result<String> {
let mut state = self.idle_state(false)?.expect("adding obtains the
state");
if self.session.is_stopped() {
@@ -1443,12 +1462,15 @@ impl StreamingQueryManager {
// 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 mut interrupted = 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);
- stream.wait_until_listener_added()?;
+ let acknowledged = stream.wait_until_listener_added();
+ interrupted = stream.interrupted;
+ acknowledged?;
Ok(stream)
});
let mut state = self.bus.lock();
@@ -1501,6 +1523,14 @@ impl StreamingQueryManager {
if opened {
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.
+ state.listeners.push((id.clone(), listener));
+ state.cancel.take();
+ return Ok(id);
+ }
state.cancel.take();
Err(error)
}
@@ -1930,6 +1960,7 @@ impl StreamingQueryManager {
stream: response_stream,
buffered_events: vec![].into_iter(),
done: false,
+ interrupted: false,
cancel: None,
})
}
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index dab7ba86..041dc9a5 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -19599,8 +19599,8 @@ def
test_sigint_during_stop_with_a_registered_listener_raises_at_once(mock_conne
def
test_sigint_during_add_listener_keeps_the_registration_removable(mock_connect):
# As PySpark's append: a signal that ends the wait for the server's
acknowledgement raises
- # KeyboardInterrupt, and the listener stays in the bus, while the server
still adds its
- # listener once it answers. A removeListener then removes that
registration.
+ # KeyboardInterrupt at once, and the listener stays in the bus, while the
server still adds
+ # its listener once it answers. A removeListener then removes that
registration.
import signal
import threading
@@ -19623,15 +19623,18 @@ def
test_sigint_during_add_listener_keeps_the_registration_removable(mock_connec
service.listener_bus_enabled = True
service.listener_register_blocked = True
listener = Listener()
+ # The release comes well after the signal: a wait that the signal does not
end lasts until it.
release = threading.Timer(2.5, service.release_listener_registration)
timer = threading.Timer(0.5, os.kill, (os.getpid(), signal.SIGINT))
release.start()
timer.start()
+ started = time.monotonic()
try:
with pytest.raises(KeyboardInterrupt):
spark.streams.addListener(listener)
finally:
timer.cancel()
+ assert time.monotonic() - started < 2
release.join(5)
assert service.wait_listener_registration(1)
assert spark.streams._sqlb._listener_bus == [listener]
@@ -19690,6 +19693,47 @@ def
test_a_second_sigint_during_add_listener_removes_the_server_listener_before_
spark.streams.removeListener(listener)
+def
test_sigint_during_add_listener_with_the_acknowledgement_held_raises_at_once(mock_connect):
+ # The server does not answer the registration for 15 seconds, while
PySpark raises
+ # KeyboardInterrupt at the signal: the wait for the acknowledgement ends
with the signal.
+ import signal
+ import threading
+
+ from pyspark.sql.streaming.listener import StreamingQueryListener
+
+ class Listener(StreamingQueryListener):
+ def onQueryStarted(self, event):
+ pass
+
+ def onQueryProgress(self, event):
+ pass
+
+ def onQueryIdle(self, event):
+ pass
+
+ def onQueryTerminated(self, event):
+ pass
+
+ spark, service = mock_connect
+ service.listener_bus_enabled = True
+ service.listener_register_blocked = True
+ listener = Listener()
+ timer = threading.Timer(0.5, os.kill, (os.getpid(), signal.SIGINT))
+ timer.start()
+ started = time.monotonic()
+ try:
+ with pytest.raises(KeyboardInterrupt):
+ spark.streams.addListener(listener)
+ finally:
+ timer.cancel()
+ assert time.monotonic() - started < 5
+ assert spark.streams._sqlb._listener_bus == [listener]
+ service.release_listener_registration()
+ spark.streams.removeListener(listener)
+ assert spark.streams._sqlb._listener_bus == []
+ assert service.listener_removals == 1
+
+
def
test_sigint_during_the_plan_compression_lookup_raises_keyboard_interrupt_at_once(mock_connect):
# As PySpark's: the Config lookup of the plan compression of the first
plan is a blocked call
# with no execution in flight, which a signal ends at once, so no
execution is started.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]