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 311555ba [SPARK-61388][CONNECT][PYTHON] Interrupt only the execution
that an interrupted call waits for, in the Python client as PySpark does
311555ba is described below
commit 311555ba7eb9245ddd63d2bcf6417dc6e97c20b2
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 08:55:28 2026 +0900
[SPARK-61388][CONNECT][PYTHON] Interrupt only the execution that an
interrupted call waits for, in the Python client as PySpark does
### What changes were proposed in this pull request?
[SPARK-61388](https://issues.apache.org/jira/browse/SPARK-61388): a
follow-up of #455 (SPARK-61259) and #457 (SPARK-61353), from a review of them.
A SIGINT in the Python client now interrupts only the execution that the
interrupted call waits for, as PySpark does:
- The registry of in-flight executions
(`crates/spark-connect-core/src/client.rs`) records, for each execution, the
thread that started it and the thread that waits for it now. The first RPC of
an execution and each `ReattachableResponseStream::message()` mark the
execution as waited for while they wait, only on the thread that started it.
`running_operation_id()` returns the innermost execution that the calling
thread waits for, so an execution that is in flight but not read (a half- [...]
- The Rust API's prefetching `to_local_iterator(prefetch_partitions =
true)` reads its stream in a task. Its `next()` marks the execution as waited
for by the caller while the caller waits for the task's batch, through a new
`InflightHandle` (`ReattachableResponseStream::inflight_handle()`).
- The signal watch (`crates/pyspark-rs/src/interrupt.rs`) no longer latches
a signal that arrives while no execution is waited for, such as during the plan
compression lookup or an analysis before an execution. It keeps the exception,
and interrupts the first execution that the call then waits for, once. An
abortable wait (the release of `stop()`) ends at once, as before.
### Why are the changes needed?
The registry was keyed by the thread that started an execution, and its
innermost entry won:
- With a half-consumed `toLocalIterator()` B alive, a SIGINT during
`next(A)` interrupted B. A ran to its end (20 s in the review's repro) before
`KeyboardInterrupt`. PySpark 4.3.0 interrupts A after about 2 s, and `next(B)`
still returns its next row. Now the drop-in does the same.
- With such an iterator, or a `StreamingQueryListener` registered from the
main thread, a SIGINT during `SparkSession.stop()` interrupted that unrelated
execution, and `stop()` then waited for the release (75 s and more with an
unreachable server) instead of raising `KeyboardInterrupt` at once, as #457
meant and PySpark does.
- A signal during the plan compression lookup (a Config RPC before the
first execution of a session) was consumed and latched, so the execution that
the call then started ran to its end. Now it is interrupted.
### Does this PR introduce _any_ user-facing change?
Yes, in the Python client and the Rust API's waits: `KeyboardInterrupt`
interrupts the execution that the interrupted call waits for, promptly, and
leaves the other executions and the session alone.
### How was this patch tested?
- Rust unit tests: the registry selects only the innermost execution that
the calling thread waits for (not an unread one, not another thread's wait),
and an `InflightHandle` marks only the waits of the thread that started the
execution.
- Rust e2e (`e2e_session_catalog.rs`): a watch on the caller interrupts a
prefetching iterator's execution during `next()`, an unread prefetching
iterator is not selected, and the session works afterwards.
- Offline Python tests (mock server): the iterator that waits is
interrupted and a held one still yields; SIGINT during `stop()` with an
unconsumed iterator and with a registered listener raises at once; a SIGINT
during the plan compression lookup interrupts the first execution. Each new
test fails without the change.
- Live Python e2e: the review's repro with a sleeping partition
(`reflect`), against a Spark 4.3.0 server.
- `cargo test -p apache-spark-connect -p apache-spark-connect-core
--release --lib`, the `--no-run` builds with and without `wasm-udf`, `cargo fmt
--check`, the offline and e2e drop-in suites.
### 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 #477 from HyukjinKwon/SPARK-61388-interrupt-waited-execution.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/interrupt.rs | 40 ++--
crates/spark-connect-core/src/client.rs | 236 +++++++++++++++++-----
crates/spark-connect/src/dataframe.rs | 13 +-
crates/spark-connect/src/progress.rs | 8 +-
crates/spark-connect/tests/e2e_session_catalog.rs | 59 ++++++
python/tests/_mock_connect_server.py | 21 +-
python/tests/test_dropin_e2e.py | 40 ++++
python/tests/test_dropin_offline.py | 146 +++++++++++++
8 files changed, 490 insertions(+), 73 deletions(-)
diff --git a/crates/pyspark-rs/src/interrupt.rs
b/crates/pyspark-rs/src/interrupt.rs
index 2be83c13..8e4f69cb 100644
--- a/crates/pyspark-rs/src/interrupt.rs
+++ b/crates/pyspark-rs/src/interrupt.rs
@@ -19,25 +19,33 @@ use crate::errors::ResultExt;
/// The poll of the signals of one wait.
struct SignalWatch {
session: SparkSession,
- /// Whether a handler raised, once: after that, the wait only waits.
- raised: AtomicBool,
- /// The exception of the handler, which the wait raises once it has ended.
+ /// Whether the execution that the wait is for has been interrupted for
the signal: after
+ /// that, the wait only waits.
+ interrupted: AtomicBool,
+ /// The exception of the first handler that raised, which the wait raises
once it has ended.
error: Mutex<Option<PyErr>>,
}
impl SignalWatch {
fn poll(&self) -> Watch {
- if self.raised.load(Ordering::SeqCst) {
+ if self.interrupted.load(Ordering::SeqCst) {
return Watch::Continue;
}
- // Takes the GIL for the check only, as the wait runs without it.
- let Err(error) = Python::attach(|py| py.check_signals()) else {
- return Watch::Continue;
- };
- self.raised.store(true, Ordering::SeqCst);
- *self.error.lock().unwrap_or_else(|e| e.into_inner()) = Some(error);
+ {
+ let mut error = self.error.lock().unwrap_or_else(|e|
e.into_inner());
+ if error.is_none() {
+ // Takes the GIL for the check only, as the wait runs without
it.
+ match Python::attach(|py| py.check_signals()) {
+ Ok(()) => return Watch::Continue,
+ Err(signal) => *error = Some(signal),
+ }
+ }
+ }
+ // The signal stays captured while no execution that the wait is for
is in flight, so
+ // that the first one the call starts is interrupted.
match self.session.running_operation_id() {
Some(operation_id) => {
+ self.interrupted.store(true, Ordering::SeqCst);
let session = self.session.clone();
Watch::Interrupt(Box::pin(async move {
// A failed interrupt does not replace the exception of
the signal.
@@ -52,13 +60,15 @@ impl SignalWatch {
}
/// Run `f` without the GIL, on the calling thread, as the signals of the
process are polled while
-/// it waits for the server. When a handler raises, the execution in flight of
the calling thread
+/// it waits for the server. When a handler raises, the execution that the
calling thread waits for
/// is interrupted, and the exception of the handler is raised once `f` has
ended. Otherwise the
/// result of `f` is returned.
///
-/// The execution is interrupted only when `f` has started one; a request that
is still waiting
-/// for its response (such as an analysis) ends when the response arrives, and
the exception is
-/// raised then. A wait of `block_on_abortable` (the release of `stop()`) ends
at once instead.
+/// The execution is interrupted only when a wait of the calling thread is for
one. A signal that
+/// arrives while none is (such as during the analysis of a plan, or the plan
compression before
+/// an execution) is kept, and the first execution that `f` then waits for is
interrupted; a
+/// request that never starts one ends when its response arrives, and the
exception is raised
+/// then. A wait of `block_on_abortable` (the release of `stop()`) ends at
once instead.
///
/// An execution that `f` ran then raises for the metrics of an Observation
that PySpark does
/// not convert, as PySpark's does (`ObservedMetricsCheck`).
@@ -85,7 +95,7 @@ pub(crate) fn interruptible_outcome<T: Send, E: Send +
Into<Box<SparkError>>>(
) -> PyResult<Result<T, Box<SparkError>>> {
let watch = Arc::new(SignalWatch {
session: session.clone(),
- raised: AtomicBool::new(false),
+ interrupted: AtomicBool::new(false),
error: Mutex::new(None),
});
let poll: Arc<WaitWatch> = {
diff --git a/crates/spark-connect-core/src/client.rs
b/crates/spark-connect-core/src/client.rs
index 37c8d8fd..460d2900 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -394,50 +394,137 @@ pub struct SparkConnectClient {
/// check of the IDs of its responses, and its close when the server
reports that the session
/// changed. See [`SparkConnectClient::set_session_tracking`].
session_tracking: bool,
- /// The executions in flight, shared by the clones of the client, each
with the calling
- /// thread that started it, in the order they started. See
+ /// The executions in flight, shared by the clones of the client, in the
order they started,
+ /// each with the thread that waits for it now, if any. See
/// [`SparkConnectClient::running_operation_id`].
inflight_operations: std::sync::Arc<std::sync::Mutex<Vec<InflightEntry>>>,
/// The plan compression of the client, shared by its clones, looked up on
its first plan.
plan_compression: std::sync::Arc<std::sync::Mutex<PlanCompression>>,
}
-/// An execution in flight: the thread that started it, and its operation ID.
+/// An execution in flight: its operation ID, and the thread that waits for it
now, if any.
#[derive(Debug, Clone, PartialEq)]
struct InflightEntry {
- thread: std::thread::ThreadId,
operation_id: String,
+ waiter: Option<std::thread::ThreadId>,
}
/// Keeps an execution in the registry of the in-flight executions of its
client until it drops.
struct InflightGuard {
registry: std::sync::Arc<std::sync::Mutex<Vec<InflightEntry>>>,
- entry: InflightEntry,
+ operation_id: String,
+ /// The thread that registered the execution, which is the caller that
starts it.
+ registered_on: std::thread::ThreadId,
}
impl InflightGuard {
- /// Register `entry` in `registry` until the guard drops.
+ /// Register the execution `operation_id` in `registry` until the guard
drops.
fn register(
registry: std::sync::Arc<std::sync::Mutex<Vec<InflightEntry>>>,
- entry: InflightEntry,
+ operation_id: String,
) -> Self {
registry
.lock()
.unwrap_or_else(|e| e.into_inner())
- .push(entry.clone());
- InflightGuard { registry, entry }
+ .push(InflightEntry {
+ operation_id: operation_id.clone(),
+ waiter: None,
+ });
+ InflightGuard {
+ registry,
+ operation_id,
+ registered_on: crate::runtime::calling_thread_id(),
+ }
+ }
+
+ /// The handle of the execution, which the caller that started it uses to
mark its waits.
+ fn handle(&self) -> InflightHandle {
+ InflightHandle {
+ registry: std::sync::Arc::clone(&self.registry),
+ operation_id: self.operation_id.clone(),
+ registered_on: self.registered_on,
+ }
+ }
+
+ /// Marks the execution as waited for by the calling thread, until the
returned guard drops.
+ fn waiting(&self) -> WaitingGuard {
+ self.handle().waiting()
+ }
+}
+
+/// A handle of an execution in flight, to mark the waits of its caller for
it: see
+/// [`InflightHandle::waiting`]. The handle does not keep the execution in
flight.
+#[derive(Clone)]
+pub struct InflightHandle {
+ registry: std::sync::Arc<std::sync::Mutex<Vec<InflightEntry>>>,
+ operation_id: String,
+ registered_on: std::thread::ThreadId,
+}
+
+impl InflightHandle {
+ /// Marks the execution as waited for by the calling thread, until the
returned guard drops,
+ /// so that a signal that the wait polls interrupts it (see
+ /// [`SparkConnectClient::running_operation_id`]). Only a wait of the
thread that started the
+ /// execution is marked: a wait of another thread, such as a background
task that reads the
+ /// execution for its caller, is not the caller's, and the caller marks
its own waits instead.
+ pub fn waiting(&self) -> WaitingGuard {
+ let caller = crate::runtime::calling_thread_id();
+ let marked = caller == self.registered_on;
+ if marked {
+ set_waiter(&self.registry, &self.operation_id, Some(caller));
+ }
+ WaitingGuard {
+ registry: std::sync::Arc::clone(&self.registry),
+ operation_id: self.operation_id.clone(),
+ marked,
+ }
}
}
impl Drop for InflightGuard {
fn drop(&mut self) {
let mut inflight = self.registry.lock().unwrap_or_else(|e|
e.into_inner());
- if let Some(position) = inflight.iter().rposition(|entry| *entry ==
self.entry) {
+ if let Some(position) = inflight
+ .iter()
+ .rposition(|entry| entry.operation_id == self.operation_id)
+ {
inflight.remove(position);
}
}
}
+/// Marks an execution as waited for by the calling thread, until it drops. See
+/// [`InflightHandle::waiting`].
+pub struct WaitingGuard {
+ registry: std::sync::Arc<std::sync::Mutex<Vec<InflightEntry>>>,
+ operation_id: String,
+ marked: bool,
+}
+
+impl Drop for WaitingGuard {
+ fn drop(&mut self) {
+ if self.marked {
+ set_waiter(&self.registry, &self.operation_id, None);
+ }
+ }
+}
+
+/// Sets the thread that waits for the execution `operation_id` in `registry`,
if it is in flight.
+fn set_waiter(
+ registry: &std::sync::Mutex<Vec<InflightEntry>>,
+ operation_id: &str,
+ waiter: Option<std::thread::ThreadId>,
+) {
+ let mut inflight = registry.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(entry) = inflight
+ .iter_mut()
+ .rev()
+ .find(|entry| entry.operation_id == operation_id)
+ {
+ entry.waiter = waiter;
+ }
+}
+
/// The user context extensions of a client, as PySpark's `SparkConnectClient`
keeps them: those
/// of all the threads, and those of each thread, which the requests of a
thread carry, of their
/// IDs.
@@ -607,11 +694,12 @@ impl SparkConnectClient {
self.closed.load(std::sync::atomic::Ordering::SeqCst)
}
- /// The operation ID of the innermost execution in flight that the calling
thread started, if
- /// any: the one that a wait of the calling thread is for, as PySpark
interrupts the operation
- /// of the iterator that is interrupted.
+ /// The operation ID of the innermost execution that the calling thread is
waiting for, if any:
+ /// the one that a wait of the calling thread is for, as PySpark
interrupts the operation of
+ /// the iterator that is interrupted. An execution in flight that nothing
waits for, such as
+ /// an iterator that is not consumed, is not one.
pub fn running_operation_id(&self) -> Option<String> {
- let thread = crate::runtime::calling_thread_id();
+ let caller = crate::runtime::calling_thread_id();
let inflight = self
.inflight_operations
.lock()
@@ -619,7 +707,7 @@ impl SparkConnectClient {
inflight
.iter()
.rev()
- .find(|entry| entry.thread == thread)
+ .find(|entry| entry.waiter == Some(caller))
.map(|entry| entry.operation_id.clone())
}
@@ -1228,16 +1316,15 @@ impl SparkConnectClient {
// Before the first RPC, so that an execution that waits for the
server is in flight.
let inflight = InflightGuard::register(
std::sync::Arc::clone(&self.inflight_operations),
- InflightEntry {
- thread: crate::runtime::calling_thread_id(),
- operation_id: iter.operation_id().to_string(),
- },
+ iter.operation_id().to_string(),
);
let start = iter.request().clone();
let deadline = self.rpc_deadlines.reattachable_execute_plan;
let mut stream_deadline = None;
- let stream = self
- .with_retry(|| {
+ let stream = {
+ // The first RPC is a wait of the caller for the execution.
+ let _waiting = inflight.waiting();
+ self.with_retry(|| {
let mut req = with_deadline(Request::new(start.clone()),
deadline);
self._attach_metadata(&mut req);
stream_deadline = deadline.map(|d| tokio::time::Instant::now()
+ d);
@@ -1248,7 +1335,8 @@ impl SparkConnectClient {
.map(Response::into_inner)
}
})
- .await;
+ .await
+ };
let stream = match stream {
Ok(stream) => Some(stream),
// As the reference iterator, past its deadline an execution is
resumed by
@@ -2164,6 +2252,13 @@ impl SparkConnectClient {
}
impl ReattachableResponseStream {
+ /// The handle of the execution of this stream, to mark the waits of the
caller that starts it
+ /// for the execution while the caller reads its responses from another
thread (see
+ /// [`InflightHandle::waiting`]).
+ pub fn inflight_handle(&self) -> InflightHandle {
+ self._inflight.handle()
+ }
+
/// The gRPC metadata of every request about this execution.
fn metadata_map(&self) -> MetadataMap {
self.client.execution_metadata()
@@ -2179,6 +2274,8 @@ impl ReattachableResponseStream {
if self.done {
return Ok(None);
}
+ // Each wait for the next response is a wait of the caller for the
execution.
+ let _waiting = self._inflight.waiting();
// As the reference iterator's `_has_next` retries with a `Retrying`
of its own, the
// reattaches of each response have the attempts and the elapsed time
of the policy.
let mut retry_state = RetryPolicyState::new(self.retry_policy.clone());
@@ -2628,45 +2725,84 @@ mod tests {
}
#[test]
- fn
test_running_operation_id_is_the_innermost_execution_of_the_calling_thread() {
+ fn
test_running_operation_id_is_the_innermost_execution_the_calling_thread_waits_for()
{
let client = connect_blocking("sc://example.com");
assert_eq!(client.running_operation_id(), None);
- let entry = |thread, operation_id: &str| InflightEntry {
- thread,
- operation_id: operation_id.to_string(),
- };
- let caller = crate::runtime::calling_thread_id();
- let outer = InflightGuard::register(
- std::sync::Arc::clone(&client.inflight_operations),
- entry(caller, "outer"),
- );
- let inner = InflightGuard::register(
- std::sync::Arc::clone(&client.inflight_operations),
- entry(caller, "inner"),
- );
+ let registry = || std::sync::Arc::clone(&client.inflight_operations);
+ let outer = InflightGuard::register(registry(), "outer".to_string());
+ let inner = InflightGuard::register(registry(), "inner".to_string());
+ // In flight, but nothing waits for them: no execution is interrupted.
+ assert_eq!(client.running_operation_id(), None);
+ let wait_outer = outer.waiting();
+ assert_eq!(client.running_operation_id().as_deref(), Some("outer"));
+ let wait_inner = inner.waiting();
assert_eq!(client.running_operation_id().as_deref(), Some("inner"));
- drop(inner);
+ drop(wait_inner);
assert_eq!(client.running_operation_id().as_deref(), Some("outer"));
- // The executions of another thread are not those of the calling
thread.
+ drop(wait_outer);
+ assert_eq!(client.running_operation_id(), None);
+ // The waits of another thread are not those of the calling thread.
+ let (waiting_tx, waiting_rx) = std::sync::mpsc::channel();
+ let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
let other = std::thread::spawn({
- let client = client.clone();
- let registry = std::sync::Arc::clone(&client.inflight_operations);
+ let registry = registry();
move || {
- let _guard = InflightGuard::register(
- registry,
- entry(crate::runtime::calling_thread_id(), "other"),
- );
- client.running_operation_id()
+ let guard = InflightGuard::register(registry,
"other".to_string());
+ let _wait = guard.waiting();
+ waiting_tx.send(()).unwrap();
+ done_rx.recv().unwrap();
}
- })
- .join()
- .unwrap();
- assert_eq!(other.as_deref(), Some("other"));
- assert_eq!(client.running_operation_id().as_deref(), Some("outer"));
+ });
+ waiting_rx.recv().unwrap();
+ assert_eq!(client.running_operation_id(), None);
+ done_tx.send(()).unwrap();
+ other.join().unwrap();
+ // Once the registration of the execution drops, it is not in flight
any more.
+ let wait_inner = inner.waiting();
+ drop(inner);
+ assert_eq!(client.running_operation_id(), None);
+ drop(wait_inner);
drop(outer);
assert_eq!(client.running_operation_id(), None);
}
+ #[test]
+ fn
test_an_inflight_handle_marks_only_the_waits_of_the_thread_that_started_it() {
+ // As a prefetching iterator: the execution is read by a task of its
own, and its caller
+ // marks its wait for the batches through the handle.
+ let client = connect_blocking("sc://example.com");
+ let guard = InflightGuard::register(
+ std::sync::Arc::clone(&client.inflight_operations),
+ "prefetch".to_string(),
+ );
+ let handle = guard.handle();
+ // Not read: the execution is in flight, but no wait of the caller is
for it.
+ assert_eq!(client.running_operation_id(), None);
+ {
+ let _waiting = handle.waiting();
+ assert_eq!(client.running_operation_id().as_deref(),
Some("prefetch"));
+ }
+ assert_eq!(client.running_operation_id(), None);
+ // The reads of a task on another thread do not mark the execution for
the caller: the
+ // task's wait is not the caller's.
+ let (waiting_tx, waiting_rx) = std::sync::mpsc::channel();
+ let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
+ let task = std::thread::spawn({
+ let handle = handle.clone();
+ move || {
+ let _waiting = handle.waiting();
+ waiting_tx.send(()).unwrap();
+ done_rx.recv().unwrap();
+ }
+ });
+ waiting_rx.recv().unwrap();
+ assert_eq!(client.running_operation_id(), None);
+ done_tx.send(()).unwrap();
+ task.join().unwrap();
+ drop(guard);
+ assert_eq!(client.running_operation_id(), None);
+ }
+
/// Connects a client on a runtime of its own, for the tests that set the
environment.
/// The channel is lazy, so no server is dialed.
fn connect_blocking(url: &str) -> SparkConnectClient {
diff --git a/crates/spark-connect/src/dataframe.rs
b/crates/spark-connect/src/dataframe.rs
index 45044adf..37fbde39 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -5,6 +5,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
+use spark_connect_core::client::InflightHandle;
use spark_connect_core::error::{Result, SparkError, SparkErrorKind};
use spark_connect_core::runtime::{block_on, get_runtime};
use spark_connect_proto as proto;
@@ -147,6 +148,8 @@ enum RowSource {
/// The task, to raise its panic (of a progress handler, say) in the
caller once its
/// channel closes, as the on-demand source raises it, instead of
ending early.
task: Option<tokio::task::JoinHandle<()>>,
+ /// The execution, which the caller waits for while it waits for the
task's batches.
+ wait: InflightHandle,
},
}
@@ -160,10 +163,12 @@ impl LocalRowIterator {
let schema = SchemaSlot::default();
let source = if prefetch_partitions {
{
+ let wait = stream.inflight_handle();
let (rx, task) = spawn_prefetch(session, stream,
Arc::clone(&schema));
RowSource::Prefetch {
rx,
task: Some(task),
+ wait,
}
}
} else {
@@ -234,8 +239,12 @@ impl LocalRowIterator {
}
}
},
- RowSource::Prefetch { rx, task } => {
- let batch = block_on(rx.recv());
+ RowSource::Prefetch { rx, task, wait } => {
+ // The caller waits for the batch of the task, which is a wait
for the execution.
+ let batch = {
+ let _waiting = wait.waiting();
+ block_on(rx.recv())
+ };
if batch.is_none() {
// The channel closed: the task ended, or it panicked,
which then drops its
// sender without an error. Raise the panic here, so the
rows are not cut
diff --git a/crates/spark-connect/src/progress.rs
b/crates/spark-connect/src/progress.rs
index 0a8c0750..6e9e1bd0 100644
--- a/crates/spark-connect/src/progress.rs
+++ b/crates/spark-connect/src/progress.rs
@@ -4,7 +4,7 @@
use std::sync::Arc;
-use spark_connect_core::client::ReattachableResponseStream;
+use spark_connect_core::client::{InflightHandle, ReattachableResponseStream};
use spark_connect_core::error::{Result, SparkError};
use spark_connect_core::runtime::CallbackGuard;
use spark_connect_proto as proto;
@@ -215,6 +215,12 @@ impl ExecutionStream {
}
}
+ /// The handle of the execution, to mark the waits of its caller for it
(see
+ /// [`ReattachableResponseStream::inflight_handle`]).
+ pub(crate) fn inflight_handle(&self) -> InflightHandle {
+ self.stream.inflight_handle()
+ }
+
/// The next response of the execution, as
`ReattachableResponseStream::message`, with the
/// chunks of an Arrow batch joined into the batch: the response of a
chunk that is not the
/// last one has no batch.
diff --git a/crates/spark-connect/tests/e2e_session_catalog.rs
b/crates/spark-connect/tests/e2e_session_catalog.rs
index 2342b590..b19ee856 100644
--- a/crates/spark-connect/tests/e2e_session_catalog.rs
+++ b/crates/spark-connect/tests/e2e_session_catalog.rs
@@ -422,6 +422,65 @@ fn json_to_ddl_converts_on_the_server() {
/// The execution that the calling thread waits for is the one that its wait
interrupts, as
/// PySpark's `KeyboardInterrupt` does: the wait ends with the server's
cancellation, and the
/// session goes on.
+/// A prefetching iterator is read by a task of its own, and its caller waits
for the task's
+/// batches: a wait of the caller interrupts its execution, while an iterator
that is not read is
+/// not the one a wait interrupts.
+#[test]
+fn interrupting_the_wait_of_a_prefetching_iterator_cancels_its_execution() {
+ use std::sync::atomic::{AtomicBool, Ordering};
+ use std::sync::Arc;
+ use std::time::{Duration, Instant};
+
+ use spark_connect_core::runtime::{with_wait_watch, WaitWatch, Watch};
+
+ if !should_run() {
+ return;
+ }
+ let spark = session();
+ let slow = spark
+ .sql("SELECT sum(sqrt(id)) FROM range(0, 1000000000000, 1, 2)")
+ .expect("sql");
+ let mut rows = slow.to_local_iterator(true).expect("to_local_iterator");
+ // Not read yet: no wait of the caller is for the execution.
+ assert_eq!(spark.running_operation_id(), None);
+ let started = Instant::now();
+ let interrupted = Arc::new(AtomicBool::new(false));
+ let watch_session = spark.clone();
+ let watch_interrupted = Arc::clone(&interrupted);
+ let watch: Arc<WaitWatch> = Arc::new(move || {
+ if started.elapsed() < Duration::from_secs(2) ||
watch_interrupted.load(Ordering::SeqCst) {
+ return Watch::Continue;
+ }
+ match watch_session.running_operation_id() {
+ Some(operation_id) => {
+ watch_interrupted.store(true, Ordering::SeqCst);
+ let session = watch_session.clone();
+ Watch::Interrupt(Box::pin(async move {
+ let _ =
session.interrupt_operation_async(&operation_id).await;
+ }))
+ }
+ None => Watch::Continue,
+ }
+ });
+ let outcome = with_wait_watch(watch, || rows.next());
+ assert!(
+ matches!(outcome, Some(Err(_))),
+ "the cancelled execution returned a batch"
+ );
+ assert!(
+ interrupted.load(Ordering::SeqCst),
+ "the caller's wait was not for the execution"
+ );
+ assert!(started.elapsed() < Duration::from_secs(30));
+ drop(rows);
+ let count = spark
+ .sql("SELECT * FROM range(3)")
+ .map_err(Box::new)
+ .and_then(|df| df.count().map_err(Box::new))
+ .expect("count");
+ assert_eq!(count, 3);
+}
+
#[test]
fn interrupting_the_wait_cancels_the_execution_of_the_calling_thread() {
use std::sync::atomic::{AtomicBool, Ordering};
diff --git a/python/tests/_mock_connect_server.py
b/python/tests/_mock_connect_server.py
index 2f23d65a..689cb188 100644
--- a/python/tests/_mock_connect_server.py
+++ b/python/tests/_mock_connect_server.py
@@ -307,6 +307,7 @@ def serve(connection):
self.plan_compression_lookups = 0
self.config_failure = None
self.block_config = False
+ self.plan_compression_lookup_delay = 0
self.rpc_events = []
self.set_confs = []
self.clone_requests = []
@@ -458,6 +459,8 @@ def serve(connection):
plan_compression_lookups = 0
config_failure = None
block_config = False
+ # The seconds that the plan compression lookup of the first plan of a
session takes.
+ plan_compression_lookup_delay = 0
rpc_events = []
set_confs = []
@@ -671,11 +674,15 @@ def serve(connection):
12, operation_id
)
yield header + message_field(13, "r1") + self.execute_payload
- if block_result_complete and not response_gate.wait(30):
- context.abort(
- grpc.StatusCode.DEADLINE_EXCEEDED,
- "ResultComplete was not released by the test",
- )
+ if block_result_complete:
+ released = self.wait_for_response(response_gate, operation_id,
30)
+ if released == "interrupted":
+ context.abort(grpc.StatusCode.CANCELLED, "Operation has
been canceled")
+ if not released:
+ context.abort(
+ grpc.StatusCode.DEADLINE_EXCEEDED,
+ "ResultComplete was not released by the test",
+ )
result_complete_operations.append(operation_id)
yield header + message_field(13, "r2") + message_field(14, b"")
@@ -739,6 +746,10 @@ def serve(connection):
if not lookup:
self.config_requests.append(request)
self.rpc_events.append("config")
+ if lookup and self.plan_compression_lookup_delay:
+ # The plan compression lookup that PySpark makes on the first
plan, held for the
+ # seconds of the delay, as a slow server holds it.
+ time.sleep(self.plan_compression_lookup_delay)
if not lookup and self.block_config and not
self.response_gate.wait(5):
context.abort(
grpc.StatusCode.DEADLINE_EXCEEDED,
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 369d269e..29d385d5 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -3877,6 +3877,46 @@ print("count", spark.range(3).count())
assert lines[1:] == ["interrupted ids []", "count 3"], result.stdout
+def
test_sigint_interrupts_the_iterator_that_waits_and_not_a_held_one_as_pyspark():
+ # As PySpark's: a SIGINT during the next of an iterator interrupts the
operation that the next
+ # waits for, though another iterator that was started later is alive and
half-consumed. The
+ # held iterator still yields its next row, and the waiting one is
cancelled at once, not when
+ # its slow partitions end.
+ import subprocess
+ import sys
+
+ remote = os.environ.get("SPARK_REMOTE")
+ if not remote:
+ pytest.skip("SPARK_REMOTE is required for live-server tests")
+ result = subprocess.run([sys.executable, "-c", """
+import os, signal, threading, time
+from pyspark.sql import SparkSession, functions as F
+spark = SparkSession.builder.remote(%r).getOrCreate()
+# Partition 0 returns at once; partitions 1 and 2 sleep 20 s on the server.
+a = spark.range(0, 3, 1, 3).select(
+ F.expr("reflect('java.lang.Thread', 'sleep', case when id = 0 then 0L else
20000L end)")
+ .alias("x"), "id")
+ia = a.toLocalIterator()
+print("a", next(ia).id, flush=True)
+ib = spark.range(0, 5, 1, 1).toLocalIterator()
+print("b", next(ib).id, flush=True)
+threading.Timer(2.0, lambda: os.kill(os.getpid(), signal.SIGINT)).start()
+started = time.monotonic()
+try:
+ next(ia)
+ print("next returned", flush=True)
+except KeyboardInterrupt:
+ print("interrupted after %%.1f" %% (time.monotonic() - started),
flush=True)
+print("b", next(ib).id, flush=True)
+""" % remote], env=dict(os.environ, TZ="UTC"), capture_output=True, text=True,
timeout=120)
+ assert result.returncode == 0, result.stderr
+ lines = result.stdout.splitlines()
+ assert lines[:2] == ["a 0", "b 0"], result.stdout
+ assert lines[2].startswith("interrupted after "), result.stdout
+ assert 2.0 <= float(lines[2].rsplit(" ", 1)[1]) < 6.0, result.stdout
+ assert lines[3:] == ["b 1"], result.stdout
+
+
def test_udfs_return_user_defined_types_of_main_as_pyspark():
# As PySpark's: a UDT that __main__ defines, of parameters, is a UDF
return type, as
# cloudpickle sends its class by value and its state to the worker. In a
new
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 0831d1d6..236bcf70 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -17170,6 +17170,152 @@ def
test_exception_of_a_signal_handler_is_raised_by_collect_as_pyspark(mock_conn
assert len(service.interrupt_requests) == 1
+def _two_row_range_results(service):
+ # The result of each range: two rows in one Arrow batch, which the
iterators read from the
+ # buffer of the batch before they wait for the next response.
+ import pyarrow as pa
+
+ table = pa.table({"id": pa.array([0, 1], pa.int64())})
+ sink = pa.BufferOutputStream()
+ with pa.ipc.new_stream(sink, table.schema) as writer:
+ writer.write_table(table)
+ # ExecutePlanResponse.schema=7 and arrow_batch=2: ArrowBatch.row_count=1,
data=2.
+ service.execute_payload = message_field(7, struct_schema("id")) +
message_field(
+ 2, varint_field(1, table.num_rows) + message_field(2,
sink.getvalue().to_pybytes()))
+
+
+def
test_sigint_interrupts_the_iterator_that_waits_and_not_a_held_one(mock_connect):
+ # As PySpark's: the signal interrupts the operation of the iterator whose
next waits for the
+ # server, even though another iterator that was started after it is alive
and half-consumed.
+ # That other iterator goes on, and the interrupted one raises
KeyboardInterrupt at once.
+ import signal
+ import threading
+
+ spark, service = mock_connect
+ _two_row_range_results(service)
+ service.block_result_complete = True
+ waiting = spark.range(2).toLocalIterator()
+ assert next(waiting).id == 0
+ service.block_result_complete = False
+ held = spark.range(2).toLocalIterator()
+ assert next(held).id == 0
+ assert next(waiting).id == 1
+ timer = threading.Timer(0.3, os.kill, (os.getpid(), signal.SIGINT))
+ started = time.monotonic()
+ timer.start()
+ try:
+ with pytest.raises(KeyboardInterrupt):
+ next(waiting)
+ finally:
+ timer.cancel()
+ service.release_response()
+ assert time.monotonic() - started < 3
+ # ExecutePlanRequest.operation_id=6, of the execution of the waiting
iterator, which is the
+ # last one that was started; InterruptRequest.operation_id=6.
+ operation_id = parse_message(service.execute_requests[-2]).get(6, [b""])[0]
+ [interrupt] = service.interrupt_requests
+ assert parse_message(interrupt)[6] == [operation_id]
+ # The held iterator still yields its next row.
+ assert next(held).id == 1
+
+
+def
test_sigint_during_stop_with_an_unconsumed_iterator_raises_at_once(mock_connect):
+ # As PySpark's stop: the release of the session is a wait that no
execution of the caller
+ # stands behind, so a signal ends it at once, though an iterator of the
caller is alive and
+ # half-consumed. The iterator is not interrupted, and the session stays
open.
+ import signal
+ import threading
+
+ spark, service = mock_connect
+ _two_row_range_results(service)
+ held = spark.range(2).toLocalIterator()
+ assert next(held).id == 0
+ service.release_session_blocked = True
+ timer = threading.Timer(0.3, os.kill, (os.getpid(), signal.SIGINT))
+ started = time.monotonic()
+ timer.start()
+ try:
+ with pytest.raises(KeyboardInterrupt):
+ spark.stop()
+ finally:
+ timer.cancel()
+ assert time.monotonic() - started < 3
+ assert not spark.is_stopped
+ assert service.interrupt_requests == []
+ service.release_session_blocked = False
+ service.release_session_release()
+ spark.stop()
+ assert spark.is_stopped
+ assert next(held).id == 1
+
+
+def
test_sigint_during_stop_with_a_registered_listener_raises_at_once(mock_connect):
+ # As PySpark's stop, with a StreamingQueryListener registered from this
thread: its
+ # subscription is an execution of the listener bus, which a wait of this
thread does not wait
+ # for, so a signal ends the release of the session at once, and the
session stays open.
+ 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
+ spark.streams.addListener(Listener())
+ assert service.wait_listener_registration(1)
+ service.release_session_blocked = True
+ timer = threading.Timer(0.3, os.kill, (os.getpid(), signal.SIGINT))
+ started = time.monotonic()
+ timer.start()
+ try:
+ with pytest.raises(KeyboardInterrupt):
+ spark.stop()
+ finally:
+ timer.cancel()
+ assert time.monotonic() - started < 3
+ assert not spark.is_stopped
+ service.release_session_blocked = False
+ service.release_session_release()
+ spark.stop()
+ assert spark.is_stopped
+
+
+def
test_sigint_during_the_plan_compression_lookup_interrupts_the_first_execution(mock_connect):
+ # As PySpark's, where a signal that arrives while the call waits for the
plan compression
+ # lookup of its first plan is raised when the lookup returns, so no
execution starts. Here
+ # the execution that the call starts after the lookup is interrupted at
once instead: the
+ # signal is kept until an execution is in flight, and the call ends
promptly.
+ import signal
+ import threading
+
+ spark, service = mock_connect
+ service.plan_compression_lookup_delay = 1.0
+ service.block_execute = True
+ timer = threading.Timer(0.3, os.kill, (os.getpid(), signal.SIGINT))
+ started = time.monotonic()
+ timer.start()
+ try:
+ with pytest.raises(KeyboardInterrupt):
+ spark.range(3).collect()
+ finally:
+ timer.cancel()
+ service.release_response()
+ assert time.monotonic() - started < 3
+ assert len(service.interrupt_requests) == 1
+
+
def test_connect_registry_sends_auto_cdc_define_flow(mock_connect):
from pyspark import pipelines as dp
from pyspark.pipelines.graph_element_registry import
graph_element_registration_context
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]