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 a071c6ee [SPARK-61526][CONNECT][PYTHON] Let a signal end the wait for
the next event of streamListenerEvents, and run the interrupt tests with the
SIGINT handler that a background start ignores
a071c6ee is described below
commit a071c6ee683733b410c4e09ed59037cd957b651e
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 20:30:32 2026 +0900
[SPARK-61526][CONNECT][PYTHON] Let a signal end the wait for the next event
of streamListenerEvents, and run the interrupt tests with the SIGINT handler
that a background start ignores
### What changes were proposed in this pull request?
Follow-ups from a review of #535 (SPARK-61470: Ctrl-C ends every wait of
the Python client for the server) and of #552:
- **`next()` of `spark.streams.streamListenerEvents()`**, an extra of this
client, waited for the server's next event with a bare `py.detach`
(`crates/pyspark-rs/src/streaming.rs`), so a Ctrl-C was ignored until an event
came or the reattach retries ended. #535's sweep missed this wait. The iterator
now keeps the session of its stream and waits through `interruptible`, as the
other waits of the client do. A signal then ends the read at once, which #552's
`until_abort` in `ListenerEven [...]
- **The interrupt tests ran with SIGINT ignored** when pytest was started
as a background job of a non-interactive shell (`pytest ... &`, `( ... ) &`,
`nohup ... &`). Such a job inherits SIGINT as ignored, and Python leaves it
ignored. Every `os.kill(SIGINT)` of the tests was then dropped, including in
their subprocesses, since an ignored signal stays ignored across exec. Each
test waited out its fallback before it failed: the mock's gates, the retry
budget (about 10 minutes), or the [...]
-
**`test_a_second_sigint_during_add_listener_removes_the_server_listener_before_the_next_add`**
no longer sent its second signal after #552, since the first signal already
ends the wait for the acknowledgement. The test now makes the mock fail the
interrupt with `UNAVAILABLE`, so that the interrupt of the first signal is
retried and only the second signal ends the wait. It also asserts the timing.
### Why are the changes needed?
- A Ctrl-C during `next()` of the event iterator was ignored. Against a
stub that acks the listener and sends no event, the client never returned and
was killed by a 40 s timeout.
- The SIGINT tests failed together whenever the suite ran as a background
job: 24 of 27 failed in 26 minutes, and the same tests pass in 29 s in the
foreground. Here,
`test_sigint_during_add_listener_keeps_the_registration_removable`,
`test_sigint_during_the_plan_compression_lookup_raises_keyboard_interrupt_at_once`
and the new conftest test pass in 5 s as a background job of `sh -c '... &
wait'`. A Python started that way prints `1` (`SIG_IGN`) for
`signal.getsignal(SIGINT)`.
- The second-signal path of the acknowledgement wait was untested after
#552.
### Does this PR introduce _any_ user-facing change?
Yes, for an extra of this client: a Ctrl-C during `next()` of
`spark.streams.streamListenerEvents()` raises `KeyboardInterrupt` at once. The
rest is tests only.
### How was this patch tested?
New tests in `python/tests/test_dropin_offline.py`:
-
`test_sigint_during_the_next_listener_event_raises_keyboard_interrupt_at_once`:
a SIGINT at 0.5 s of a `next()` that gets no event raises within 5 s. Without
the change, the `KeyboardInterrupt` came after the stream's end at 10 s and
escaped the test.
- `test_tests_restore_the_sigint_handler_that_a_background_start_ignores`:
a subprocess that starts with SIGINT ignored runs `conftest.py` and gets
`KeyboardInterrupt` from a SIGINT. It fails without `conftest.py`, and with a
`conftest.py` that does not restore the handler.
- The second-signal test above, now with `0.9 < elapsed < 5`.
Also run:
- the add-listener SIGINT tests;
- the three tests above as a background job, without GNU `timeout`, which
resets SIGINT for its child: 3 passed in 5 s;
- `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 #562 from HyukjinKwon/SPARK-61526-ctrlc-followups.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/streaming.rs | 21 +++++++++-----
python/tests/conftest.py | 12 ++++++++
python/tests/test_dropin_offline.py | 56 +++++++++++++++++++++++++++++++++++++
3 files changed, 82 insertions(+), 7 deletions(-)
diff --git a/crates/pyspark-rs/src/streaming.rs
b/crates/pyspark-rs/src/streaming.rs
index e6749ae5..14664aa6 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -1560,10 +1560,11 @@ impl PyStreamingQueryManager {
}
fn streamListenerEvents(&self, py: Python<'_>) ->
PyResult<PyListenerEventStream> {
- let stream = interruptible(py, &self.inner.spark_session(), || {
+ let session = self.inner.spark_session();
+ let stream = interruptible(py, &session, || {
self.inner.listener_event_stream().map_err(Box::new)
})?;
- Ok(PyListenerEventStream::new(stream))
+ Ok(PyListenerEventStream::new(stream, session))
}
}
@@ -1572,12 +1573,15 @@ impl PyStreamingQueryManager {
#[pyclass(name = "ListenerEventStream", module =
"pyspark.sql.streaming.query")]
pub struct PyListenerEventStream {
inner: Option<ListenerEventStream>,
+ /// The session of the stream, whose waits a signal of the process ends.
+ session: spark_connect::session::SparkSession,
}
impl PyListenerEventStream {
- pub fn new(stream: ListenerEventStream) -> Self {
+ pub fn new(stream: ListenerEventStream, session:
spark_connect::session::SparkSession) -> Self {
PyListenerEventStream {
inner: Some(stream),
+ session,
}
}
}
@@ -1595,10 +1599,13 @@ impl PyListenerEventStream {
));
};
// The listener bus blocks in `next()` waiting for the server's next
event
- // (arbitrarily far apart on a live query), so release the GIL across
it —
- // otherwise the daemon thread would freeze the whole interpreter
between
- // events. Mirrors `PyLocalRowIterator::__next__`.
- match py.detach(|| stream.next()) {
+ // (arbitrarily far apart on a live query), so the wait releases the
GIL, or a daemon
+ // thread would freeze the whole interpreter between events, and a
signal of the process
+ // ends it with its exception, as it ends the other waits of the
client for the server.
+ let next = interruptible(py, &self.session, || {
+ Ok::<_, Box<SparkError>>(stream.next())
+ })?;
+ match next {
Some(Ok((event_type, event_json))) => Ok(Some((event_type,
event_json))),
Some(Err(e)) => Err(PyErr::new::<pyo3::exceptions::PyRuntimeError,
_>(format!(
"Error reading listener events: {}",
diff --git a/python/tests/conftest.py b/python/tests/conftest.py
new file mode 100644
index 00000000..89506041
--- /dev/null
+++ b/python/tests/conftest.py
@@ -0,0 +1,12 @@
+"""The setup of the processes of the tests of the drop-in."""
+
+import signal
+
+# A pytest that a non-interactive shell starts in the background (`pytest ...
&`, `nohup ... &`)
+# inherits SIGINT as ignored, and Python then leaves it ignored: the SIGINT
that the tests of the
+# interrupts send would be dropped, and each of them would wait out its
fallback (the retry
+# budget, the timeout of its subprocess) before it fails. Python's own handler
is installed
+# instead, and the subprocesses of the tests start with the default too, as
exec resets a
+# signal that a handler catches.
+if signal.getsignal(signal.SIGINT) == signal.SIG_IGN:
+ signal.signal(signal.SIGINT, signal.default_int_handler)
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index c8797779..0a8fd960 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -20211,18 +20211,24 @@ def
test_a_second_sigint_during_add_listener_removes_the_server_listener_before_
spark, service = mock_connect
service.listener_bus_enabled = True
service.listener_register_blocked = True
+ # The interrupt of the first signal is retried, as the server is
unavailable for it, so only
+ # the second signal ends the wait, as PySpark's retry sleep raises at it.
+ service.interrupt_failure = ("UNAVAILABLE", "server is unavailable")
# A wait that the signals do not end is released after 10 s, so the test
fails, not hangs.
release = threading.Timer(10, service.release_listener_registration)
timers = [threading.Timer(delay, os.kill, (os.getpid(), signal.SIGINT))
for delay in (0.5, 1.0)]
release.start()
for timer in timers:
timer.start()
+ started = time.monotonic()
try:
with pytest.raises(KeyboardInterrupt):
spark.streams.addListener(Listener())
finally:
for timer in timers:
timer.cancel()
+ service.interrupt_failure = None
+ assert 0.9 < time.monotonic() - started < 5
release.cancel()
service.release_listener_registration()
assert service.wait_listener_registration(1)
@@ -20276,6 +20282,56 @@ def
test_sigint_during_add_listener_with_the_acknowledgement_held_raises_at_once
assert service.listener_removals == 1
+def
test_sigint_during_the_next_listener_event_raises_keyboard_interrupt_at_once(mock_connect):
+ # The iterator of streamListenerEvents, an extra of this client, waits for
the next event of
+ # the server, which a signal ends at once, as it ends the other waits for
the server.
+ import signal
+ import threading
+
+ spark, service = mock_connect
+ service.listener_bus_enabled = True
+ events = spark.streams.streamListenerEvents()
+ # The stream ends after 10 s, so that a wait that the signal does not end
fails, not hangs.
+ end = threading.Timer(10, service.end_listener_stream, (spark.session_id,))
+ timer = threading.Timer(0.5, os.kill, (os.getpid(), signal.SIGINT))
+ end.start()
+ timer.start()
+ started = time.monotonic()
+ try:
+ with pytest.raises(KeyboardInterrupt):
+ next(events)
+ finally:
+ timer.cancel()
+ assert time.monotonic() - started < 5
+ end.cancel()
+ del events
+
+
+def test_tests_restore_the_sigint_handler_that_a_background_start_ignores():
+ # A process that a non-interactive shell starts in the background inherits
SIGINT as
+ # ignored: conftest.py installs Python's handler, so that a SIGINT raises
KeyboardInterrupt.
+ import signal
+ import subprocess
+ import sys
+
+ conftest = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"conftest.py")
+ code = (
+ "import os, runpy, signal, time\n"
+ "assert signal.getsignal(signal.SIGINT) == signal.SIG_IGN\n"
+ "runpy.run_path(os.environ['CONFTEST'])\n"
+ "try:\n"
+ " os.kill(os.getpid(), signal.SIGINT)\n"
+ " time.sleep(5)\n"
+ "except KeyboardInterrupt:\n"
+ " print('interrupted')\n"
+ )
+ result = subprocess.run(
+ [sys.executable, "-c", code], env={**os.environ, "CONFTEST": conftest},
+ preexec_fn=lambda: signal.signal(signal.SIGINT, signal.SIG_IGN),
+ capture_output=True, text=True, timeout=60, check=True)
+ assert result.stdout.strip() == "interrupted"
+
+
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]