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 d2a3db1f [SPARK-61440][CONNECT] Make the retries of the calls of the
Spark Connect Rust client in one place, and do not panic on a stream deadline
too far to be a time
d2a3db1f is described below
commit d2a3db1fb6633b880c36f5c3cd0be19d3eefd7ce
Author: Liang-Chi Hsieh <[email protected]>
AuthorDate: Thu Nov 12 09:51:19 2026 +0900
[SPARK-61440][CONNECT] Make the retries of the calls of the Spark Connect
Rust client in one place, and do not panic on a stream deadline too far to be a
time
### What changes were proposed in this pull request?
This PR is #508 by viirya (commit cf0aa70, unchanged) plus one commit so
that CI passes. `with_retry` now awaits its attempt through `FutureExt::map`
instead of an async block that captures the future of the RPC and awaits it.
Such a block keeps that future twice, which made every call future of the
client about half again as large (`analyze_plan` 75 KB -> 110 KB in a release
build). That overflowed the stack of `deep_request_stack_tests` (SPARK-61400)
and of the debug test threads of [...]
The rest of this description is #508's:
The Rust client retried its calls in four hand-written loops in
`crates/spark-connect-core/src/client.rs`: the unary and stream-opening calls
(`with_retry`), the artifact upload, the background `ReleaseExecute`, and the
reattach of a result stream. Each had its own copy of the decision "can the
policy retry this failure, is a retry left, wait its backoff".
That decision is now `retries::Retrying`, as PySpark's `Retrying`:
- `Retrying::backoff(status)`: a failure that the policy can retry is an
attempt of the policy. It waits the backoff of the attempt (or the `RetryInfo`
delay of the server) and is bounded by `max_retries`.
- `Retrying::retry_at_once()`: what PySpark raises as a `RetryException` is
retried without a wait and outside the attempts of the policy, for up to
`max_retry_exception_elapsed_time_ms` from the first of them. This was
`retry_exception_bound_passed` in `client.rs`.
- `retries::retrying(retrying, before_retry, attempt)`: the loop over the
attempts of a call. `with_retry`, the artifact upload and `ReleaseExecute` use
it.
The four loops were not the same, and the differences are on purpose. They
are kept, as parameters:
- The calls of a client check that the client is still open after the wait
of each retry (`before_retry`), as PySpark's `_stub` raises `NO_ACTIVE_SESSION`
for a closed client. `ReleaseExecute` checks nothing, as PySpark sends it
through the stub of its iterator, and its failure is only logged.
- The backoffs of the calls that a caller waits for end with a signal that
the wait of the caller takes (SPARK-61407), as the sleep of PySpark's
`Retrying` raises `KeyboardInterrupt`: `Retrying::ending_with_abort`, and
`backoff` answers `Backoff::Aborted`. Those of `ReleaseExecute`, in the
background, are waited whole. Only `with_retry` also ends an attempt that is
not answered, as before.
- An attempt of the artifact upload can fail with an error that is not a
failed RPC, such as a source that cannot be read. It ends the call and is not
retried: `RetryError::Aborted`.
- The reader of a reattachable stream does not make one call for each
attempt. A stream that fails and the reattach after it share the attempts of
one `Retrying` for each response (SPARK-61415), and a deadline or an unknown
operation is retried at once. It keeps its own loop, and asks `backoff` and
`retry_at_once` for every decision.
Two related fixes in the same code:
- `Instant::now() + deadline`, at the three places that set the deadline of
a stream, panics for a deadline too large to add to the time. It is now
`checked_add` in `stream_deadline_in`, and a deadline that cannot be a time is
none, as it is never reached.
- PySpark recognizes `INVALID_CURSOR.DISCONNECTED` (`in str(e)` in
`DefaultPolicy.can_retry`) and `INVALID_HANDLE.OPERATION_NOT_FOUND` /
`SESSION_NOT_FOUND` (`in status.message` in
`ExecutePlanResponseReattachableIterator`) by their name in the message, not by
the `ErrorInfo` of the status. So the client still matches on the message,
through one function, `retries::condition_in_message`, behind
`cursor_disconnected` and `unknown_operation`.
### Why are the changes needed?
A change to how the client retries had to be made in four places, and the
loops could drift apart: SPARK-61415 had to change the reattach path alone.
With one implementation, which errors are retried, the backoff, the number of
retries and the elapsed-time bound are each decided in one place, next to the
policy.
### Does this PR introduce _any_ user-facing change?
A reattachable execution whose `RpcDeadlines` are too large to add to the
current time (such as `Duration::MAX`) no longer panics; its streams have no
deadline. Nothing else changes.
### How was this patch tested?
- New unit tests in `retries.rs` for `retrying` (a retryable failure until
an attempt succeeds, a failure that is not retryable, the retries spent,
`no_retries`, a call past its deadline, an attempt that fails with an error
that is not a failed RPC, the check before a retry that fails), for
`Retrying::backoff` (it waits, a failure that is not retried spends no retry,
and a signal ends the backoff of the retries that end with an abort and not of
the others), for `Retrying::retry_at_onc [...]
- `cargo test -p apache-spark-connect-core --release`: 258 passed, 0
failed, 3 ignored (the tests of a live server). The existing loopback tests
(`deadlines`, `reattach_cleanup`, `artifact_uploads`, `server_session`,
`user_context`) cover each of the four call sites and pass unchanged.
- `cargo test -p apache-spark-connect --release --no-run` compiles.
- `cargo fmt --all --check` is clean.
- `cargo clippy -p apache-spark-connect-core --all-targets` reports nothing
in `retries.rs`, and one new advisory `result_large_err` warning in
`client.rs`, of the kind that the file already has for `SparkError`.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code (claude-fable-5-2)
This pull request and its description were written by Isaac.
Closes #536 from HyukjinKwon/SPARK-61440-with-retry-future-size.
Lead-authored-by: Liang-Chi Hsieh <[email protected]>
Co-authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/spark-connect-core/src/client.rs | 283 ++++++++----------
crates/spark-connect-core/src/retries.rs | 487 ++++++++++++++++++++++++++++++-
2 files changed, 606 insertions(+), 164 deletions(-)
diff --git a/crates/spark-connect-core/src/client.rs
b/crates/spark-connect-core/src/client.rs
index 4bd37e11..3fa7fb25 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -28,7 +28,7 @@ use crate::artifact::{
use crate::channel::{is_secret_param, ChannelBuilder,
GRPC_MAX_MESSAGE_LENGTH_DEFAULT};
use crate::error::{Result, SparkError, SparkErrorKind};
use crate::reattach::ExecutePlanResponseReattachableIterator;
-use crate::retries::{retry_delay_ms, RetryPolicy, RetryPolicyState};
+use crate::retries::{retrying, unknown_operation, Backoff, RetryError,
RetryPolicy, Retrying};
use crate::thread_entries::forget_when_thread_ends;
/// How long to wait for the lazy gRPC channel to become ready before
surfacing a
@@ -220,16 +220,11 @@ fn assertion_error(message: String) -> SparkError {
}
}
-/// The error class of `status` when the server does not know the operation of
a reattach, or
-/// its session, which the reference reads alike: the initial ExecutePlan
never reached the
-/// server, unless a response was read already.
-fn unknown_operation(status: &tonic::Status) -> Option<&'static str> {
- [
- "INVALID_HANDLE.OPERATION_NOT_FOUND",
- "INVALID_HANDLE.SESSION_NOT_FOUND",
- ]
- .into_iter()
- .find(|error| status.message().contains(error))
+/// When a stream opened now passes `deadline`, the timeout of the call that
opens it. A
+/// deadline too far to be a time, as of a duration set to its maximum, is
never reached, so
+/// it is none, where adding it to the time would panic.
+fn stream_deadline_in(deadline: Option<Duration>) ->
Option<tokio::time::Instant> {
+ deadline.and_then(|deadline|
tokio::time::Instant::now().checked_add(deadline))
}
/// The error of a reattach to an operation that the server does not know,
once a response was
@@ -242,18 +237,6 @@ fn response_already_received(error_type: &str) ->
SparkError {
)
}
-/// Whether the retries that the reference makes as `RetryException`s have run
for the policy's
-/// elapsed-time bound, measured from the first of them, which starts `since`
when it is unset.
-fn retry_exception_bound_passed(
- policy: &RetryPolicy,
- since: &mut Option<std::time::Instant>,
-) -> bool {
- let since = *since.get_or_insert_with(std::time::Instant::now);
- policy
- .max_retry_exception_elapsed_time_ms
- .is_some_and(|ms| since.elapsed() >= Duration::from_millis(ms))
-}
-
const PLAN_COMPRESSION_THRESHOLD_CONF: &str =
"spark.connect.session.planCompression.threshold";
const PLAN_COMPRESSION_ALGORITHM_CONF: &str =
"spark.connect.session.planCompression.defaultAlgorithm";
@@ -1332,39 +1315,43 @@ impl SparkConnectClient {
F: FnMut() -> Fut,
Fut: std::future::Future<Output = std::result::Result<T,
tonic::Status>>,
{
- let mut state = RetryPolicyState::new(self.retry_policy.clone());
- loop {
+ use futures::FutureExt;
+ self.with_attempts(|| {
// 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)) {
- // 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.
- self.ensure_open()?;
- continue;
- }
- }
- return Err(self.error_from_status(status).await);
+ // 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
+ // captures and as what it awaits, and that future, of the state
of a gRPC call, is
+ // large enough that the extra copy overflows the stack of a test
thread or of a
+ // Python thread of 512 KiB.
+ crate::runtime::until_abort(crate::runtime::ABORT_RETRIES,
op()).map(|attempt| {
+ match attempt {
+ Some(result) => result.map_err(RetryError::Status),
+ None => Err(RetryError::Aborted(wait_aborted())),
}
- }
+ })
+ })
+ .await
+ }
+
+ /// Makes the attempts of a call of this client under its retry policy
(see [`retrying`]),
+ /// and gives the failed RPC that ends them as the error of the server. An
attempt may fail
+ /// with an error that is not a failed RPC, which is not retried. The
backoff before a retry
+ /// ends with a signal that the wait of the caller takes, as the sleep of
PySpark's
+ /// `Retrying` does.
+ async fn with_attempts<T, Fut>(&self, attempt: impl FnMut() -> Fut) ->
Result<T>
+ where
+ Fut: std::future::Future<Output = std::result::Result<T,
RetryError<SparkError>>>,
+ {
+ let retries = Retrying::new(&self.retry_policy).ending_with_abort();
+ // 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.
+ let still_open = || self.ensure_open();
+ match retrying(retries, still_open, attempt).await {
+ Ok(value) => Ok(value),
+ Err(RetryError::Status(status)) =>
Err(self.error_from_status(status).await),
+ Err(RetryError::Aborted(error)) => Err(error),
+ Err(RetryError::WaitAborted) => Err(wait_aborted()),
}
}
@@ -1414,7 +1401,7 @@ impl SparkConnectClient {
let request = clone_on_grown_stack(iter.request());
let mut req = with_deadline(Request::new(request), deadline);
self._attach_metadata(&mut req);
- stream_deadline = deadline.map(|d| tokio::time::Instant::now()
+ d);
+ stream_deadline = stream_deadline_in(deadline);
let mut stub = self.stub.clone();
async move {
within_deadline(deadline, stub.execute_plan(req))
@@ -2130,39 +2117,20 @@ impl SparkConnectClient {
/// a stream is not resumed. The frames are read as the RPC consumes them,
so an attempt
/// holds one chunk of the artifact at a time.
async fn upload_artifact(&self, artifact: &NamedArtifact) -> Result<()> {
- let mut state = RetryPolicyState::new(self.retry_policy.clone());
- loop {
- // A data source that cannot be opened is an error before any
frame is sent.
- let frames = ArtifactFrames::new(self.session_id.clone(),
artifact)?;
- let failure = frames.failure();
- let result = self.add_artifacts_rpc(frames).await;
- // A read that failed ended the frames early, whatever the RPC
answered.
- take_frame_failure(&failure)?;
- match result {
- Ok(response) => {
- self.verify_response(&response.session_id,
&response.server_side_session_id)?;
- return check_artifact_upload(response, None);
- }
- Err(status) => {
- if self.retry_policy.can_retry(&status) {
- if let Some(wait_ms) =
state.next_attempt(retry_delay_ms(&status)) {
- 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;
- }
- }
- return Err(self.error_from_status(status).await);
- }
- }
- }
+ let response = self
+ .with_attempts(|| async move {
+ // A data source that cannot be opened is an error before any
frame is sent.
+ let frames = ArtifactFrames::new(self.session_id.clone(),
artifact)
+ .map_err(RetryError::Aborted)?;
+ let failure = frames.failure();
+ let result = self.add_artifacts_rpc(frames).await;
+ // A read that failed ended the frames early, whatever the RPC
answered.
+ take_frame_failure(&failure).map_err(RetryError::Aborted)?;
+ result.map_err(RetryError::Status)
+ })
+ .await?;
+ self.verify_response(&response.session_id,
&response.server_side_session_id)?;
+ check_artifact_upload(response, None)
}
/// The AddArtifacts call of `requests`, once. Stamps user_context on
every frame as it is
@@ -2402,30 +2370,34 @@ impl SparkConnectClient {
/// `spark.connect.execute.manager.detachedTimeout`. As the reference's,
the request carries
/// no observed server-side session ID.
fn spawn_release(&self, metadata: MetadataMap, request:
ReleaseExecuteRequest) {
- let mut stub = self.stub.clone();
+ let stub = self.stub.clone();
let policy = self.retry_policy.clone();
let release = async move {
- let mut state = RetryPolicyState::new(policy.clone());
- loop {
+ // 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 mut req = Request::new(request.clone());
*req.metadata_mut() = metadata.clone();
- match stub.release_execute(req).await {
- Ok(_) => return,
- Err(status) => {
- if policy.can_retry(&status) {
- if let Some(w) =
state.next_attempt(retry_delay_ms(&status)) {
-
tokio::time::sleep(Duration::from_millis(w)).await;
- continue;
- }
- }
- tracing::warn!(
- "ReleaseExecute of operation {} failed: {}",
- request.operation_id,
- status
- );
- return;
- }
+ let mut stub = stub.clone();
+ async move {
+ stub.release_execute(req)
+ .await
+ .map(drop)
+ .map_err(RetryError::Status)
}
+ })
+ .await;
+ match released {
+ Ok(()) => {}
+ Err(RetryError::Status(status)) => tracing::warn!(
+ "ReleaseExecute of operation {} failed: {}",
+ request.operation_id,
+ status
+ ),
+ Err(RetryError::Aborted(never)) => match never {},
+ // Its backoffs are waited whole.
+ Err(RetryError::WaitAborted) => {}
}
};
// A stream is read inside a runtime, but it can be dropped outside of
any, for
@@ -2464,15 +2436,12 @@ impl ReattachableResponseStream {
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());
// The clock of the retries that the reference makes as
`RetryException`s, bounded by the
- // policy's elapsed time: it starts at the first deadline that passes,
the deadline of
- // the initial ExecutePlan included, and the reattaches after a
deadline or an unknown
+ // 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 retry_exception_since: Option<std::time::Instant> = None;
- if self.stream.is_none()
- && retry_exception_bound_passed(&self.retry_policy, &mut
retry_exception_since)
- {
+ let mut retrying =
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.
let status = tonic::Status::deadline_exceeded("Deadline Exceeded");
@@ -2480,8 +2449,7 @@ impl ReattachableResponseStream {
}
loop {
let Some(stream) = self.stream.as_mut() else {
- self.reattach(&mut retry_state, &mut retry_exception_since)
- .await?;
+ self.reattach(&mut retrying).await?;
continue;
};
let deadline = self.stream_deadline;
@@ -2519,10 +2487,7 @@ impl ReattachableResponseStream {
// The server completes a reattachable stream before
`ResultComplete` on
// purpose, after `senderMaxStreamDuration` or
`senderMaxStreamSize`: the rest
// of the result is read by reattaching.
- Ok(None) => {
- self.reattach(&mut retry_state, &mut retry_exception_since)
- .await?
- }
+ Ok(None) => self.reattach(&mut retrying).await?,
// As the reference iterator: the per-RPC deadline of the
stream passed, and the
// execution goes on on the server, so the iteration
reattaches at once, for up
// to the policy's bound of such retries.
@@ -2530,8 +2495,7 @@ impl ReattachableResponseStream {
if status.code() == tonic::Code::DeadlineExceeded
&& !self.iter.is_completed().await =>
{
- if retry_exception_bound_passed(&self.retry_policy, &mut
retry_exception_since)
- {
+ if !retrying.retry_at_once() {
return Err(self.fail_with_status(status).await);
}
self.stream = None;
@@ -2546,8 +2510,7 @@ impl ReattachableResponseStream {
let error_type =
unknown_operation(&status).unwrap_or_default();
return
Err(self.fail(response_already_received(error_type)));
}
- if retry_exception_bound_passed(&self.retry_policy, &mut
retry_exception_since)
- {
+ if !retrying.retry_at_once() {
return Err(self.fail_with_status(status).await);
}
self.execute_again = true;
@@ -2555,9 +2518,6 @@ impl ReattachableResponseStream {
}
Err(status) => {
// Only reattach a still-running execution on a retriable
drop.
- if self.iter.is_completed().await ||
!self.retry_policy.can_retry(&status) {
- return Err(self.fail_with_status(status).await);
- }
// As the reference's `_has_next`, which reads the stream
and reattaches in
// one attempt of its `Retrying`: a stream that fails,
also one that a
// reattach opened, is an attempt of the policy, which
waits its backoff before
@@ -2566,20 +2526,15 @@ impl ReattachableResponseStream {
// reattached at once, without end. As at the other
retries, the server's
// 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) => {
- 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),
+ if self.iter.is_completed().await {
+ return Err(self.fail_with_status(status).await);
}
- self.reattach(&mut retry_state, &mut retry_exception_since)
- .await?;
+ match retrying.backoff(&status).await {
+ Backoff::Retry => {}
+ Backoff::GiveUp => return
Err(self.fail_with_status(status).await),
+ Backoff::Aborted => return
Err(self.fail(wait_aborted())),
+ }
+ self.reattach(&mut retrying).await?;
}
}
}
@@ -2587,13 +2542,12 @@ impl ReattachableResponseStream {
/// Opens the stream of the execution again: by reattaching to it from the
last response
/// read, or, when the server does not know it, by sending the ExecutePlan
again. Transient
- /// failures are retried under `retry_state`, and a deadline or an unknown
execution as the
- /// reference's `RetryException`s, bounded by `retry_exception_since`.
- async fn reattach(
- &mut self,
- retry_state: &mut RetryPolicyState,
- retry_exception_since: &mut Option<std::time::Instant>,
- ) -> Result<()> {
+ /// failures are retried under the policy with their backoff
([`Retrying::backoff`]), and a
+ /// deadline or an unknown execution at once, as the reference's
`RetryException`s, for up
+ /// to their elapsed-time bound ([`Retrying::retry_at_once`]). `retrying`
is that of the
+ /// response being read, so the failures of its streams and of its
reattaches share the
+ /// attempts of the policy.
+ async fn reattach(&mut self, retrying: &mut Retrying) -> Result<()> {
loop {
// As the reference's `_stub`: once the client is closed (its
session stopped), the
// reattach and the ExecutePlan sent again raise
NO_ACTIVE_SESSION, and the stream ends.
@@ -2624,7 +2578,7 @@ impl ReattachableResponseStream {
if self.iter.last_response_id().await.is_some() {
return
Err(self.fail(response_already_received(error_type)));
}
- if retry_exception_bound_passed(&self.retry_policy,
retry_exception_since) {
+ if !retrying.retry_at_once() {
return Err(self.fail_with_status(status).await);
}
self.execute_again = true;
@@ -2633,25 +2587,17 @@ impl ReattachableResponseStream {
if status.code() == tonic::Code::DeadlineExceeded {
// As the reference: a call past its deadline, whether it is
sent again or
// reattached, is retried at once, the execution going on on
the server.
- if retry_exception_bound_passed(&self.retry_policy,
retry_exception_since) {
+ if !retrying.retry_at_once() {
return Err(self.fail_with_status(status).await);
}
self.execute_again = false;
continue;
}
- if self.retry_policy.can_retry(&status) {
- if let Some(w) =
retry_state.next_attempt(retry_delay_ms(&status)) {
- 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;
- }
+ match retrying.backoff(&status).await {
+ Backoff::Retry => continue,
+ Backoff::GiveUp => return
Err(self.fail_with_status(status).await),
+ Backoff::Aborted => return Err(self.fail(wait_aborted())),
}
- return Err(self.fail_with_status(status).await);
}
}
@@ -2664,7 +2610,7 @@ impl ReattachableResponseStream {
self.attach_metadata(&mut req);
// After the metadata, which the deadline is a header of.
let req = with_deadline(req, deadline);
- self.stream_deadline = deadline.map(|d| tokio::time::Instant::now() +
d);
+ self.stream_deadline = stream_deadline_in(deadline);
let response =
within_deadline(deadline,
self.client.stub.clone().reattach_execute(req)).await?;
Ok(response.into_inner())
@@ -2678,7 +2624,7 @@ impl ReattachableResponseStream {
let request = clone_on_grown_stack(self.iter.request());
let mut req = with_deadline(Request::new(request), deadline);
self.client._attach_metadata(&mut req);
- self.stream_deadline = deadline.map(|d| tokio::time::Instant::now() +
d);
+ self.stream_deadline = stream_deadline_in(deadline);
let response =
within_deadline(deadline,
self.client.stub.clone().execute_plan(req)).await?;
Ok(response.into_inner())
@@ -2889,6 +2835,17 @@ mod tests {
});
}
+ #[tokio::test]
+ async fn test_stream_deadline_too_far_to_be_a_time_is_none() {
+ assert_eq!(stream_deadline_in(None), None);
+ let before = tokio::time::Instant::now();
+ let deadline =
stream_deadline_in(Some(Duration::from_secs(600))).expect("a time");
+ assert!(deadline >= before + Duration::from_secs(600));
+ assert!(deadline <= tokio::time::Instant::now() +
Duration::from_secs(600));
+ // Adding it to the time would overflow, and panic.
+ assert_eq!(stream_deadline_in(Some(Duration::MAX)), None);
+ }
+
#[tokio::test]
async fn test_empty_cache_artifacts_needs_no_server() {
let builder = ChannelBuilder::parse("sc://localhost").unwrap();
diff --git a/crates/spark-connect-core/src/retries.rs
b/crates/spark-connect-core/src/retries.rs
index eee6d4b0..da5dea79 100644
--- a/crates/spark-connect-core/src/retries.rs
+++ b/crates/spark-connect-core/src/retries.rs
@@ -78,13 +78,49 @@ impl RetryPolicy {
pub fn can_retry(&self, status: &tonic::Status) -> bool {
let transient = match grpc_python_code(status) {
tonic::Code::Unavailable => true,
- tonic::Code::Internal =>
status.message().contains("INVALID_CURSOR.DISCONNECTED"),
+ tonic::Code::Internal => cursor_disconnected(status),
_ => false,
};
transient || retry_info(status).is_some()
}
}
+/// The first of the error conditions `conditions` that the message of a
failed RPC names.
+///
+/// The reference client recognizes these conditions by their name in the
message of the error
+/// (`"INVALID_CURSOR.DISCONNECTED" in str(e)` in `DefaultPolicy.can_retry`,
and
+/// `error in status.message` in `ExecutePlanResponseReattachableIterator`),
not by the
+/// `ErrorInfo` detail of the status, so this client does too: every such
match goes through
+/// here.
+fn condition_in_message(
+ status: &tonic::Status,
+ conditions: &[&'static str],
+) -> Option<&'static str> {
+ conditions
+ .iter()
+ .copied()
+ .find(|condition| status.message().contains(condition))
+}
+
+/// Whether the message of `status` names `INVALID_CURSOR.DISCONNECTED`:
another RPC took over
+/// the cursor of the response stream, which a reattach resumes.
+pub(crate) fn cursor_disconnected(status: &tonic::Status) -> bool {
+ condition_in_message(status, &["INVALID_CURSOR.DISCONNECTED"]).is_some()
+}
+
+/// The error class of `status` when the server does not know the operation of
a reattach, or
+/// its session, which the reference reads alike: the initial ExecutePlan
never reached the
+/// server, unless a response was read already.
+pub(crate) fn unknown_operation(status: &tonic::Status) -> Option<&'static
str> {
+ condition_in_message(
+ status,
+ &[
+ "INVALID_HANDLE.OPERATION_NOT_FOUND",
+ "INVALID_HANDLE.SESSION_NOT_FOUND",
+ ],
+ )
+}
+
/// The `google.rpc.Status` of a failed RPC, from its
`grpc-status-details-bin`, whose details
/// hold Any-packed messages.
#[derive(Clone, PartialEq, Message)]
@@ -243,6 +279,145 @@ impl RetryPolicyState {
}
}
+/// The retries of one call, as PySpark's `Retrying`: the one place that
decides whether a
+/// failed attempt is made again, and that waits before it is.
+///
+/// A failure is retried in one of two ways, as in the reference:
+///
+/// - [`Retrying::backoff`]: a failed RPC that the policy can retry
+/// ([`RetryPolicy::can_retry`]) is an attempt of the policy. It waits the
backoff of the
+/// attempt (or the delay that the server asks for) and is bounded by
`max_retries`.
+/// - [`Retrying::retry_at_once`]: what the reference raises as a
`RetryException` (a stream of
+/// an execution past its deadline, or an execution that the server does not
know yet) is
+/// retried without a wait and outside the attempts of the policy, for up to
+/// `max_retry_exception_elapsed_time_ms` from the first of them.
+///
+/// [`retrying`] is the loop over the attempts of a call. A caller whose
attempts are not one
+/// call each, as the reader of a reattachable stream, asks the two methods
itself.
+pub struct Retrying {
+ state: RetryPolicyState,
+ /// When the first retry made at once was asked for.
+ retry_exception_since: Option<std::time::Instant>,
+ /// Whether a signal that the wait of the caller takes ends a backoff.
+ ends_with_abort: bool,
+}
+
+/// What [`Retrying::backoff`] decides for a failed attempt.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Backoff {
+ /// The wait before the retry is over: the attempt is made again.
+ Retry,
+ /// The policy cannot retry the failure, or its retries are spent: the
failure is the error
+ /// of the call.
+ GiveUp,
+ /// A signal that the wait of the caller takes ended the wait before the
retry, which is not
+ /// made (see [`crate::runtime::until_abort`]).
+ Aborted,
+}
+
+impl Retrying {
+ /// The retries of a call under `policy`, whose backoffs are waited whole.
+ pub fn new(policy: &RetryPolicy) -> Self {
+ Self {
+ state: RetryPolicyState::new(policy.clone()),
+ retry_exception_since: None,
+ ends_with_abort: false,
+ }
+ }
+
+ /// These retries, whose backoffs a signal of the process ends when the
wait of the caller
+ /// takes it ([`crate::runtime::ABORT_RETRIES`]), as the sleep of
PySpark's `Retrying`
+ /// raises KeyboardInterrupt. For the calls that a caller waits for; a
call in the
+ /// background, that no caller waits for, waits its backoffs whole.
+ pub fn ending_with_abort(mut self) -> Self {
+ self.ends_with_abort = true;
+ self
+ }
+
+ /// Whether the attempt that failed with `status` is made again under the
policy, after the
+ /// wait before it, which this awaits. It is not when the policy cannot
retry the failure,
+ /// or once its retries are spent: `status` is then the error of the call.
+ pub async fn backoff(&mut self, status: &tonic::Status) -> Backoff {
+ if !self.state.policy().can_retry(status) {
+ return Backoff::GiveUp;
+ }
+ let Some(wait_ms) = self.state.next_attempt(retry_delay_ms(status))
else {
+ return Backoff::GiveUp;
+ };
+ let wait =
tokio::time::sleep(std::time::Duration::from_millis(wait_ms));
+ if !self.ends_with_abort {
+ wait.await;
+ return Backoff::Retry;
+ }
+ match crate::runtime::until_abort(crate::runtime::ABORT_RETRIES,
wait).await {
+ Some(()) => Backoff::Retry,
+ None => Backoff::Aborted,
+ }
+ }
+
+ /// Whether a failure that the reference retries as a `RetryException` is
retried, at once:
+ /// until such retries have run for the policy's elapsed-time bound,
measured from the first
+ /// of them, which this call is when there was none.
+ pub fn retry_at_once(&mut self) -> bool {
+ let since = *self
+ .retry_exception_since
+ .get_or_insert_with(std::time::Instant::now);
+ !self
+ .state
+ .policy()
+ .max_retry_exception_elapsed_time_ms
+ .is_some_and(|ms| since.elapsed() >=
std::time::Duration::from_millis(ms))
+ }
+}
+
+/// Why a call made by [`retrying`] failed, and what an attempt of it fails
with.
+#[derive(Debug)]
+pub enum RetryError<E> {
+ /// A failed RPC. From an attempt, it is retried when the policy allows;
from [`retrying`],
+ /// the policy could not retry it, or its retries are spent.
+ Status(tonic::Status),
+ /// An error that is not retried: of an attempt, or of the check before a
retry.
+ Aborted(E),
+ /// A signal ended the wait before a retry ([`Backoff::Aborted`]). Only of
retries
+ /// [`Retrying::ending_with_abort`].
+ WaitAborted,
+}
+
+/// 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.
+///
+/// What differs between the calls is given rather than built in:
+///
+/// - `retrying` says whether a signal ends the backoffs
([`Retrying::ending_with_abort`]).
+/// - `before_retry` runs after the wait of each retry, before its attempt,
and its error ends
+/// the call. The calls of a client check there that the client is still
open, as the
+/// reference's `_stub` raises for a closed one; the release of an
execution, which the
+/// reference sends through the stub of its iterator, checks nothing.
+/// - `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 async fn retrying<T, E, Fut>(
+ mut retrying: Retrying,
+ mut before_retry: impl FnMut() -> Result<(), E>,
+ mut attempt: impl FnMut() -> Fut,
+) -> Result<T, RetryError<E>>
+where
+ Fut: std::future::Future<Output = Result<T, RetryError<E>>>,
+{
+ loop {
+ match attempt().await {
+ Err(RetryError::Status(status)) => {
+ match retrying.backoff(&status).await {
+ Backoff::Retry => {}
+ Backoff::GiveUp => return Err(RetryError::Status(status)),
+ Backoff::Aborted => return Err(RetryError::WaitAborted),
+ }
+ before_retry().map_err(RetryError::Aborted)?;
+ }
+ result => return result,
+ }
+ }
+}
+
/// A pseudo-random jitter value in `[0, max)` milliseconds.
///
/// Mirrors `random.uniform(0, jitter)` in the reference `RetryPolicyState`.
Retry
@@ -940,4 +1115,314 @@ mod tests {
assert_eq!(grpc_python_code(&timeout), tonic::Code::Cancelled);
assert!(!p.can_retry(&timeout));
}
+
+ #[test]
+ fn test_conditions_are_read_from_the_message_as_the_reference_does() {
+ // The cursor that another RPC took over, anywhere in the message.
+ let disconnected = tonic::Status::internal(
+ "[INVALID_CURSOR.DISCONNECTED] The cursor has been disconnected by
the server.",
+ );
+ assert!(cursor_disconnected(&disconnected));
+ assert!(!cursor_disconnected(&tonic::Status::internal(
+ "[INVALID_CURSOR.POSITION_NOT_FOUND] The cursor position was not
found."
+ )));
+ assert!(!cursor_disconnected(&tonic::Status::internal("")));
+ // The match is on the message alone, whatever the code: `can_retry`
asks for INTERNAL.
+ let not_internal =
tonic::Status::invalid_argument("INVALID_CURSOR.DISCONNECTED");
+ assert!(cursor_disconnected(¬_internal));
+ assert!(!RetryPolicy::default().can_retry(¬_internal));
+ assert!(RetryPolicy::default().can_retry(&disconnected));
+
+ // An operation or a session that the server does not know, named as
the server names it.
+ assert_eq!(
+ unknown_operation(&tonic::Status::not_found(
+ "[INVALID_HANDLE.OPERATION_NOT_FOUND] Operation not found."
+ )),
+ Some("INVALID_HANDLE.OPERATION_NOT_FOUND")
+ );
+ assert_eq!(
+ unknown_operation(&tonic::Status::internal(
+ "[INVALID_HANDLE.SESSION_NOT_FOUND] Session not found."
+ )),
+ Some("INVALID_HANDLE.SESSION_NOT_FOUND")
+ );
+ // The other conditions of a handle are not: a session that changed
closes the client.
+ for message in [
+ "[INVALID_HANDLE.SESSION_CHANGED] The existing session changed.",
+ "[INVALID_HANDLE.OPERATION_ABANDONED] Operation was abandoned.",
+ "INVALID_HANDLE",
+ "operation not found",
+ "",
+ ] {
+ assert_eq!(unknown_operation(&tonic::Status::internal(message)),
None);
+ }
+ }
+
+ /// A policy of `max_retries` retries with waits of 1 ms, so that a test
does not wait.
+ fn quick_policy(max_retries: u32) -> RetryPolicy {
+ RetryPolicy {
+ max_retries: Some(max_retries),
+ initial_backoff_ms: 1,
+ max_backoff_ms: Some(1),
+ backoff_multiplier: 1.0,
+ jitter_ms: 0,
+ min_jitter_threshold_ms: 0,
+ recognize_server_retry_delay: false,
+ max_server_retry_delay_ms: None,
+ max_retry_exception_elapsed_time_ms: None,
+ }
+ }
+
+ /// Runs [`retrying`] over `outcomes`, one for each attempt in order, and
gives its result
+ /// with the numbers of attempts made and of checks made before a retry.
+ async fn retry_over(
+ policy: &RetryPolicy,
+ outcomes: Vec<Result<u32, RetryError<&'static str>>>,
+ ) -> (Result<u32, RetryError<&'static str>>, usize, usize) {
+ let total = outcomes.len();
+ let mut outcomes = outcomes.into_iter();
+ let mut checks = 0;
+ let result = retrying(
+ Retrying::new(policy),
+ || {
+ checks += 1;
+ Ok(())
+ },
+ || {
+ let outcome = outcomes.next().expect("no attempt after the
last outcome");
+ async move { outcome }
+ },
+ )
+ .await;
+ (result, total - outcomes.len(), checks)
+ }
+
+ fn unavailable<T>() -> Result<T, RetryError<&'static str>> {
+ Err(RetryError::Status(tonic::Status::unavailable("restarting")))
+ }
+
+ #[tokio::test]
+ async fn
test_retrying_retries_a_retryable_failure_until_an_attempt_succeeds() {
+ let outcomes = vec![unavailable(), unavailable(), Ok(7)];
+ let (result, attempts, checks) = retry_over(&quick_policy(5),
outcomes).await;
+ assert!(matches!(result, Ok(7)), "{result:?}");
+ assert_eq!(attempts, 3);
+ // The check runs before each retry, and not before the first attempt.
+ assert_eq!(checks, 2);
+ }
+
+ #[tokio::test]
+ async fn test_retrying_makes_one_attempt_of_a_call_that_succeeds() {
+ let (result, attempts, checks) = retry_over(&quick_policy(5),
vec![Ok(1)]).await;
+ assert!(matches!(result, Ok(1)), "{result:?}");
+ assert_eq!((attempts, checks), (1, 0));
+ }
+
+ #[tokio::test]
+ async fn test_retrying_does_not_retry_a_failure_that_the_policy_cannot() {
+ let outcomes = vec![
+ Err(RetryError::Status(tonic::Status::invalid_argument("bad"))),
+ Ok(1),
+ ];
+ let (result, attempts, checks) = retry_over(&quick_policy(5),
outcomes).await;
+ match result {
+ Err(RetryError::Status(status)) => {
+ assert_eq!(status.code(), tonic::Code::InvalidArgument);
+ assert_eq!(status.message(), "bad");
+ }
+ other => panic!("{other:?}"),
+ }
+ assert_eq!((attempts, checks), (1, 0));
+ }
+
+ #[tokio::test]
+ async fn
test_retrying_fails_with_the_last_failure_once_the_retries_are_spent() {
+ let outcomes = vec![
+ unavailable(),
+ unavailable(),
+ Err(RetryError::Status(tonic::Status::unavailable("the last"))),
+ Ok(1),
+ ];
+ // Two retries: three attempts.
+ let (result, attempts, checks) = retry_over(&quick_policy(2),
outcomes).await;
+ match result {
+ Err(RetryError::Status(status)) => assert_eq!(status.message(),
"the last"),
+ other => panic!("{other:?}"),
+ }
+ assert_eq!((attempts, checks), (3, 2));
+
+ // No retries: the failure of the only attempt.
+ let (result, attempts, checks) =
+ retry_over(&RetryPolicy::no_retries(), vec![unavailable(),
Ok(1)]).await;
+ assert!(matches!(result, Err(RetryError::Status(_))), "{result:?}");
+ assert_eq!((attempts, checks), (1, 0));
+ }
+
+ #[tokio::test]
+ async fn test_retrying_does_not_retry_a_call_past_its_deadline() {
+ // The deadline of a call is not a failure of the policy: the
reference retries it only
+ // as a RetryException of a reattachable execution, which
`retry_at_once` bounds.
+ let outcomes = vec![
+ Err(RetryError::Status(tonic::Status::deadline_exceeded(
+ "Deadline Exceeded",
+ ))),
+ Ok(1),
+ ];
+ let (result, attempts, checks) = retry_over(&quick_policy(5),
outcomes).await;
+ match result {
+ Err(RetryError::Status(status)) => {
+ assert_eq!(status.code(), tonic::Code::DeadlineExceeded)
+ }
+ other => panic!("{other:?}"),
+ }
+ assert_eq!((attempts, checks), (1, 0));
+ }
+
+ #[tokio::test]
+ async fn
test_retrying_ends_with_the_error_of_an_attempt_that_is_no_failed_rpc() {
+ let outcomes = vec![unavailable(),
Err(RetryError::Aborted("unreadable")), Ok(1)];
+ let (result, attempts, checks) = retry_over(&quick_policy(5),
outcomes).await;
+ assert!(
+ matches!(result, Err(RetryError::Aborted("unreadable"))),
+ "{result:?}"
+ );
+ assert_eq!((attempts, checks), (2, 1));
+ }
+
+ #[tokio::test]
+ 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)),
+ || Err("closed"),
+ || {
+ attempts += 1;
+ async { unavailable() }
+ },
+ )
+ .await;
+ assert!(
+ matches!(result, Err(RetryError::Aborted("closed"))),
+ "{result:?}"
+ );
+ // The retry that the check refused is not sent.
+ assert_eq!(attempts, 1);
+ }
+
+ #[tokio::test]
+ async fn test_backoff_waits_the_delay_of_the_attempt_before_a_retry() {
+ let policy = RetryPolicy {
+ initial_backoff_ms: 40,
+ max_backoff_ms: Some(40),
+ ..quick_policy(1)
+ };
+ let mut retrying = Retrying::new(&policy);
+ let status = tonic::Status::unavailable("restarting");
+ let started = std::time::Instant::now();
+ assert_eq!(retrying.backoff(&status).await, Backoff::Retry);
+ assert!(started.elapsed() >= std::time::Duration::from_millis(40));
+ // The retries are spent: no wait, and no retry.
+ let started = std::time::Instant::now();
+ assert_eq!(retrying.backoff(&status).await, Backoff::GiveUp);
+ assert!(started.elapsed() < std::time::Duration::from_millis(40));
+ }
+
+ #[tokio::test]
+ async fn
test_backoff_does_not_spend_a_retry_on_a_failure_that_is_not_retried() {
+ let mut retrying = Retrying::new(&quick_policy(1));
+ let missing = tonic::Status::not_found("missing");
+ assert_eq!(retrying.backoff(&missing).await, Backoff::GiveUp);
+ let late = tonic::Status::deadline_exceeded("Deadline Exceeded");
+ assert_eq!(retrying.backoff(&late).await, Backoff::GiveUp);
+ // The one retry of the policy is still there.
+ let down = tonic::Status::unavailable("down");
+ assert_eq!(retrying.backoff(&down).await, Backoff::Retry);
+ assert_eq!(retrying.backoff(&down).await, Backoff::GiveUp);
+ }
+
+ /// A policy whose one backoff, of a minute, a test does not wait out.
+ fn slow_policy() -> RetryPolicy {
+ RetryPolicy {
+ initial_backoff_ms: 60_000,
+ max_backoff_ms: Some(60_000),
+ ..quick_policy(1)
+ }
+ }
+
+ #[test]
+ fn test_a_signal_ends_the_backoff_of_retries_that_end_with_an_abort() {
+ use crate::runtime::{block_on, with_wait_watch, Watch};
+ let down = tonic::Status::unavailable("down");
+ let started = std::time::Instant::now();
+ let ended = with_wait_watch(std::sync::Arc::new(|| Watch::Abort), || {
+ block_on(async {
+ let mut retrying =
Retrying::new(&slow_policy()).ending_with_abort();
+ retrying.backoff(&down).await
+ })
+ });
+ assert_eq!(ended, Backoff::Aborted);
+ assert!(started.elapsed() < std::time::Duration::from_secs(30));
+
+ // The retry after the backoff is not made, and its check is not run.
+ let mut attempts = 0;
+ 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(),
+ || panic!("no check before a retry that is not made"),
+ || {
+ attempts += 1;
+ async { unavailable() }
+ },
+ ))
+ });
+ assert!(matches!(result, Err(RetryError::WaitAborted)), "{result:?}");
+ assert_eq!(attempts, 1);
+ }
+
+ #[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};
+ // Longer than the poll of the watch, which aborts at its first poll.
+ let policy = RetryPolicy {
+ initial_backoff_ms: (POLL_INTERVAL * 2).as_millis() as u64,
+ max_backoff_ms: None,
+ ..quick_policy(1)
+ };
+ let down = tonic::Status::unavailable("down");
+ let ended = with_wait_watch(std::sync::Arc::new(|| Watch::Abort), || {
+ block_on(async {
+ let mut retrying = Retrying::new(&policy);
+ retrying.backoff(&down).await
+ })
+ });
+ assert_eq!(ended, Backoff::Retry);
+ }
+
+ #[tokio::test]
+ async fn
test_retries_at_once_are_bounded_by_their_elapsed_time_and_not_by_the_attempts()
{
+ let bounded = |ms| RetryPolicy {
+ max_retry_exception_elapsed_time_ms: ms,
+ ..quick_policy(0)
+ };
+ // No bound: always, though the policy has no retries.
+ let mut retrying = Retrying::new(&bounded(None));
+ assert!((0..100).all(|_| retrying.retry_at_once()));
+ // A bound of 0 has passed at the first of them.
+ assert!(!Retrying::new(&bounded(Some(0))).retry_at_once());
+ // The clock starts at the first of them, not when the call started.
+ let mut retrying = Retrying::new(&bounded(Some(50)));
+ std::thread::sleep(std::time::Duration::from_millis(60));
+ assert!(retrying.retry_at_once());
+ std::thread::sleep(std::time::Duration::from_millis(60));
+ assert!(!retrying.retry_at_once());
+ // They do not spend the retries of the policy, nor the policy's
theirs.
+ let mut retrying = Retrying::new(&RetryPolicy {
+ max_retry_exception_elapsed_time_ms: Some(0),
+ ..quick_policy(1)
+ });
+ assert!(!retrying.retry_at_once());
+ let down = tonic::Status::unavailable("down");
+ assert_eq!(retrying.backoff(&down).await, Backoff::Retry);
+ }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]