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 8aab0e75 [SPARK-61577][CONNECT] Stop the retries of an abortable wait
at its first interrupt, and retry the first response of an execution within one
retry budget, as PySpark does
8aab0e75 is described below
commit 8aab0e75c6f5f0c2087504c582d82aaeab7811d3
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 08:49:43 2026 +0900
[SPARK-61577][CONNECT] Stop the retries of an abortable wait at its first
interrupt, and retry the first response of an execution within one retry
budget, as PySpark does
### What changes were proposed in this pull request?
Two fixes in the retries of the Rust Spark Connect client core, from a
review of #536 and #541:
1. An abortable wait (`block_on_abortable`) now ends the retry backoffs of
its future at the first interrupt of the execution in flight, as the other
waits already do. Its drive enters an `AbortScope`, and `watched_abortable`
sends `ABORT_RETRIES` when its watch returns `Interrupt`. Before, the interrupt
was sent but a backoff inside the wait (for example the ReleaseSession release
of a `stop()` called while an execution is in flight on the same thread, such
as from a progress handler [...]
2. The first response of a reattachable execution now shares the retry
budget of the first ExecutePlan, instead of starting a fresh one: the first RPC
runs on a `Retrying` that the response stream keeps, and the first wait for a
response takes it. Later waits keep their own budgets.
### Why are the changes needed?
Both differ from PySpark 4.3.0
(`python/pyspark/sql/connect/client/retries.py`, `reattach.py` and `core.py`).
PySpark's retry sleep raises KeyboardInterrupt at the first signal. Its initial
ExecutePlan has no retry of its own: its error surfaces in the first
`_has_next`, whose single `Retrying` also covers the reattaches.
Before the fix, with `max_retries=3`, an execution whose ExecutePlan fails
twice and whose first response then fails made 3 ExecutePlan and 3
ReattachExecute calls, 6 in all, where the policy allows 4. After it: 3 and 1.
### Does this PR introduce _any_ user-facing change?
Yes, in retries: the first interrupt ends the retry backoff of an abortable
wait, and an execution's first response is retried within the budget of its
first request.
### How was this patch tested?
New Rust unit tests, each checked to fail without the fix:
-
`test_an_interrupt_ends_the_backoff_of_an_abortable_wait_as_the_first_signal_does`
(retries.rs): the backoff ends at the first interrupt; it timed out at 5 s
without the fix. It also checks that a future without backoffs still returns
its output after an interrupt.
- `the_first_response_shares_the_attempts_of_the_first_rpc_as_pyspark`
(client.rs, mock server): (ExecutePlan, ReattachExecute) calls are (3, 1), and
were (3, 3) without the fix.
The connect and connect-core lib tests, the connect-core integration tests,
the Rust e2e suites and the Python drop-in offline and e2e suites (against
Spark 4.3.0) pass, as do `cargo fmt`, `scripts/audit_no_stubs.sh` and ruff.
### 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 #577 from HyukjinKwon/SPARK-61577-abort-retries.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/spark-connect-core/src/client.rs | 218 ++++++++++++++++++++++++++++++-
crates/spark-connect-core/src/retries.rs | 64 ++++++++-
crates/spark-connect-core/src/runtime.rs | 20 ++-
3 files changed, 286 insertions(+), 16 deletions(-)
diff --git a/crates/spark-connect-core/src/client.rs
b/crates/spark-connect-core/src/client.rs
index b41d33dc..d8cad29b 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -1314,13 +1314,24 @@ impl SparkConnectClient {
/// Mirrors `pyspark.sql.connect.client.retries.Retrying` / `RetryPolicy`:
retry
/// `UNAVAILABLE` (and cursor-disconnect) per the policy, sleeping the
computed
/// backoff between attempts, then surface the last error.
- async fn with_retry<T, Fut, F>(&self, mut op: F) -> Result<T>
+ async fn with_retry<T, Fut, F>(&self, op: F) -> Result<T>
+ where
+ F: FnMut() -> Fut,
+ Fut: std::future::Future<Output = std::result::Result<T,
tonic::Status>>,
+ {
+ let mut retries =
Retrying::new(&self.retry_policy).ending_with_abort();
+ self.with_retry_in(&mut retries, op).await
+ }
+
+ /// As [`Self::with_retry`], whose attempts are those of `retries`, which
the caller keeps
+ /// for the wait that follows the call (see
[`ReattachableResponseStream`]).
+ async fn with_retry_in<T, Fut, F>(&self, retries: &mut Retrying, mut op:
F) -> Result<T>
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = std::result::Result<T,
tonic::Status>>,
{
use futures::FutureExt;
- self.with_attempts(|| {
+ self.with_attempts_in(retries, || {
// An attempt that is not answered ends with the signal that a
wait of the caller
// takes, as PySpark's blocked call does. A combinator rather than
an async block that
// awaits the call: such a block keeps the future of the call
twice, as what it
@@ -1346,7 +1357,20 @@ impl SparkConnectClient {
where
Fut: std::future::Future<Output = std::result::Result<T,
RetryError<SparkError>>>,
{
- let retries = Retrying::new(&self.retry_policy).ending_with_abort();
+ let mut retries =
Retrying::new(&self.retry_policy).ending_with_abort();
+ self.with_attempts_in(&mut retries, attempt).await
+ }
+
+ /// As [`Self::with_attempts`], whose attempts are those of `retries` (see
+ /// [`Self::with_retry_in`]).
+ async fn with_attempts_in<T, Fut>(
+ &self,
+ retries: &mut Retrying,
+ attempt: impl FnMut() -> Fut,
+ ) -> Result<T>
+ where
+ Fut: std::future::Future<Output = std::result::Result<T,
RetryError<SparkError>>>,
+ {
// 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.
@@ -1398,10 +1422,13 @@ impl SparkConnectClient {
);
let deadline = self.rpc_deadlines.reattachable_execute_plan;
let mut stream_deadline = None;
+ // The attempts of the first RPC are those of the first response too,
as the reference's
+ // first `_has_next` retries both (see `first_response_retries`).
+ let mut first_response_retries =
Retrying::new(&self.retry_policy).ending_with_abort();
let stream = {
// The first RPC is a wait of the caller for the execution.
let _waiting = inflight.waiting();
- self.with_retry(|| {
+ self.with_retry_in(&mut first_response_retries, || {
let request = clone_on_grown_stack(iter.request());
let mut req = with_deadline(Request::new(request), deadline);
self._attach_metadata(&mut req);
@@ -1432,6 +1459,7 @@ impl SparkConnectClient {
Ok(ReattachableResponseStream {
client: self.clone(),
retry_policy,
+ first_response_retries: Some(first_response_retries),
iter,
stream,
stream_deadline,
@@ -2335,6 +2363,11 @@ pub struct ReattachableResponseStream {
/// The client that started the execution, whose stub, headers and session
it uses.
client: SparkConnectClient,
retry_policy: RetryPolicy,
+ /// The retries of the first wait for a response, which carry on the
attempts of the first RPC
+ /// that started the execution: as the reference's first `_has_next`
retries the initial
+ /// ExecutePlan together with the reads of its first response, the
policy's attempts are shared
+ /// by both. Taken by that wait; the later waits have their own.
+ first_response_retries: Option<Retrying>,
iter: ExecutePlanResponseReattachableIterator,
/// The stream of the execution, or none to reattach before reading.
stream: Option<Streaming<ExecutePlanResponse>>,
@@ -2387,7 +2420,7 @@ impl SparkConnectClient {
// As the reference's, which goes through the stub of its iterator
rather than the
// `_stub` of the client: a release is retried whether or not the
client was closed.
let whatever_the_client = || Ok::<(),
std::convert::Infallible>(());
- let released = retrying(Retrying::new(&policy),
whatever_the_client, || {
+ let released = retrying(&mut Retrying::new(&policy),
whatever_the_client, || {
let mut req = Request::new(request.clone());
*req.metadata_mut() = metadata.clone();
let mut stub = stub.clone();
@@ -2451,7 +2484,10 @@ impl ReattachableResponseStream {
// policy's elapsed time, starts at the first deadline that passes,
the deadline of the
// initial ExecutePlan included, and the reattaches after a deadline
or an unknown
// execution are its retries.
- let mut retrying =
Retrying::new(&self.retry_policy).ending_with_abort();
+ let mut retrying = match self.first_response_retries.take() {
+ Some(retries) => retries,
+ None => Retrying::new(&self.retry_policy).ending_with_abort(),
+ };
if self.stream.is_none() && !retrying.retry_at_once() {
// The initial ExecutePlan passed its deadline, a RetryException
that fails at once
// when the bound of the retries has passed, as it has when the
bound is 0.
@@ -3167,6 +3203,176 @@ mod tests {
}
}
+ /// A loopback service of ExecutePlan and ReattachExecute only. Its first
`execute_failures`
+ /// ExecutePlan calls answer UNAVAILABLE; a later one opens a stream whose
first response is
+ /// UNAVAILABLE, and every ReattachExecute answers UNAVAILABLE. The calls
of each are counted.
+ struct FirstResponseCalls {
+ execute_plan: std::sync::atomic::AtomicUsize,
+ reattach: std::sync::atomic::AtomicUsize,
+ execute_failures: usize,
+ }
+
+ #[derive(Clone)]
+ struct FirstResponseService(std::sync::Arc<FirstResponseCalls>);
+
+ impl tonic::server::NamedService for FirstResponseService {
+ const NAME: &'static str = "spark.connect.SparkConnectService";
+ }
+
+ impl
tonic::codegen::Service<tonic::codegen::http::Request<tonic::body::Body>>
+ for FirstResponseService
+ {
+ type Response = tonic::codegen::http::Response<tonic::body::Body>;
+ type Error = std::convert::Infallible;
+ type Future = tonic::codegen::BoxFuture<Self::Response, Self::Error>;
+
+ fn poll_ready(
+ &mut self,
+ _: &mut std::task::Context<'_>,
+ ) -> std::task::Poll<std::result::Result<(), Self::Error>> {
+ std::task::Poll::Ready(Ok(()))
+ }
+
+ fn call(
+ &mut self,
+ request: tonic::codegen::http::Request<tonic::body::Body>,
+ ) -> Self::Future {
+ let state = self.0.clone();
+ Box::pin(async move {
+ // Each method has a codec of its own, for the message it
decodes.
+ match request.uri().path() {
+ "/spark.connect.SparkConnectService/ExecutePlan" => {
+ let mut grpc =
tonic::server::Grpc::new(tonic_prost::ProstCodec::default());
+ Ok(grpc.server_streaming(ExecutePlanRpc(state),
request).await)
+ }
+ "/spark.connect.SparkConnectService/ReattachExecute" => {
+ let mut grpc =
tonic::server::Grpc::new(tonic_prost::ProstCodec::default());
+ Ok(grpc
+ .server_streaming(ReattachExecuteRpc(state),
request)
+ .await)
+ }
+ _ => Ok(tonic::codegen::http::Response::builder()
+ .status(200)
+ .header("grpc-status", "12")
+ .header("content-type", "application/grpc")
+ .body(tonic::body::Body::empty())
+ .unwrap()),
+ }
+ })
+ }
+ }
+
+ struct ExecutePlanRpc(std::sync::Arc<FirstResponseCalls>);
+
+ impl tonic::server::ServerStreamingService<ExecutePlanRequest> for
ExecutePlanRpc {
+ type Response = spark_connect_proto::ExecutePlanResponse;
+ type ResponseStream = futures::stream::Iter<
+ std::vec::IntoIter<std::result::Result<Self::Response,
tonic::Status>>,
+ >;
+ type Future =
+ tonic::codegen::BoxFuture<tonic::Response<Self::ResponseStream>,
tonic::Status>;
+
+ fn call(&mut self, _request: tonic::Request<ExecutePlanRequest>) ->
Self::Future {
+ let state = self.0.clone();
+ Box::pin(async move {
+ let call = state
+ .execute_plan
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ if call < state.execute_failures {
+ return Err(tonic::Status::unavailable("the server is
restarting"));
+ }
+ let lost = tonic::Status::unavailable("the first response is
lost");
+
Ok(tonic::Response::new(futures::stream::iter(vec![Err(lost)])))
+ })
+ }
+ }
+
+ struct ReattachExecuteRpc(std::sync::Arc<FirstResponseCalls>);
+
+ impl
tonic::server::ServerStreamingService<spark_connect_proto::ReattachExecuteRequest>
+ for ReattachExecuteRpc
+ {
+ type Response = spark_connect_proto::ExecutePlanResponse;
+ type ResponseStream = futures::stream::Iter<
+ std::vec::IntoIter<std::result::Result<Self::Response,
tonic::Status>>,
+ >;
+ type Future =
+ tonic::codegen::BoxFuture<tonic::Response<Self::ResponseStream>,
tonic::Status>;
+
+ fn call(
+ &mut self,
+ _request:
tonic::Request<spark_connect_proto::ReattachExecuteRequest>,
+ ) -> Self::Future {
+ let state = self.0.clone();
+ Box::pin(async move {
+ state
+ .reattach
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Err(tonic::Status::unavailable("the server is restarting"))
+ })
+ }
+ }
+
+ /// The first response of an execution shares the attempts of its first
RPC, as the reference's
+ /// first `_has_next` does: an ExecutePlan that is unavailable twice, then
opens a stream whose
+ /// first response is unavailable, and a ReattachExecute that is
unavailable, make four calls
+ /// under the three retries of the policy. Each of the two waits having
its own budget would
+ /// make six.
+ #[tokio::test]
+ async fn
the_first_response_shares_the_attempts_of_the_first_rpc_as_pyspark() {
+ let calls = std::sync::Arc::new(FirstResponseCalls {
+ execute_plan: std::sync::atomic::AtomicUsize::new(0),
+ reattach: std::sync::atomic::AtomicUsize::new(0),
+ execute_failures: 2,
+ });
+ let listener =
tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let incoming = futures::stream::unfold(listener, |listener| async {
+ Some((listener.accept().await.map(|(socket, _)| socket), listener))
+ });
+ let service = FirstResponseService(calls.clone());
+ let server = tokio::spawn(async move {
+ tonic::transport::Server::builder()
+ .add_service(service)
+ .serve_with_incoming(incoming)
+ .await
+ .unwrap();
+ });
+ // `connect` reads the token of the environment too, so none is set
until it returns:
+ // another test may set one, which would make the channel TLS.
+ let env =
crate::channel::set_env(&[("SPARK_CONNECT_AUTHENTICATE_TOKEN", None)]);
+ let builder = ChannelBuilder::parse(&format!("sc://127.0.0.1:{}",
address.port())).unwrap();
+ let mut client = SparkConnectClient::connect(&builder).await.unwrap();
+ drop(env);
+ client.set_retry_policy(RetryPolicy {
+ max_retries: Some(3),
+ initial_backoff_ms: 1,
+ max_backoff_ms: Some(2),
+ ..RetryPolicy::default()
+ });
+
+ let mut stream = client
+ .execute_plan_reattachable(ExecutePlanRequest {
+ session_id: client.session_id().to_string(),
+ plan: Some(Plan {
+ op_type: Some(PlanOpType::Root(Default::default())),
+ }),
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ let failed = stream.message().await;
+ server.abort();
+ failed.expect_err("the first response is unavailable and the retries
are spent");
+ let execute_plan =
calls.execute_plan.load(std::sync::atomic::Ordering::SeqCst);
+ let reattach =
calls.reattach.load(std::sync::atomic::Ordering::SeqCst);
+ assert_eq!(
+ (execute_plan, reattach),
+ (3, 1),
+ "the first response retried outside the budget of the first RPC"
+ );
+ }
+
/// A loopback service of ReleaseSession only: its first `unavailable`
calls answer
/// UNAVAILABLE, the later ones succeed. `calls` counts every call.
struct ReleaseCalls {
diff --git a/crates/spark-connect-core/src/retries.rs
b/crates/spark-connect-core/src/retries.rs
index f75567a0..dadaeada 100644
--- a/crates/spark-connect-core/src/retries.rs
+++ b/crates/spark-connect-core/src/retries.rs
@@ -384,7 +384,9 @@ pub(crate) enum RetryError<E> {
}
/// Makes the attempts of a call under the policy of `retrying` until one
succeeds or fails for
-/// good: a failed RPC is retried as [`Retrying::backoff`] decides, after its
wait.
+/// good: a failed RPC is retried as [`Retrying::backoff`] decides, after its
wait. The retries
+/// are the caller's, so that a call and the wait for the first response of
its execution can
+/// share their attempts (see [`crate::client::ReattachableResponseStream`]).
///
/// What differs between the calls is given rather than built in:
///
@@ -396,7 +398,7 @@ pub(crate) enum RetryError<E> {
/// - `attempt` fails with [`RetryError::Aborted`] for an error that is no
failed RPC, such as
/// the unreadable source of an upload, which ends the call as it is.
pub(crate) async fn retrying<T, E, Fut>(
- mut retrying: Retrying,
+ retrying: &mut Retrying,
mut before_retry: impl FnMut() -> Result<(), E>,
mut attempt: impl FnMut() -> Fut,
) -> Result<T, RetryError<E>>
@@ -1183,7 +1185,7 @@ mod tests {
let mut outcomes = outcomes.into_iter();
let mut checks = 0;
let result = retrying(
- Retrying::new(policy),
+ &mut Retrying::new(policy),
|| {
checks += 1;
Ok(())
@@ -1293,7 +1295,7 @@ mod tests {
async fn test_retrying_ends_with_the_error_of_the_check_before_a_retry() {
let mut attempts = 0;
let result: Result<(), _> = retrying(
- Retrying::new(&quick_policy(5)),
+ &mut Retrying::new(&quick_policy(5)),
|| Err("closed"),
|| {
attempts += 1;
@@ -1367,7 +1369,7 @@ mod tests {
let result: Result<(), RetryError<&'static str>> =
with_wait_watch(std::sync::Arc::new(|| Watch::Abort), || {
block_on(retrying(
- Retrying::new(&slow_policy()).ending_with_abort(),
+ &mut Retrying::new(&slow_policy()).ending_with_abort(),
|| panic!("no check before a retry that is not made"),
|| {
attempts += 1;
@@ -1379,6 +1381,58 @@ mod tests {
assert_eq!(attempts, 1);
}
+ #[test]
+ fn
test_an_interrupt_ends_the_backoff_of_an_abortable_wait_as_the_first_signal_does()
{
+ // The release of `stop()` backs off inside `block_on_abortable`,
which an interrupt of
+ // the execution in flight leaves running. The first interrupt ends
the backoff at once,
+ // as PySpark's sleep raises KeyboardInterrupt, and a future without
backoffs is not ended
+ // by it. The wait runs on a thread of its own, so that a backoff that
is not ended fails
+ // the test at its timeout rather than after the whole minute.
+ use crate::runtime::{block_on_abortable, with_wait_watch, Watch};
+ use std::sync::atomic::{AtomicBool, Ordering};
+ let (sender, receiver) = std::sync::mpsc::channel();
+ std::thread::spawn(move || {
+ let first = std::sync::Arc::new(AtomicBool::new(true));
+ let watch: std::sync::Arc<crate::runtime::WaitWatch> =
std::sync::Arc::new(move || {
+ if first.swap(false, Ordering::SeqCst) {
+ Watch::Interrupt(Box::pin(async {}))
+ } else {
+ Watch::Continue
+ }
+ });
+ let ended = with_wait_watch(watch, || {
+ block_on_abortable(async {
+ let mut retrying =
Retrying::new(&slow_policy()).ending_with_abort();
+ retrying.backoff(&tonic::Status::unavailable("down")).await
+ })
+ });
+ let _ = sender.send(ended);
+ });
+ let ended = receiver
+ .recv_timeout(std::time::Duration::from_secs(5))
+ .expect("the interrupt did not end the backoff");
+ assert_eq!(ended, Some(Backoff::Aborted));
+
+ // A future that waits without backoffs is given its output after the
interrupt.
+ let watch: std::sync::Arc<crate::runtime::WaitWatch> =
std::sync::Arc::new({
+ let first = AtomicBool::new(true);
+ move || {
+ if first.swap(false, Ordering::SeqCst) {
+ Watch::Interrupt(Box::pin(async {}))
+ } else {
+ Watch::Continue
+ }
+ }
+ });
+ let kept = with_wait_watch(watch, || {
+ block_on_abortable(async {
+ tokio::time::sleep(crate::runtime::POLL_INTERVAL * 2).await;
+ 5
+ })
+ });
+ assert_eq!(kept, Some(5));
+ }
+
#[test]
fn
test_a_signal_does_not_end_the_backoff_of_retries_that_are_waited_whole() {
use crate::runtime::{block_on, with_wait_watch, Watch, POLL_INTERVAL};
diff --git a/crates/spark-connect-core/src/runtime.rs
b/crates/spark-connect-core/src/runtime.rs
index c16d883f..ba807c6a 100644
--- a/crates/spark-connect-core/src/runtime.rs
+++ b/crates/spark-connect-core/src/runtime.rs
@@ -173,7 +173,11 @@ where
let f = Box::pin(f);
let watch = WAIT_WATCH.with(|watch| watch.borrow().clone());
let drive = |f: Pin<Box<F>>| match watch {
- Some(watch) => get_runtime().block_on(watched_abortable(f, watch)),
+ Some(watch) => {
+ let (abort, receiver) = tokio::sync::watch::channel(0_u8);
+ let _scope = AbortScope::enter(receiver);
+ get_runtime().block_on(watched_abortable(f, watch, abort))
+ }
None => Some(get_runtime().block_on(f)),
};
match tokio::runtime::Handle::try_current() {
@@ -188,10 +192,15 @@ where
/// `f`, polled as it is, and `watch` called every [`POLL_INTERVAL`]: `None`
at once when it
/// returns [`Watch::Abort`], else the output of `f`. The first interrupt that
`watch` returns is
-/// spawned and awaited with `f`, as in [`watched`]. The polls go on after it,
so that a second
-/// signal ends the wait even while the interrupt hangs, and the running
interrupt is cancelled
-/// with the wait.
-async fn watched_abortable<F: Future>(f: F, watch: Arc<WaitWatch>) ->
Option<F::Output> {
+/// spawned and awaited with `f`, as in [`watched`], and the wait reaches
[`ABORT_RETRIES`], which
+/// ends the backoffs of `f` (see [`until_abort`]), as PySpark's retry sleeps
raise
+/// KeyboardInterrupt at the first signal. The polls go on after it, so that a
second signal ends
+/// the wait even while the interrupt hangs, and the running interrupt is
cancelled with the wait.
+async fn watched_abortable<F: Future>(
+ f: F,
+ watch: Arc<WaitWatch>,
+ abort: tokio::sync::watch::Sender<u8>,
+) -> Option<F::Output> {
tokio::pin!(f);
let mut ticks = tokio::time::interval(POLL_INTERVAL);
let mut interrupt: Option<tokio::task::JoinHandle<()>> = None;
@@ -223,6 +232,7 @@ async fn watched_abortable<F: Future>(f: F, watch:
Arc<WaitWatch>) -> Option<F::
return None;
}
Watch::Interrupt(sent) => {
+ abort.send_replace(ABORT_RETRIES);
if interrupt.is_none() {
interrupt = Some(tokio::spawn(sent));
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]