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 ad9dbfab [SPARK-61407][CONNECT][PYTHON] Let Ctrl-C end a call that 
waits for an unreachable or retrying server, in the Python client as PySpark 
does
ad9dbfab is described below

commit ad9dbfabc11310e4b2b0e1fcb4cdcaf1dd7dfacf
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 06:16:45 2026 +0900

    [SPARK-61407][CONNECT][PYTHON] Let Ctrl-C end a call that waits for an 
unreachable or retrying server, in the Python client as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61407](https://issues.apache.org/jira/browse/SPARK-61407): a 
follow-up of #455 (SPARK-61259), #457 (SPARK-61353) and #477 (SPARK-61388). A 
Ctrl-C ends a call that waits for a server that does not answer, as PySpark 
does:
    
    - **Abort levels** (`crates/spark-connect-core/src/runtime.rs`): the wait 
of an interruptible call keeps a watch of its abort level, which the new 
`until_abort` races a future against.
      - The first signal while an execution is in flight interrupts the 
execution, as before, and ends the retry backoffs, the unanswered RPC attempts 
and the reattach backoffs at once, as PySpark's `Retrying` sleep and grpc's 
signal check raise. A streaming read still goes on until the server cancels it.
      - A signal while no execution is in flight, or a second signal after the 
interrupt, ends every wait, including an interrupt that is itself retrying. 
Before, `Abort` was ignored for these waits, and the signals were no longer 
checked after the interrupt was sent.
    - **Client** (`client.rs`): the attempts and backoffs of `with_retry`, the 
reattach loop, the backoff of the artifact upload and the stream read of 
`ReattachableResponseStream::message` end when their wait is aborted, with the 
new `wait_aborted()` error, which the signal's exception replaces. The backoffs 
keep the server's `RetryInfo` delay of #480. An aborted plan compression lookup 
is not cached as a result.
    - **The backoff before a reattach** that #488 (SPARK-61415) added, for a 
stream that fails after a response (the server's `RetryInfo` delay if any), 
ends with a signal too.
    - **Prefetch** (`dataframe.rs`): the caller's wait for a batch of the task 
ends at the first signal, and dropping the receiver stops the task.
    - **A done call with a signal** (`interrupt.rs`, `errors.rs`): when a 
signal ends the call and a progress handler's done call raised, that exception 
is raised instead of `KeyboardInterrupt`, with the `KeyboardInterrupt` as its 
`__context__`, as PySpark's `progress.finish()` runs in its `except 
KeyboardInterrupt`. Its exception is released from the core's callbacks.
    
    ### Why are the changes needed?
    
    `spark.range(1).collect()` on `sc://127.0.0.1:1` ignored Ctrl-C for the 
whole retry budget, about 10 minutes: with SIGINTs at 2, 4, 6 and 8 s the call 
was still blocked at 30 s, where PySpark raises `KeyboardInterrupt` at 2 s from 
its retry sleep. The same held for an `ExecutePlan` that the server answers 
`UNAVAILABLE`, and for an interrupt that is retried: a second Ctrl-C did not 
end it. This is when users press Ctrl-C: a wrong URL, a server that is down or 
restarting, or a dropped n [...]
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. A Ctrl-C during a call to an unreachable or unavailable server raises 
`KeyboardInterrupt` promptly, a second Ctrl-C ends a retried interrupt, and a 
progress handler's done-call error during a signal is raised with the 
`KeyboardInterrupt` as its context, as in PySpark.
    
    ### How was this patch tested?
    
    - A Rust unit test of the abort levels: `Abort` ends the `ABORT_ALL` waits, 
an `Interrupt` ends the `ABORT_RETRIES` waits and awaits the interrupt, and 
without a watch the future is awaited as it is.
    - Offline tests with the mock server: an `UNAVAILABLE` execute that is 
retried raises within 3 s of the SIGINT; a second SIGINT ends an interrupt that 
the server answers `UNAVAILABLE`; a SIGINT during the plan compression lookup 
raises at once with no execution; and a progress handler's done-call error is 
raised with the `KeyboardInterrupt` as its context.
    - An offline test of a stream that fails after a response with a 5 s 
`RetryInfo` delay: a SIGINT at 1 s raises within 3 s, with no reattach (5.4 s 
without the wrap of that backoff). The mock server can fail a stream after its 
responses, with a `RetryInfo` delay, and records the ReattachExecute requests.
    - A subprocess test against `sc://127.0.0.1:1`, with no server: 
`KeyboardInterrupt` 2 to 4.5 s after the SIGINT at 2 s.
    - The three timing tests hang or fail without the change (61.9 s, and past 
a 100 s timeout).
    - `cargo test -p apache-spark-connect -p apache-spark-connect-core 
--release --lib`, the `--no-run` builds, `cargo fmt --check`, 
`scripts/audit_no_stubs.sh`, the full offline drop-in suite, and the SIGINT, 
prefetch and local iterator e2e tests and the Rust 
`e2e_session_catalog`/`e2e_dataframe` against a Spark 4.3.0 server.
    
    ### 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 #491 from HyukjinKwon/SPARK-61407-ctrl-c-unreachable-server.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/errors.rs          |   5 +-
 crates/pyspark-rs/src/interrupt.rs       |  41 ++++++---
 crates/spark-connect-core/src/client.rs  | 107 +++++++++++++++++++----
 crates/spark-connect-core/src/runtime.rs | 131 +++++++++++++++++++++++++---
 crates/spark-connect/src/dataframe.rs    |  11 ++-
 crates/spark-connect/src/progress.rs     |   6 +-
 python/tests/_mock_connect_server.py     |  66 ++++++++++----
 python/tests/test_dropin_offline.py      | 143 +++++++++++++++++++++++++++++--
 8 files changed, 442 insertions(+), 68 deletions(-)

diff --git a/crates/pyspark-rs/src/errors.rs b/crates/pyspark-rs/src/errors.rs
index 1584f936..c26e3ee9 100644
--- a/crates/pyspark-rs/src/errors.rs
+++ b/crates/pyspark-rs/src/errors.rs
@@ -228,8 +228,9 @@ fn callback_id(err: &SparkError) -> Option<u64> {
     err.params.get("callback_id")?.parse::<u64>().ok()
 }
 
-/// The exception of the Python callback of `err`, if it is the error of one.
-fn callback_exception(err: &SparkError) -> Option<PyErr> {
+/// The exception of the Python callback of `err`, if it is the error of one, 
which is then
+/// released: the exception is raised by the caller instead of `err`.
+pub(crate) fn callback_exception(err: &SparkError) -> Option<PyErr> {
     let id = callback_id(err)?;
     CALLBACK_EXCEPTIONS
         .lock()
diff --git a/crates/pyspark-rs/src/interrupt.rs 
b/crates/pyspark-rs/src/interrupt.rs
index 8e4f69cb..7644aaaf 100644
--- a/crates/pyspark-rs/src/interrupt.rs
+++ b/crates/pyspark-rs/src/interrupt.rs
@@ -28,9 +28,6 @@ struct SignalWatch {
 
 impl SignalWatch {
     fn poll(&self) -> Watch {
-        if self.interrupted.load(Ordering::SeqCst) {
-            return Watch::Continue;
-        }
         {
             let mut error = self.error.lock().unwrap_or_else(|e| 
e.into_inner());
             if error.is_none() {
@@ -39,10 +36,14 @@ impl SignalWatch {
                     Ok(()) => return Watch::Continue,
                     Err(signal) => *error = Some(signal),
                 }
+            } else if self.interrupted.load(Ordering::SeqCst) {
+                // After the interrupt, a second signal ends the wait, as 
PySpark's wait does.
+                return match Python::attach(|py| py.check_signals()) {
+                    Ok(()) => Watch::Continue,
+                    Err(_) => Watch::Abort,
+                };
             }
         }
-        // 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);
@@ -64,11 +65,12 @@ impl SignalWatch {
 /// 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 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.
+/// The execution is interrupted only when a wait of the calling thread is for 
one. The waits
+/// that a signal ends at once, as PySpark's do (a retry sleep, or a call that 
the server does not
+/// answer): the retries and the RPCs of `f` that are not answered when the 
first signal arrives
+/// during an execution, and all of them when no execution is in flight, or 
after a second
+/// signal. A streaming execution is still read after the first one, until the 
server cancels it.
+/// A wait of `block_on_abortable` (the release of `stop()`) ends at once as 
well.
 ///
 /// An execution that `f` ran then raises for the metrics of an Observation 
that PySpark does
 /// not convert, as PySpark's does (`ObservedMetricsCheck`).
@@ -104,8 +106,23 @@ pub(crate) fn interruptible_outcome<T: Send, E: Send + 
Into<Box<SparkError>>>(
     };
     let output = py.detach(|| with_wait_watch(poll, f));
     let signal = watch.error.lock().unwrap_or_else(|e| e.into_inner()).take();
+    let output: Result<T, Box<SparkError>> = output.map_err(Into::into);
     match signal {
-        Some(error) => Err(error),
-        None => Ok(output.map_err(Into::into)),
+        Some(error) => {
+            // As PySpark's: the done call of a progress handler that raised 
while the signal ended
+            // the call replaces the KeyboardInterrupt, which becomes its 
context, as the done call
+            // runs in the `except KeyboardInterrupt` of PySpark's execution. 
Its exception is
+            // released from the core's callbacks, so that it is not left 
behind.
+            if let Err(err) = &output {
+                if let Some(done) = crate::errors::callback_exception(err) {
+                    // The context is set on the instance, as the implicit 
chaining of PySpark's
+                    // `except` clause sets it.
+                    let _ = done.value(py).setattr("__context__", 
error.value(py));
+                    return Err(done);
+                }
+            }
+            Err(error)
+        }
+        None => Ok(output),
     }
 }
diff --git a/crates/spark-connect-core/src/client.rs 
b/crates/spark-connect-core/src/client.rs
index 7d2f2d85..af08ea07 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -527,6 +527,21 @@ fn set_waiter(
     }
 }
 
+/// The class of the error of a wait that a signal of the process ended (see
+/// [`crate::runtime::until_abort`]).
+const WAIT_ABORTED: &str = "WAIT_ABORTED";
+
+/// The error of a wait, of an RPC or a retry, that a signal of the process 
ended: the signal's own
+/// exception is what the call raises.
+pub fn wait_aborted() -> SparkError {
+    SparkError::classed(SparkErrorKind::Connect, WAIT_ABORTED, &[])
+}
+
+/// Whether `error` is the error of a wait that a signal of the process ended.
+pub fn is_wait_aborted(error: &SparkError) -> bool {
+    error.error_class == WAIT_ABORTED
+}
+
 /// 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.
@@ -1084,7 +1099,14 @@ impl SparkConnectClient {
                 }
                 _ => PlanCompression::Disabled,
             },
-            Err(_) => PlanCompression::Disabled,
+            Err(error) => {
+                // An aborted lookup is not the answer of the server: nothing 
is kept, so the
+                // lookup is made again by the next plan.
+                if is_wait_aborted(&error) {
+                    return PlanCompression::Disabled;
+                }
+                PlanCompression::Disabled
+            }
         };
         *self
             .plan_compression
@@ -1296,12 +1318,27 @@ impl SparkConnectClient {
     {
         let mut state = RetryPolicyState::new(self.retry_policy.clone());
         loop {
-            match op().await {
+            // An attempt that is not answered ends with the signal that a 
wait of the caller
+            // takes, as PySpark's blocked call does.
+            let attempt =
+                match 
crate::runtime::until_abort(crate::runtime::ABORT_RETRIES, op()).await {
+                    Some(attempt) => attempt,
+                    None => return Err(wait_aborted()),
+                };
+            match attempt {
                 Ok(v) => return Ok(v),
                 Err(status) => {
                     if self.retry_policy.can_retry(&status) {
                         if let Some(wait_ms) = 
state.next_attempt(retry_delay_ms(&status)) {
-                            
tokio::time::sleep(std::time::Duration::from_millis(wait_ms)).await;
+                            // The backoff ends with a signal, as PySpark's 
`Retrying` sleep does.
+                            let backoff =
+                                
tokio::time::sleep(std::time::Duration::from_millis(wait_ms));
+                            if 
crate::runtime::until_abort(crate::runtime::ABORT_RETRIES, backoff)
+                                .await
+                                .is_none()
+                            {
+                                return Err(wait_aborted());
+                            }
                             // As the reference's `_stub`, through which each 
attempt goes: once
                             // the client is closed (its session stopped while 
the call waited),
                             // the retry raises NO_ACTIVE_SESSION and sends 
nothing.
@@ -2085,7 +2122,14 @@ impl SparkConnectClient {
                 Err(status) => {
                     if self.retry_policy.can_retry(&status) {
                         if let Some(wait_ms) = 
state.next_attempt(retry_delay_ms(&status)) {
-                            
tokio::time::sleep(std::time::Duration::from_millis(wait_ms)).await;
+                            let backoff =
+                                
tokio::time::sleep(std::time::Duration::from_millis(wait_ms));
+                            if 
crate::runtime::until_abort(crate::runtime::ABORT_RETRIES, backoff)
+                                .await
+                                .is_none()
+                            {
+                                return Err(wait_aborted());
+                            }
                             // As in `with_retry`: a closed client sends no 
more attempts.
                             self.ensure_open()?;
                             continue;
@@ -2416,11 +2460,20 @@ impl ReattachableResponseStream {
                     .await?;
                 continue;
             };
-            let next = match self.stream_deadline {
-                Some(deadline) => tokio::time::timeout_at(deadline, 
stream.message())
-                    .await
-                    .unwrap_or_else(|_| 
Err(tonic::Status::deadline_exceeded("Deadline Exceeded"))),
-                None => stream.message().await,
+            let deadline = self.stream_deadline;
+            let read = async {
+                match deadline {
+                    Some(deadline) => tokio::time::timeout_at(deadline, 
stream.message())
+                        .await
+                        .unwrap_or_else(|_| {
+                            Err(tonic::Status::deadline_exceeded("Deadline 
Exceeded"))
+                        }),
+                    None => stream.message().await,
+                }
+            };
+            let next = match 
crate::runtime::until_abort(crate::runtime::ABORT_ALL, read).await {
+                Some(next) => next,
+                None => return Err(self.fail(wait_aborted())),
             };
             match next {
                 Ok(Some(resp)) => {
@@ -2487,9 +2540,18 @@ impl ReattachableResponseStream {
                     // reattaching and is the error once the policy's retries 
are spent. Else a
                     // connection that keeps failing after the headers of each 
reattach is
                     // reattached at once, without end. As at the other 
retries, the server's
-                    // RetryInfo delay of the failure, if any, is the wait.
+                    // RetryInfo delay of the failure, if any, is the wait. 
The backoff ends with a
+                    // signal, as the reference's `Retrying` sleep does.
                     match retry_state.next_attempt(retry_delay_ms(&status)) {
-                        Some(wait_ms) => 
tokio::time::sleep(Duration::from_millis(wait_ms)).await,
+                        Some(wait_ms) => {
+                            let backoff = 
tokio::time::sleep(Duration::from_millis(wait_ms));
+                            if 
crate::runtime::until_abort(crate::runtime::ABORT_RETRIES, backoff)
+                                .await
+                                .is_none()
+                            {
+                                return Err(self.fail(wait_aborted()));
+                            }
+                        }
                         None => return 
Err(self.fail_with_status(status).await),
                     }
                     self.reattach(&mut retry_state, &mut retry_exception_since)
@@ -2514,10 +2576,17 @@ impl ReattachableResponseStream {
             if let Err(error) = self.client.ensure_open() {
                 return Err(self.fail(error));
             }
-            let opened = if self.execute_again {
-                self.open_execute_plan_again().await
-            } else {
-                self.open_reattach().await
+            let opened = match 
crate::runtime::until_abort(crate::runtime::ABORT_RETRIES, async {
+                if self.execute_again {
+                    self.open_execute_plan_again().await
+                } else {
+                    self.open_reattach().await
+                }
+            })
+            .await
+            {
+                Some(opened) => opened,
+                None => return Err(self.fail(wait_aborted())),
             };
             let status = match opened {
                 Ok(stream) => {
@@ -2548,7 +2617,13 @@ impl ReattachableResponseStream {
             }
             if self.retry_policy.can_retry(&status) {
                 if let Some(w) = 
retry_state.next_attempt(retry_delay_ms(&status)) {
-                    tokio::time::sleep(Duration::from_millis(w)).await;
+                    let backoff = tokio::time::sleep(Duration::from_millis(w));
+                    if 
crate::runtime::until_abort(crate::runtime::ABORT_RETRIES, backoff)
+                        .await
+                        .is_none()
+                    {
+                        return Err(self.fail(wait_aborted()));
+                    }
                     continue;
                 }
             }
diff --git a/crates/spark-connect-core/src/runtime.rs 
b/crates/spark-connect-core/src/runtime.rs
index 860b7c4a..2b6678fc 100644
--- a/crates/spark-connect-core/src/runtime.rs
+++ b/crates/spark-connect-core/src/runtime.rs
@@ -74,8 +74,59 @@ pub enum Watch {
 /// [`POLL_INTERVAL`] on the thread that waits.
 pub type WaitWatch = dyn Fn() -> Watch + Send + Sync;
 
+/// The level of [`until_abort`] that a wait reaches once the first signal of 
the process
+/// arrives while an execution of the wait is in flight: the retries, the 
backoffs and the RPCs
+/// that have not been answered end at once, as PySpark's retry sleeps raise 
KeyboardInterrupt,
+/// while the responses of a streaming execution are still read, so that the 
server's
+/// cancellation of it ends them.
+pub const ABORT_RETRIES: u8 = 1;
+
+/// The level of [`until_abort`] that every wait reaches, when a signal 
arrives while no execution
+/// of the wait is in flight, or a second signal arrives after the interrupt 
of the execution.
+pub const ABORT_ALL: u8 = 2;
+
 thread_local! {
     static WAIT_WATCH: RefCell<Option<Arc<WaitWatch>>> = const { 
RefCell::new(None) };
+    /// The abort level of the wait that the calling thread runs, see 
[`until_abort`].
+    static WAIT_ABORT: RefCell<Option<tokio::sync::watch::Receiver<u8>>> =
+        const { RefCell::new(None) };
+}
+
+/// Runs the abort level of the wait of [`drive`] on this thread, until it 
drops.
+struct AbortScope(Option<tokio::sync::watch::Receiver<u8>>);
+
+impl AbortScope {
+    fn enter(receiver: tokio::sync::watch::Receiver<u8>) -> Self {
+        AbortScope(WAIT_ABORT.with(|abort| abort.replace(Some(receiver))))
+    }
+}
+
+impl Drop for AbortScope {
+    fn drop(&mut self) {
+        let previous = self.0.take();
+        WAIT_ABORT.with(|abort| *abort.borrow_mut() = previous);
+    }
+}
+
+/// `f`, which a wait of the calling thread ends at once, dropping it 
unfinished, when the wait
+/// reaches `level` (see [`ABORT_RETRIES`] and [`ABORT_ALL`]): None then, else 
the output of `f`.
+/// Outside a wait that a watch polls, `f` is awaited as it is.
+pub async fn until_abort<F: std::future::Future>(level: u8, f: F) -> 
Option<F::Output> {
+    let receiver = WAIT_ABORT.with(|abort| abort.borrow().clone());
+    let Some(mut receiver) = receiver else {
+        return Some(f.await);
+    };
+    tokio::pin!(f);
+    tokio::select! {
+        biased;
+        _ = async {
+            // A wait whose sender is gone is not aborted by it.
+            if receiver.wait_for(|reached| *reached >= level).await.is_err() {
+                std::future::pending::<()>().await;
+            }
+        } => None,
+        output = &mut f => Some(output),
+    }
 }
 
 /// Run `f` on this thread, with `watch` called by the waits for the server 
that `f` makes on this
@@ -151,31 +202,62 @@ async fn watched_abortable<F: Future>(f: F, watch: 
Arc<WaitWatch>) -> Option<F::
 /// Drive `f` on the shared runtime, polling `watch` (if any) as the wait goes 
on.
 fn drive<F: Future>(f: F, watch: Option<Arc<WaitWatch>>) -> F::Output {
     match watch {
-        Some(watch) => get_runtime().block_on(watched(f, watch)),
+        Some(watch) => {
+            let (abort, receiver) = tokio::sync::watch::channel(0_u8);
+            let _scope = AbortScope::enter(receiver);
+            get_runtime().block_on(watched(f, watch, abort))
+        }
         None => get_runtime().block_on(f),
     }
 }
 
-/// `f`, polled as it is, and `watch` called every [`POLL_INTERVAL`] until it 
returns an interrupt,
-/// which is spawned once. `f` is driven to its end, and the interrupt is 
awaited with it, so that
-/// the cleanup of `f` runs as the server ends the execution.
-async fn watched<F: Future>(f: F, watch: Arc<WaitWatch>) -> F::Output {
+/// `f`, polled as it is, and `watch` called every [`POLL_INTERVAL`]. The 
first interrupt that it
+/// returns is spawned, and the wait reaches [`ABORT_RETRIES`]: `f` is driven 
on, and the interrupt
+/// is awaited with it, so that the cleanup of `f` runs as the server ends the 
execution. A wait
+/// that `watch` aborts reaches [`ABORT_ALL`], which ends the waits of `f` 
that [`until_abort`]
+/// covers, and the interrupt that is still running. The polls go on after an 
interrupt, so that
+/// a second signal aborts the wait.
+async fn watched<F: Future>(
+    f: F,
+    watch: Arc<WaitWatch>,
+    abort: tokio::sync::watch::Sender<u8>,
+) -> F::Output {
     tokio::pin!(f);
     let mut ticks = tokio::time::interval(POLL_INTERVAL);
     let mut interrupt: Option<tokio::task::JoinHandle<()>> = None;
     loop {
         tokio::select! {
             output = &mut f => {
-                if let Some(interrupt) = interrupt {
-                    let _ = interrupt.await;
+                // The interrupt is awaited, and a second signal, polled 
meanwhile, ends the wait
+                // of it: the interrupt is then cancelled.
+                if let Some(mut interrupt) = interrupt {
+                    loop {
+                        tokio::select! {
+                            _ = &mut interrupt => break,
+                            _ = ticks.tick() => {
+                                if let Watch::Abort = watch() {
+                                    abort.send_replace(ABORT_ALL);
+                                    interrupt.abort();
+                                    break;
+                                }
+                            }
+                        }
+                    }
                 }
                 return output;
             }
-            _ = ticks.tick(), if interrupt.is_none() => {
-                if let Watch::Interrupt(sent) = watch() {
-                    interrupt = Some(tokio::spawn(sent));
+            _ = ticks.tick() => match watch() {
+                Watch::Continue => {}
+                Watch::Interrupt(sent) => {
+                    abort.send_replace(ABORT_RETRIES);
+                    if interrupt.is_none() {
+                        interrupt = Some(tokio::spawn(sent));
+                    }
                 }
-            }
+                Watch::Abort => {
+                    abort.send_replace(ABORT_ALL);
+                }
+            },
         }
     }
 }
@@ -375,7 +457,7 @@ mod tests {
             })
         });
         assert_eq!(output, 9);
-        assert!(interrupted.load(Ordering::SeqCst));
+        assert!(interrupted.load(std::sync::atomic::Ordering::SeqCst));
     }
 
     #[test]
@@ -404,6 +486,31 @@ mod tests {
         assert_eq!(waited, 9);
     }
 
+    #[test]
+    fn test_until_abort_ends_the_waits_that_the_watch_aborts_at_their_level() {
+        // A wait of the watch's abort at ABORT_ALL ends at once, dropping its 
future unfinished.
+        let aborted = with_wait_watch(Arc::new(|| Watch::Abort), || {
+            block_on(until_abort(ABORT_ALL, std::future::pending::<u8>()))
+        });
+        assert_eq!(aborted, None);
+        // An interrupt reaches ABORT_RETRIES only: the retries end, and the 
interrupt is awaited.
+        let interrupted = Arc::new(std::sync::atomic::AtomicBool::new(false));
+        let flag = Arc::clone(&interrupted);
+        let retried = with_wait_watch(
+            Arc::new(move || {
+                let flag = Arc::clone(&flag);
+                Watch::Interrupt(Box::pin(async move {
+                    flag.store(true, std::sync::atomic::Ordering::SeqCst);
+                }))
+            }),
+            || block_on(until_abort(ABORT_RETRIES, 
std::future::pending::<u8>())),
+        );
+        assert_eq!(retried, None);
+        assert!(interrupted.load(std::sync::atomic::Ordering::SeqCst));
+        // Outside a watch, a future is awaited as it is.
+        assert_eq!(block_on(until_abort(ABORT_ALL, async { 8 })), Some(8));
+    }
+
     #[test]
     fn test_with_wait_watch_restores_the_enclosing_watch() {
         let outer: Arc<WaitWatch> = Arc::new(|| Watch::Continue);
diff --git a/crates/spark-connect/src/dataframe.rs 
b/crates/spark-connect/src/dataframe.rs
index a3586d90..c58e7e29 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -241,9 +241,18 @@ impl LocalRowIterator {
             },
             RowSource::Prefetch { rx, task, wait } => {
                 // The caller waits for the batch of the task, which is a wait 
for the execution.
+                // The task has no wait of its own that a signal aborts, so 
the caller ends its
+                // wait for the batch at the first signal, as PySpark's retry 
sleeps do, and
+                // dropping the receiver stops the task.
                 let batch = {
                     let _waiting = wait.waiting();
-                    block_on(rx.recv())
+                    block_on(spark_connect_core::runtime::until_abort(
+                        spark_connect_core::runtime::ABORT_RETRIES,
+                        rx.recv(),
+                    ))
+                };
+                let Some(batch) = batch else {
+                    return 
Some(Err(spark_connect_core::client::wait_aborted().into()));
                 };
                 if batch.is_none() {
                     // The channel closed: the task ended, or it panicked, 
which then drops its
diff --git a/crates/spark-connect/src/progress.rs 
b/crates/spark-connect/src/progress.rs
index aefc09b3..5adb3f54 100644
--- a/crates/spark-connect/src/progress.rs
+++ b/crates/spark-connect/src/progress.rs
@@ -133,7 +133,11 @@ impl ProgressTracker {
         match self.finish() {
             Ok(()) => error,
             Err(done) => {
-                hand_over(UnreturnedError::Replaced { error, done: &done });
+                // The error of a wait that a signal ended is not one that a 
caller returns: the
+                // signal's exception replaces it, so nothing is handed over.
+                if !spark_connect_core::client::is_wait_aborted(&error) {
+                    hand_over(UnreturnedError::Replaced { error, done: &done 
});
+                }
                 done
             }
         }
diff --git a/python/tests/_mock_connect_server.py 
b/python/tests/_mock_connect_server.py
index db078d63..8a783fc0 100644
--- a/python/tests/_mock_connect_server.py
+++ b/python/tests/_mock_connect_server.py
@@ -243,6 +243,24 @@ def struct_schema(name="id"):
     return message_field(21, message_field(1, field))
 
 
+def retry_info_status(code, delay_ms):
+    """The grpc-status-details-bin of a failure of `code` with a RetryInfo of 
`delay_ms`."""
+    import grpc
+
+    # google.rpc: Status.code=1, message=2, details=3; Any.type_url=1, value=2;
+    # RetryInfo.retry_delay=1; Duration.seconds=1, nanos=2.
+    delay = varint_field(1, delay_ms // 1000) + varint_field(2, (delay_ms % 
1000) * 1_000_000)
+    return (
+        varint_field(1, getattr(grpc.StatusCode, code).value[0])
+        + message_field(2, "retry later")
+        + message_field(
+            3,
+            message_field(1, "type.googleapis.com/google.rpc.RetryInfo")
+            + message_field(2, message_field(1, delay)),
+        )
+    )
+
+
 def serve(connection):
     import grpc
 
@@ -291,6 +309,8 @@ def serve(connection):
             self.execute_payloads = None
             self.execute_failure = None
             self.execute_error = None
+            self.stream_failure = None
+            self.reattach_requests = []
             self.retry_info_failures = []
             # The InterruptRequests of each Interrupt, and the operations that 
they interrupt.
             self.interrupt_requests = []
@@ -308,6 +328,7 @@ def serve(connection):
             self.config_failure = None
             self.block_config = False
             self.plan_compression_lookup_delay = 0
+            self.interrupt_failure = None
             self.rpc_events = []
             self.set_confs = []
             self.clone_requests = []
@@ -424,6 +445,12 @@ def serve(connection):
         # streams one response of each, r1, r2, ..., instead of 
`execute_payload`.
         execute_payloads = None
         execute_failure = None
+        # With `stream_failure` set to a status code name, or a (name, delay 
in ms) of a failure
+        # with that RetryInfo delay, ExecutePlan streams its responses and 
then fails with it,
+        # before ResultComplete, as a dropped stream does. Each 
ReattachExecute is recorded in
+        # `reattach_requests`.
+        stream_failure = None
+        reattach_requests = []
         # With `execute_error` set to (message, reason, metadata), ExecutePlan 
fails as the
         # server does for an error that it raised: INTERNAL, with a 
google.rpc.Status of an
         # ErrorInfo of `reason` and `metadata` in grpc-status-details-bin.
@@ -464,6 +491,8 @@ def serve(connection):
         block_config = False
         # The seconds that the plan compression lookup of the first plan of a 
session takes.
         plan_compression_lookup_delay = 0
+        # The (code, message) of each Interrupt, which the server fails with, 
or None.
+        interrupt_failure = None
         rpc_events = []
         set_confs = []
 
@@ -628,20 +657,7 @@ def serve(connection):
                     )
             if self.retry_info_failures:
                 code, delay_ms = self.retry_info_failures.pop(0)
-                # google.rpc: Status.code=1, message=2, details=3; 
Any.type_url=1, value=2;
-                # RetryInfo.retry_delay=1; Duration.seconds=1, nanos=2.
-                delay = varint_field(1, delay_ms // 1000) + varint_field(
-                    2, (delay_ms % 1000) * 1_000_000
-                )
-                status = (
-                    varint_field(1, getattr(grpc.StatusCode, code).value[0])
-                    + message_field(2, "retry later")
-                    + message_field(
-                        3,
-                        message_field(1, 
"type.googleapis.com/google.rpc.RetryInfo")
-                        + message_field(2, message_field(1, delay)),
-                    )
-                )
+                status = retry_info_status(code, delay_ms)
                 context.set_trailing_metadata((("grpc-status-details-bin", 
status),))
                 context.abort(getattr(grpc.StatusCode, code), "retry later")
             if self.execute_failure:
@@ -681,6 +697,16 @@ def serve(connection):
             )
             for index, payload in enumerate(payloads, 1):
                 yield header + message_field(13, f"r{index}") + payload
+            if self.stream_failure:
+                code, delay_ms = (
+                    self.stream_failure
+                    if isinstance(self.stream_failure, tuple)
+                    else (self.stream_failure, None)
+                )
+                if delay_ms is not None:
+                    status = retry_info_status(code, delay_ms)
+                    context.set_trailing_metadata((("grpc-status-details-bin", 
status),))
+                context.abort(getattr(grpc.StatusCode, code), "stream dropped")
             if block_result_complete:
                 released = self.wait_for_response(response_gate, operation_id, 
30)
                 if released == "interrupted":
@@ -697,6 +723,11 @@ def serve(connection):
             # ConfigResponse.warnings=3, of `config_warnings`.
             return b"".join(message_field(3, warning) for warning in 
self.config_warnings)
 
+        def reattach_execute(self, request, context):
+            self.reattach_requests.append(request)
+            # ExecutePlanResponse.result_complete=14.
+            yield message_field(14, b"")
+
         def release_execute(self, request, context):
             self.release_execute_requests.append(request)
             return b""
@@ -717,6 +748,9 @@ def serve(connection):
             # .session_id=1, interrupted_ids=2.
             fields = parse_message(request)
             self.interrupt_requests.append(request)
+            if self.interrupt_failure:
+                code, message = self.interrupt_failure
+                context.abort(getattr(grpc.StatusCode, code), message)
             if fields.get(4, [0])[0] != 3:
                 context.abort(grpc.StatusCode.UNIMPLEMENTED, "only Interrupt 
of an operation")
             operation_id = fields[6][0]
@@ -829,9 +863,7 @@ def serve(connection):
             "AnalyzePlan": 
grpc.unary_unary_rpc_method_handler(service.analyze),
             "ReleaseSession": 
grpc.unary_unary_rpc_method_handler(service.release_session),
             "ExecutePlan": 
grpc.unary_stream_rpc_method_handler(service.execute),
-            "ReattachExecute": grpc.unary_stream_rpc_method_handler(
-                lambda request, context: iter([message_field(14, b"")])
-            ),
+            "ReattachExecute": 
grpc.unary_stream_rpc_method_handler(service.reattach_execute),
             "ReleaseExecute": 
grpc.unary_unary_rpc_method_handler(service.release_execute),
             "FetchErrorDetails": 
grpc.unary_unary_rpc_method_handler(service.fetch_error_details),
             "Config": grpc.unary_unary_rpc_method_handler(service.config),
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 3b68b42a..433a9e04 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -17987,16 +17987,14 @@ def 
test_sigint_during_stop_with_a_registered_listener_raises_at_once(mock_conne
     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.
+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.
     import signal
     import threading
 
     spark, service = mock_connect
-    service.plan_compression_lookup_delay = 1.0
+    service.plan_compression_lookup_delay = 2.0
     service.block_execute = True
     timer = threading.Timer(0.3, os.kill, (os.getpid(), signal.SIGINT))
     started = time.monotonic()
@@ -18007,8 +18005,139 @@ def 
test_sigint_during_the_plan_compression_lookup_interrupts_the_first_executio
     finally:
         timer.cancel()
         service.release_response()
+    assert time.monotonic() - started < 1.5
+    assert service.execute_requests == []
+    assert service.interrupt_requests == []
+
+
+def 
test_sigint_ends_the_backoff_before_the_reattach_of_a_dropped_stream(mock_connect):
+    # As PySpark's: a stream that fails after a response is reattached after 
the backoff of the
+    # retry policy, here the server's RetryInfo delay of 5 s, as an attempt of 
its `Retrying`,
+    # and a signal ends that backoff at once, as it ends the reference's retry 
sleep.
+    import signal
+    import threading
+
+    spark, service = mock_connect
+    service.stream_failure = ("UNAVAILABLE", 5000)
+    timer = threading.Timer(1.0, os.kill, (os.getpid(), signal.SIGINT))
+    started = time.monotonic()
+    timer.start()
+    try:
+        with pytest.raises(KeyboardInterrupt):
+            spark.range(3).collect()
+    finally:
+        timer.cancel()
     assert time.monotonic() - started < 3
-    assert len(service.interrupt_requests) == 1
+    assert service.reattach_requests == []
+
+
+def 
test_sigint_while_an_unavailable_execute_is_retried_raises_keyboard_interrupt(mock_connect):
+    # As PySpark's: the retry sleep of an ExecutePlan that the server answers 
UNAVAILABLE raises
+    # KeyboardInterrupt at the first signal, instead of the whole retry budget.
+    import signal
+    import threading
+
+    spark, service = mock_connect
+    service.execute_failure = ("UNAVAILABLE", "server is unavailable")
+    timer = threading.Timer(0.5, os.kill, (os.getpid(), signal.SIGINT))
+    started = time.monotonic()
+    timer.start()
+    try:
+        with pytest.raises(KeyboardInterrupt):
+            spark.range(3).collect()
+    finally:
+        timer.cancel()
+        service.execute_failure = None
+    assert time.monotonic() - started < 3
+
+
+def 
test_second_sigint_ends_the_wait_for_an_interrupt_that_is_retried(mock_connect):
+    # As PySpark's: the first signal interrupts the operation, and the 
interrupt call is retried
+    # while the server is unavailable, so the call waits for it; a second 
signal raises
+    # KeyboardInterrupt out of that wait.
+    import signal
+    import threading
+
+    spark, service = mock_connect
+    service.block_execute = True
+    service.interrupt_failure = ("UNAVAILABLE", "server is unavailable")
+    first = threading.Timer(0.5, os.kill, (os.getpid(), signal.SIGINT))
+    second = threading.Timer(1.5, os.kill, (os.getpid(), signal.SIGINT))
+    started = time.monotonic()
+    first.start()
+    second.start()
+    try:
+        with pytest.raises(KeyboardInterrupt):
+            spark.range(3).collect()
+    finally:
+        first.cancel()
+        second.cancel()
+        service.interrupt_failure = None
+        service.release_response()
+    assert 1.5 <= time.monotonic() - started < 4
+    assert len(service.interrupt_requests) >= 1
+
+
+def 
test_sigint_raises_the_done_call_error_of_a_progress_handler_with_the_signal_as_context(
+    mock_connect,
+):
+    # As PySpark's: the progress handler's done call, made in the `except 
KeyboardInterrupt` of
+    # the execution, raises its own exception, which replaces the 
KeyboardInterrupt, with the
+    # KeyboardInterrupt as its context.
+    import signal
+    import threading
+
+    spark, service = mock_connect
+    stage = (varint_field(1, 7) + varint_field(2, 4) + varint_field(3, 1)
+             + varint_field(4, 1024) + varint_field(5, 0))
+    service.execute_payload = message_field(18, message_field(1, stage) + 
varint_field(2, 3))
+    service.block_result_complete = True
+
+    def handler(**kwargs):
+        if kwargs["done"]:
+            raise ValueError("done call failed")
+
+    spark.registerProgressHandler(handler)
+    timer = threading.Timer(0.5, os.kill, (os.getpid(), signal.SIGINT))
+    timer.start()
+    try:
+        with pytest.raises(ValueError, match="done call failed") as error:
+            spark.range(1).collect()
+    finally:
+        timer.cancel()
+        service.release_response()
+    assert isinstance(error.value.__context__, KeyboardInterrupt)
+
+
+def test_sigint_ends_a_call_to_an_unreachable_server_at_once_as_pyspark():
+    # As PySpark's: the Config lookup of the first plan of a session that no 
server answers is
+    # retried, and a signal raises KeyboardInterrupt from its retry sleep. No 
server is needed.
+    import subprocess
+    import sys
+
+    code = """
+import os, signal, threading, time
+from pyspark.sql import SparkSession
+spark = SparkSession.builder.remote("sc://127.0.0.1:1").getOrCreate()
+threading.Timer(2.0, lambda: os.kill(os.getpid(), signal.SIGINT)).start()
+started = time.monotonic()
+try:
+    spark.range(1).collect()
+    print("collect returned")
+except KeyboardInterrupt:
+    print("interrupted after", round(time.monotonic() - started, 1))
+"""
+    result = subprocess.run(
+        [sys.executable, "-c", code],
+        env=dict(os.environ, TZ="UTC"),
+        capture_output=True,
+        text=True,
+        timeout=60,
+    )
+    assert result.returncode == 0, result.stderr
+    lines = result.stdout.splitlines()
+    assert lines[-1].startswith("interrupted after "), result.stdout
+    assert 2.0 <= float(lines[-1].rsplit(" ", 1)[1]) < 4.5, result.stdout
 
 
 def test_connect_registry_sends_auto_cdc_define_flow(mock_connect):


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to