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 cefa44df [SPARK-61208][CONNECT][FOLLOWUP] Make a removal wait for the
synchronous started event in delivery, in the Rust and Python clients as
PySpark does
cefa44df is described below
commit cefa44dfbab471bdad7ed266740f6a8ac33f08b4
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Mon Nov 9 17:32:28 2026 +0900
[SPARK-61208][CONNECT][FOLLOWUP] Make a removal wait for the synchronous
started event in delivery, in the Rust and Python clients as PySpark does
### What changes were proposed in this pull request?
[SPARK-61208](https://issues.apache.org/jira/browse/SPARK-61208): make a
removal of a non-last listener wait for the synchronous started event in
delivery, as PySpark does.
`start()` and `toTable()` deliver the query-started event to the listeners
on the calling thread before they return. The asynchronous event loop already
marked its delivery, so `removeListener` from another thread waited for it. The
synchronous started delivery was not marked, so such a removal returned at
once, and the removed listener still received the started event afterwards.
This change:
- Marks the started delivery of `start`/`toTable` as in progress (a
per-delivery guard recording the delivering thread), taken before the listener
snapshot is read, in the Rust core (`DataStreamWriter::_start_internal`).
- A removal of a non-last listener from another thread waits until that
delivery finishes. A removal from the delivering thread itself (a callback
removing a listener) does not wait, so it cannot deadlock.
Official PySpark 4.3.0 holds the listener bus lock for the started event as
well, so its `removeListener` waits and the removed listener has the event
before the call returns. Reproduced with a started callback that sleeps 1 s on
one listener, while another thread removes the second listener at 0.3 s: before
this change the removal returned at 0.31 s with no started event for the
removed listener, and that listener got the event at 1.01 s; now it returns at
1.01 s, after the event, as [...]
### Why are the changes needed?
A removal from another thread could return while a started callback was
still running, and the removed listener then received the started event after
`removeListener` returned. This breaks the guarantee that a removed listener
gets no more events, which the asynchronous path already provides.
### Does this PR introduce _any_ user-facing change?
Yes. `removeListener` (and the Rust `remove_listener`) of a non-last
listener from another thread now waits for a query-started event that
`start()`/`toTable()` is delivering to finish. A removal from inside that
callback does not wait.
### How was this patch tested?
-
`test_streaming_listener_start_removal_waits_for_the_started_event_in_delivery`
(Python, mock service, ordered by events and gates): a removal from another
thread waits for the started event in delivery and the removed listener
receives it before the removal returns; a removal from the started callback
returns without waiting. The first part fails without this change and passes
with it.
-
`nonlast_removal_waits_for_a_started_event_in_delivery_from_another_thread` and
`nonlast_removal_from_the_started_event_thread_does_not_wait_for_itself` (Rust
unit tests).
- A live check against a Spark Connect server with a native Rust listener
and `start()` gave the same ordering (the removal waited for the started event
to reach both listeners).
- The same start-removal case matches official PySpark 4.3.0 in timing and
delivery.
- The lib tests of both crates (660 passed), the build of all tests, also
with `wasm-udf`, the offline Python suites (2808 passed, 8 skipped), and the
live drop-in and Arrow suites (224 passed) and live cases (13 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 #410 from HyukjinKwon/SPARK-61208-fu-p8.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/spark-connect/src/streaming.rs | 146 ++++++++++++++++++++++++++++++-
python/tests/streaming_listener_cases.py | 85 ++++++++++++++++++
2 files changed, 228 insertions(+), 3 deletions(-)
diff --git a/crates/spark-connect/src/streaming.rs
b/crates/spark-connect/src/streaming.rs
index 67e7dfb6..49fc586f 100644
--- a/crates/spark-connect/src/streaming.rs
+++ b/crates/spark-connect/src/streaming.rs
@@ -520,8 +520,12 @@ impl DataStreamWriter {
// with the result of its start, as the session has client-side
listeners, and the client
// posts it to them before it gives back the query.
if let Some(event_json) = started_event {
+ let manager = self.session.streams();
+ // Mark the delivery before its listener snapshot is taken, so
that a removal
+ // from another thread waits for it, as PySpark's bus holds its
lock for it.
+ let _dispatch = manager.started_dispatch();
on_started(
- &self.session.streams(),
+ &manager,
&StreamingQueryListenerEvent {
event_type: QUERY_STARTED_EVENT,
event_json,
@@ -1002,6 +1006,29 @@ struct ListenerBusState {
/// failure, to its snapshot of the listeners. PySpark's bus holds its
lock during
/// delivery, so a removal from another thread waits for it.
dispatching: Option<u64>,
+ /// The threads delivering a synchronous started event in
`start`/`toTable`, one entry
+ /// per delivery. As with `dispatching`, a removal from another thread
waits for them.
+ started_dispatches: Vec<std::thread::ThreadId>,
+}
+
+/// A synchronous started event in delivery by the calling thread of
`start`/`toTable`.
+struct StartedDispatch {
+ bus: Arc<ListenerBus>,
+ thread: std::thread::ThreadId,
+}
+
+impl Drop for StartedDispatch {
+ fn drop(&mut self) {
+ let mut state = self.bus.state.lock().unwrap();
+ if let Some(index) = state
+ .started_dispatches
+ .iter()
+ .rposition(|thread| *thread == self.thread)
+ {
+ state.started_dispatches.remove(index);
+ }
+ self.bus.changed.notify_all();
+ }
}
/// An event delivery or terminal failure notification by the worker of
`generation`.
@@ -1270,9 +1297,15 @@ impl StreamingQueryManager {
// including the removed listener, to finish. This also covers
a
// terminal error notification. A callback of the bus does not
wait,
// as it would wait for its own delivery.
- if state.worker_id != Some(std::thread::current().id()) {
+ let current = std::thread::current().id();
+ if state.worker_id != Some(current) {
let generation = state.generation;
- while state.dispatching == Some(generation) {
+ while state.dispatching == Some(generation)
+ || state
+ .started_dispatches
+ .iter()
+ .any(|thread| *thread != current)
+ {
state = self.bus.changed.wait(state).unwrap();
}
}
@@ -1332,6 +1365,22 @@ impl StreamingQueryManager {
.collect()
}
+ /// 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 {
+ let thread = std::thread::current().id();
+ self.bus
+ .state
+ .lock()
+ .unwrap()
+ .started_dispatches
+ .push(thread);
+ StartedDispatch {
+ bus: Arc::clone(&self.bus),
+ thread,
+ }
+ }
+
/// Post `event` to the client-side listeners of the session.
pub(crate) fn post_to_all(&self, event: &StreamingQueryListenerEvent) {
self.bus.post_to_all(event);
@@ -2329,4 +2378,95 @@ mod tests {
assert!(!streams.remove_listener_found("no-such-id").unwrap());
streams.remove_listener("no-such-id").unwrap();
}
+
+ #[test]
+ fn
nonlast_removal_waits_for_a_started_event_in_delivery_from_another_thread() {
+ use std::sync::mpsc;
+ use std::time::{Duration, Instant};
+
+ struct Listener;
+ impl StreamingQueryListener for Listener {
+ fn on_event(&self, _: &StreamingQueryListenerEvent) {}
+ }
+
+ let spark = session();
+ let manager = spark.streams();
+ {
+ let mut state = manager.bus.state.lock().unwrap();
+ state
+ .listeners
+ .push(("first".to_string(), Arc::new(Listener)));
+ state
+ .listeners
+ .push(("second".to_string(), Arc::new(Listener)));
+ }
+ let dispatch = manager.started_dispatch();
+ let (removed, removal) = mpsc::channel();
+ std::thread::scope(|scope| {
+ // Drop the delivery guard even if an assertion fails, so the
scoped remover
+ // is released before the scope joins it.
+ let dispatch = dispatch;
+ let manager = &manager;
+ scope.spawn(move || {
+ assert!(manager.remove_listener_found("second").unwrap());
+ removed.send(()).unwrap();
+ });
+ let deadline = Instant::now() + Duration::from_secs(5);
+ loop {
+ if manager.bus.state.lock().unwrap().listeners.len() == 1 {
+ break;
+ }
+ assert!(Instant::now() < deadline, "remover did not reach the
bus");
+ std::thread::yield_now();
+ }
+ assert!(matches!(
+ removal.recv_timeout(Duration::from_millis(100)),
+ Err(mpsc::RecvTimeoutError::Timeout)
+ ));
+ drop(dispatch);
+ removal
+ .recv_timeout(Duration::from_secs(5))
+ .expect("removal finishes once the started event is
delivered");
+ });
+ let state = manager.bus.state.lock().unwrap();
+ assert!(state.started_dispatches.is_empty());
+ assert_eq!(state.listeners.len(), 1);
+ }
+
+ #[test]
+ fn
nonlast_removal_from_the_started_event_thread_does_not_wait_for_itself() {
+ use std::sync::mpsc;
+ use std::time::Duration;
+
+ struct Listener;
+ impl StreamingQueryListener for Listener {
+ fn on_event(&self, _: &StreamingQueryListenerEvent) {}
+ }
+
+ let spark = session();
+ {
+ let bus = spark.listener_bus();
+ let mut state = bus.state.lock().unwrap();
+ state
+ .listeners
+ .push(("first".to_string(), Arc::new(Listener)));
+ state
+ .listeners
+ .push(("second".to_string(), Arc::new(Listener)));
+ }
+ let (result, returned) = mpsc::channel();
+ // The delivery and its callback removal run on one thread; a
self-wait would hang.
+ std::thread::spawn(move || {
+ let manager = spark.streams();
+ let _dispatch = manager.started_dispatch();
+ result
+ .send(manager.remove_listener_found("second"))
+ .unwrap();
+ });
+ let removed = returned
+ .recv_timeout(Duration::from_secs(5))
+ .expect("a removal from its own started event does not wait for
itself")
+ .unwrap();
+ assert!(removed);
+ }
}
diff --git a/python/tests/streaming_listener_cases.py
b/python/tests/streaming_listener_cases.py
index 0daf541a..19569ddd 100644
--- a/python/tests/streaming_listener_cases.py
+++ b/python/tests/streaming_listener_cases.py
@@ -632,6 +632,91 @@ class TestStreamingListenerLifecycle:
assert service.release_session_calls == 0
+ def
test_streaming_listener_start_removal_waits_for_the_started_event_in_delivery(
+ self, mock_connect,
+ ):
+ # As PySpark's bus, whose delivery of the started event of start()
holds the lock of
+ # its removal: a listener removed by another thread gets that event
before
+ # removeListener returns. A removal from the callback that receives
the event does
+ # not wait for its own delivery.
+ spark, service = mock_connect
+ service.listener_bus_enabled = True
+ service.execute_payload = start_response(json.dumps({
+ "id": "00000000-0000-4000-8000-000000000001",
+ "runId": "00000000-0000-4000-8000-000000000002",
+ "name": "query", "timestamp": "started", "jobTags": [],
+ }))
+ order = []
+ outcome = {}
+ entered, release = threading.Event(), threading.Event()
+
+ class Blocking(IdleListener):
+ def onQueryStarted(self, event):
+ order.append("first started")
+ entered.set()
+ assert release.wait(5)
+
+ class Recording(IdleListener):
+ def onQueryStarted(self, event):
+ order.append("second started")
+
+ def start_query():
+ try:
+ outcome["query"] =
spark.readStream.format("rate").load().writeStream.start()
+ except BaseException as error:
+ outcome["error"] = error
+
+ def remove(listener):
+ spark.streams.removeListener(listener)
+ order.append("removed")
+
+ first, second = Blocking(), Recording()
+ try:
+ spark.streams.addListener(first)
+ spark.streams.addListener(second)
+ starter = threading.Thread(target=start_query, daemon=True)
+ starter.start()
+ assert entered.wait(5)
+ removal = threading.Thread(target=remove, args=(second,),
daemon=True)
+ removal.start()
+ # The started event is in delivery to the first listener, so the
removal waits.
+ removal.join(0.5)
+ assert removal.is_alive()
+ release.set()
+ removal.join(5)
+ starter.join(5)
+ assert not removal.is_alive() and not starter.is_alive()
+ assert "error" not in outcome
+ assert order == ["first started", "second started", "removed"]
+ emit_idle(service, spark, "after")
+ first.wait_for("after")
+ assert second.timestamps == []
+ finally:
+ release.set()
+ spark.streams.close()
+
+ # A removal from the callback that receives the started event returns
at once.
+ removed_listener = Recording()
+ order.clear()
+
+ class Removing(IdleListener):
+ def onQueryStarted(self, event):
+ order.append("removing started")
+ spark.streams.removeListener(removed_listener)
+ order.append("removed in callback")
+
+ try:
+ spark.streams.addListener(Removing())
+ spark.streams.addListener(removed_listener)
+ starter = threading.Thread(target=start_query, daemon=True)
+ starter.start()
+ starter.join(5)
+ assert not starter.is_alive()
+ assert "error" not in outcome
+ assert order[:2] == ["removing started", "removed in callback"]
+ finally:
+ spark.streams.close()
+
def test_streaming_listener_removal_waits_for_the_event_in_delivery(self,
mock_connect):
# As PySpark's bus, whose delivery of an event holds the lock of its
removal: a
# listener removed by another thread while an event is delivered gets
that event
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]