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 9663e22a [SPARK-61218][SPARK-61219][CONNECT][PYTHON] End a session
whose server-side session changed as stopped, and release the session before
the listeners are cancelled in stop()
9663e22a is described below
commit 9663e22a71ba6f356d08d28b50ac60de1305858e
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Mon Nov 9 17:07:43 2026 +0900
[SPARK-61218][SPARK-61219][CONNECT][PYTHON] End a session whose server-side
session changed as stopped, and release the session before the listeners are
cancelled in stop()
### What changes were proposed in this pull request?
[SPARK-61218](https://issues.apache.org/jira/browse/SPARK-61218): a session
whose server-side session changed is stopped, as PySpark's `is_stopped` is the
client's `is_closed`.
[SPARK-61219](https://issues.apache.org/jira/browse/SPARK-61219):
`spark.stop()` releases the server session before it cancels the listener bus,
so the terminated events of the running queries reach the listeners.
- `SparkSession::is_stopped` is true when the client is closed, as after a
server-side session change (SPARK-61184). So `is_stopped`, `getActiveSession()`
and `getOrCreate()` no longer return the dead session, and `getOrCreate()`
makes a working session, as in PySpark.
- `SparkSession::stop` releases the server session only while the client is
open, as PySpark's `stop()` checks `if not self.is_stopped`. Then it cancels
the listener bus and closes the client, so the server's terminated events of
the queries still running are dispatched. The stop stays idempotent.
### Why are the changes needed?
After a server restart, the observed server-side session ID changes and the
client closes, so every call raises `NO_ACTIVE_SESSION`. But `spark.is_stopped`
stayed `False`, `SparkSession.getActiveSession()` returned that session, and
`SparkSession.builder.getOrCreate()` returned it again, so the error's own
recovery ("create a new Spark Session") did not work. `stop()` also sent
ReleaseSession to the restarted server.
`spark.stop()` cancelled the listener bus before ReleaseSession, so a
listener of a query still running at stop got `onQueryStarted` and never
`onQueryTerminated`. Official PySpark 4.3.0 gives the terminated event
(`['start', 'term']` in the probe).
### Does this PR introduce _any_ user-facing change?
Yes. After a server-side session change, `is_stopped` is `True`,
`getActiveSession()` is `None` and `getOrCreate()` creates a new session.
`stop()` of such a session sends no ReleaseSession. `spark.stop()` delivers
`onQueryTerminated` to the listeners of the queries running at stop.
### How was this patch tested?
- `test_a_server_side_session_change_stops_the_session_as_pyspark`
(offline, mock gRPC server whose server-side ID changes): the session is
stopped after the change, `getActiveSession()` is `None`, `getOrCreate()`
returns a new working session, and `stop()` of the closed session sends no
ReleaseSession. Official PySpark 4.3.0 gives the same results (`is_stopped`
True, `getActiveSession()` None, a new session works).
-
`test_a_query_running_at_stop_sends_its_terminated_event_to_the_listeners_as_pyspark`
(live): a rate query with a listener on a new session, `stop()` of the
session, then the terminated event within 120 s. Official PySpark 4.3.0 gives
the same event.
-
`session::tests::a_session_whose_client_closed_is_stopped_and_is_not_released`
(Rust): a closed client makes the session stopped and shared by clones, and
`stop()` does not release it (the port has no server, so a release that reached
the wire would fail).
- Both Python tests fail without the change (the terminated test times out,
the offline test fails at `is_stopped`).
- The tests of both crates against a local Spark 4.3.0 Connect server (791
and 185 passed), the build of all tests, also with `wasm-udf`, the offline
Python suites (2704 passed, 8 skipped), and the live drop-in, Arrow and ML
suites (225 passed) and live cases (12 passed). rustfmt passes, and clippy
reports no diagnostics in the changed lines. The new live test passed in 10 of
10 runs under a machine load of about 45.
### 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 #402 from HyukjinKwon/SPARK-61218-session-end.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/spark-connect/src/session.rs | 47 +++++++++++++++++++++----
python/tests/test_dropin_e2e.py | 41 ++++++++++++++++++++++
python/tests/test_dropin_offline.py | 70 +++++++++++++++++++++++++++++++++++++
3 files changed, 151 insertions(+), 7 deletions(-)
diff --git a/crates/spark-connect/src/session.rs
b/crates/spark-connect/src/session.rs
index 23849793..6fc04310 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -1143,17 +1143,24 @@ 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.
///
- /// Cancel local listener registration/dispatch first, release the server
session, then
- /// close the client even if release fails. As PySpark's stop, this does
not make a
- /// separate listener-removal RPC: ReleaseSession releases the server's
listeners too.
+ /// 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.
+ /// As PySpark's stop, a client that is already closed, by a server-side
session change, is
+ /// not released. This does not make a separate listener-removal RPC:
ReleaseSession
+ /// releases the server's listeners too.
/// 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) {
return Ok(());
}
+ let released = if self.client.is_closed() {
+ Ok(())
+ } else {
+ block_on(self.client.release_session())
+ };
self.streams().cancel_listener_bus();
- let released = block_on(self.client.release_session());
// As PySpark's `stop()`, close the client even if server cleanup
fails, so its
// future requests raise `NO_ACTIVE_SESSION`.
self.client.close();
@@ -1176,10 +1183,11 @@ impl SparkSession {
self.client.close();
}
- /// Whether `stop()` has been called on this session. Mirrors
- /// `pyspark.sql.connect.session.SparkSession.is_stopped`.
+ /// 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`.
pub fn is_stopped(&self) -> bool {
- self.stopped.load(Ordering::SeqCst)
+ self.stopped.load(Ordering::SeqCst) || self.client.is_closed()
}
}
@@ -3665,4 +3673,29 @@ mod tests {
}
}
}
+
+ #[test]
+ fn a_session_whose_client_closed_is_stopped_and_is_not_released() {
+ // Port 1: nothing listens, so a ReleaseSession that reached the wire
would fail. As
+ // PySpark's stop(), a client that a server-side session change closed
is not released.
+ let spark = SparkSession::builder()
+ .remote("sc://localhost:1")
+ .get_or_create()
+ .expect("failed to build session");
+ let other = spark.clone();
+ spark.client.close();
+ assert!(
+ spark.is_stopped(),
+ "a closed client makes the session stopped"
+ );
+ assert!(
+ other.is_stopped(),
+ "the closed client is shared across clones"
+ );
+ assert!(
+ spark.stop().is_ok(),
+ "stop() does not release a closed client"
+ );
+ assert!(spark.stopped.load(Ordering::SeqCst));
+ }
}
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index b26a142b..0419b353 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -58,6 +58,47 @@ def session():
session.stop()
+def
test_a_query_running_at_stop_sends_its_terminated_event_to_the_listeners_as_pyspark(session):
+ # As PySpark's stop(): the session is released before its client closes,
so the terminated
+ # event that the server sends for a query still running at stop reaches
the listeners.
+ import threading
+
+ from pyspark.sql.streaming import StreamingQueryListener
+
+ started, terminated = threading.Event(), threading.Event()
+ terminated_ids = []
+
+ class Listener(StreamingQueryListener):
+ def onQueryStarted(self, event):
+ started.set()
+
+ def onQueryProgress(self, event):
+ pass
+
+ def onQueryIdle(self, event):
+ pass
+
+ def onQueryTerminated(self, event):
+ terminated_ids.append(str(event.id))
+ terminated.set()
+
+ other = session.newSession()
+ other.streams.addListener(Listener())
+ query =
other.readStream.format("rate").load().writeStream.format("noop").start()
+ try:
+ assert started.wait(timeout=120)
+ other.stop()
+ assert terminated.wait(timeout=120)
+ assert terminated_ids == [query.id]
+ finally:
+ try:
+ query.stop()
+ except Exception:
+ # The session is stopped, so the query is no longer reachable.
+ pass
+ other.stop()
+
+
@pytest.mark.parametrize("prefetch", [False, True])
def
test_to_local_iterator_raises_the_error_of_the_execution_as_pyspark(session,
prefetch):
# As official PySpark 4.3.0: the error of a query that fails while it is
iterated is
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 2eb7c42c..01a0ac8d 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -3256,6 +3256,76 @@ def
test_spatial_types_are_parsed_of_their_json_as_pyspark():
assert e.value.getCondition() == condition
+def test_a_server_side_session_change_stops_the_session_as_pyspark():
+ # As PySpark's, a server-side session ID that changes closes the client:
the session is
+ # stopped and no longer the active session, getOrCreate() makes a working
session, and
+ # stop() of the closed session sends no ReleaseSession.
+ import grpc
+ import pyspark.sql.connect.proto as pb2
+ from pyspark.errors import PySparkAssertionError
+
+ pytest.importorskip("grpc")
+ server_side_ids = ["srv-A"]
+ released = []
+
+ def config(raw, context):
+ request = pb2.ConfigRequest.FromString(raw)
+ if request.operation.HasField("get"):
+ keys = list(request.operation.get.keys)
+ else:
+ keys = [pair.key for pair in
request.operation.get_with_default.pairs]
+ response = pb2.ConfigResponse(
+ session_id=request.session_id,
server_side_session_id=server_side_ids[0]
+ )
+ for key in keys:
+ response.pairs.add(key=key, value="value")
+ return response.SerializeToString()
+
+ def release_session(raw, context):
+ request = pb2.ReleaseSessionRequest.FromString(raw)
+ released.append(request.session_id)
+ return pb2.ReleaseSessionResponse(
+ session_id=request.session_id,
server_side_session_id=server_side_ids[0]
+ ).SerializeToString()
+
+ server = grpc.server(ThreadPoolExecutor(max_workers=4))
+ server.add_generic_rpc_handlers(
+ (
+ grpc.method_handlers_generic_handler(
+ "spark.connect.SparkConnectService",
+ {
+ "Config": grpc.unary_unary_rpc_method_handler(config),
+ "ReleaseSession":
grpc.unary_unary_rpc_method_handler(release_session),
+ },
+ ),
+ )
+ )
+ port = server.add_insecure_port("127.0.0.1:0")
+ server.start()
+ remote = f"sc://127.0.0.1:{port}"
+ key = "spark.sql.shuffle.partitions"
+ try:
+ spark = SparkSession.builder.remote(remote).getOrCreate()
+ assert spark.conf.get(key) == "value"
+ assert not spark.is_stopped
+
+ server_side_ids[0] = "srv-B"
+ with pytest.raises(PySparkAssertionError, match="server side session
identifier"):
+ spark.conf.get(key)
+ assert spark.is_stopped and spark._client.is_closed
+ assert SparkSession.getActiveSession() is None
+
+ new = SparkSession.builder.remote(remote).getOrCreate()
+ try:
+ assert new is not spark and not new.is_stopped
+ assert new.conf.get(key) == "value"
+ spark.stop()
+ assert released == []
+ finally:
+ new.stop()
+ assert len(released) == 1
+ finally:
+ server.stop(0).wait()
def test_variant_and_geo_values():
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]