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 ae4dad68 [SPARK-61390][CONNECT] Use the default retry policy of
PySpark in Spark Connect Rust
ae4dad68 is described below
commit ae4dad680e8c45a4376377d80a2e1e362493fe47
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 08:52:02 2026 +0900
[SPARK-61390][CONNECT] Use the default retry policy of PySpark in Spark
Connect Rust
### What changes were proposed in this pull request?
[SPARK-61390](https://issues.apache.org/jira/browse/SPARK-61390):
`RetryPolicy::default()` now has the values of PySpark 4.3.0's `DefaultPolicy`,
which the Scala client's `RetryPolicy.defaultPolicy()` shares:
- 15 retries from 50 ms, quadrupling up to 60 s.
- 500 ms of jitter on the waits from the 2 s threshold.
- The server's `google.rpc.RetryInfo` delay is honored, capped at 10
minutes.
A failure with a `RetryInfo` detail is retried whatever its code, as
`DefaultPolicy.can_retry` does. The new `retry_delay_ms` reads the delay from
`grpc-status-details-bin`, and the four retry sites of the client pass it to
the backoff. The wait is rounded down, as the reference's `int()` does.
### Why are the changes needed?
The default policy was that of an older client: 1 s doubling up to 64 s,
without jitter and without the server's delay. So a client retried on another
schedule than PySpark's, with a total of 639 s instead of 608.25 s with the
jitter off, and ignored the delay that the server asks for. For example, a
`RESOURCE_EXHAUSTED` with `RetryInfo(retry_delay=300ms)` was raised at once;
now it is retried after 300 ms, as PySpark does.
### Does this PR introduce _any_ user-facing change?
Yes. The retry timings of the default client match PySpark's, and failures
with a `RetryInfo` detail are retried.
### How was this patch tested?
- Rust unit tests: the default schedule without jitter (50, 200, 800, 3200,
12800, 51200, then 60000 nine times, 608250 ms in total); the jitter applies
only from the threshold and stays under 500 ms; the server delay is honored and
capped, and ignored when `recognize_server_retry_delay` is false; and a status
with `RetryInfo` is retried whatever its code.
- An offline Python test with a mock `RetryInfo` failure, retried after the
server's delay.
- `cargo test -p apache-spark-connect -p apache-spark-connect-core
--release --lib`, the core e2e tests and the drop-in suites 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 #480 from HyukjinKwon/SPARK-61390-default-retry-policy.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/spark-connect-core/src/client.rs | 10 +-
crates/spark-connect-core/src/retries.rs | 209 +++++++++++++++++++++++++++++--
python/tests/_mock_connect_server.py | 22 ++++
python/tests/test_dropin_offline.py | 12 ++
4 files changed, 236 insertions(+), 17 deletions(-)
diff --git a/crates/spark-connect-core/src/client.rs
b/crates/spark-connect-core/src/client.rs
index 2a3c669e..37c8d8fd 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -29,7 +29,7 @@ use crate::artifact::{
use crate::channel::{ChannelBuilder, GRPC_MAX_MESSAGE_LENGTH_DEFAULT};
use crate::error::{Result, SparkError, SparkErrorKind};
use crate::reattach::ExecutePlanResponseReattachableIterator;
-use crate::retries::{RetryPolicy, RetryPolicyState};
+use crate::retries::{retry_delay_ms, RetryPolicy, RetryPolicyState};
use crate::thread_entries::forget_when_thread_ends;
/// How long to wait for the lazy gRPC channel to become ready before
surfacing a
@@ -1184,7 +1184,7 @@ impl SparkConnectClient {
Ok(v) => return Ok(v),
Err(status) => {
if self.retry_policy.can_retry(&status) {
- if let Some(wait_ms) = state.next_attempt(None) {
+ if let Some(wait_ms) =
state.next_attempt(retry_delay_ms(&status)) {
tokio::time::sleep(std::time::Duration::from_millis(wait_ms)).await;
// As the reference's `_stub`, through which each
attempt goes: once
// the client is closed (its session stopped while
the call waited),
@@ -1957,7 +1957,7 @@ impl SparkConnectClient {
}
Err(status) => {
if self.retry_policy.can_retry(&status) {
- if let Some(wait_ms) = state.next_attempt(None) {
+ if let Some(wait_ms) =
state.next_attempt(retry_delay_ms(&status)) {
tokio::time::sleep(std::time::Duration::from_millis(wait_ms)).await;
// As in `with_retry`: a closed client sends no
more attempts.
self.ensure_open()?;
@@ -2139,7 +2139,7 @@ impl SparkConnectClient {
Ok(_) => return,
Err(status) => {
if policy.can_retry(&status) {
- if let Some(w) = state.next_attempt(None) {
+ if let Some(w) =
state.next_attempt(retry_delay_ms(&status)) {
tokio::time::sleep(Duration::from_millis(w)).await;
continue;
}
@@ -2321,7 +2321,7 @@ impl ReattachableResponseStream {
continue;
}
if self.retry_policy.can_retry(&status) {
- if let Some(w) = retry_state.next_attempt(None) {
+ if let Some(w) =
retry_state.next_attempt(retry_delay_ms(&status)) {
tokio::time::sleep(Duration::from_millis(w)).await;
continue;
}
diff --git a/crates/spark-connect-core/src/retries.rs
b/crates/spark-connect-core/src/retries.rs
index 21f0bb1a..eee6d4b0 100644
--- a/crates/spark-connect-core/src/retries.rs
+++ b/crates/spark-connect-core/src/retries.rs
@@ -3,6 +3,8 @@
//! Mirrors `pyspark.sql.connect.client.retries.RetryPolicy` and friends.
//! The backoff computation is deterministic and unit-testable without
sleeping.
+use prost::Message;
+
/// Default maximum cumulative elapsed time for retry exception retries.
pub const DEFAULT_MAX_RETRY_EXCEPTION_ELAPSED_TIME: u64 = 60 * 60; // 1 hour
in seconds
@@ -34,16 +36,17 @@ pub struct RetryPolicy {
}
impl Default for RetryPolicy {
+ /// The values of PySpark's `DefaultPolicy`, which the Scala client's
`defaultPolicy()` shares.
fn default() -> Self {
Self {
max_retries: Some(15),
- initial_backoff_ms: 1000,
- max_backoff_ms: Some(64000),
- backoff_multiplier: 2.0,
- jitter_ms: 0,
- min_jitter_threshold_ms: 0,
- recognize_server_retry_delay: false,
- max_server_retry_delay_ms: None,
+ initial_backoff_ms: 50,
+ max_backoff_ms: Some(60000),
+ backoff_multiplier: 4.0,
+ jitter_ms: 500,
+ min_jitter_threshold_ms: 2000,
+ recognize_server_retry_delay: true,
+ max_server_retry_delay_ms: Some(10 * 60 * 1000),
max_retry_exception_elapsed_time_ms: Some(
DEFAULT_MAX_RETRY_EXCEPTION_ELAPSED_TIME * 1000,
),
@@ -70,16 +73,57 @@ impl RetryPolicy {
/// Mirrors `pyspark.sql.connect.client.retries.DefaultPolicy.can_retry`,
on the code that
/// grpc-python gives the failure (see [`grpc_python_code`]): retry
transient `UNAVAILABLE`,
/// and `INTERNAL` errors whose message carries
`INVALID_CURSOR.DISCONNECTED` (a mid-stream
- /// cursor drop resumed via reattach).
+ /// cursor drop resumed via reattach). Any failure with a `RetryInfo`
detail is retried too,
+ /// whatever its code, as the server asks for it.
pub fn can_retry(&self, status: &tonic::Status) -> bool {
- match grpc_python_code(status) {
+ let transient = match grpc_python_code(status) {
tonic::Code::Unavailable => true,
tonic::Code::Internal =>
status.message().contains("INVALID_CURSOR.DISCONNECTED"),
_ => false,
- }
+ };
+ transient || retry_info(status).is_some()
}
}
+/// The `google.rpc.Status` of a failed RPC, from its
`grpc-status-details-bin`, whose details
+/// hold Any-packed messages.
+#[derive(Clone, PartialEq, Message)]
+struct StatusDetails {
+ #[prost(message, repeated, tag = "3")]
+ details: Vec<prost_types::Any>,
+}
+
+/// The `google.rpc.RetryInfo` of a failed RPC: how long the server asks the
client to wait.
+#[derive(Clone, PartialEq, Message)]
+struct RetryInfo {
+ #[prost(message, optional, tag = "1")]
+ retry_delay: Option<prost_types::Duration>,
+}
+
+/// The `google.rpc.RetryInfo` detail of a status, if it has one.
+fn retry_info(status: &tonic::Status) -> Option<RetryInfo> {
+ StatusDetails::decode(status.details())
+ .ok()?
+ .details
+ .into_iter()
+ .find(|detail| detail.type_url.rsplit('/').next() ==
Some("google.rpc.RetryInfo"))
+ .and_then(|detail| RetryInfo::decode(detail.value.as_slice()).ok())
+}
+
+/// The delay that the server asks for in the `RetryInfo` detail of a status,
in milliseconds.
+///
+/// Mirrors `pyspark.sql.connect.client.retries.extract_retry_delay`. A
negative delay is zero.
+pub fn retry_delay_ms(status: &tonic::Status) -> Option<u64> {
+ let delay = retry_info(status)?.retry_delay?;
+ let seconds = u64::try_from(delay.seconds).unwrap_or(0);
+ let nanos = u64::try_from(delay.nanos).unwrap_or(0);
+ Some(
+ seconds
+ .saturating_mul(1000)
+ .saturating_add(nanos / 1_000_000),
+ )
+}
+
/// The code of a failed RPC as grpc-python reports it, which PySpark's
retries and errors see.
/// A status that the server sent keeps its code. tonic gives some transport
failures other
/// codes: a connection that closes under a call is `UNAVAILABLE` in
grpc-python (tonic:
@@ -186,8 +230,8 @@ impl RetryPolicyState {
wait_time += rand_jitter(self.policy.jitter_ms);
}
- // Round to whole milliseconds
- Some(wait_time.ceil() as u64)
+ // Round down to whole milliseconds, as the reference's int()
+ Some(wait_time.floor() as u64)
}
pub fn policy(&self) -> &RetryPolicy {
@@ -407,6 +451,147 @@ mod tests {
assert_eq!(wait, Some(200)); // client backoff wins
}
+ /// A status of `code` with a `RetryInfo` detail that asks for a delay of
`seconds` and
+ /// `nanos`, as the server sends it in `grpc-status-details-bin`.
+ fn status_with_retry_info(code: tonic::Code, seconds: i64, nanos: i32) ->
tonic::Status {
+ let info = RetryInfo {
+ retry_delay: Some(prost_types::Duration { seconds, nanos }),
+ };
+ let detail = prost_types::Any {
+ type_url: "type.googleapis.com/google.rpc.RetryInfo".to_string(),
+ value: info.encode_to_vec(),
+ };
+ let details = StatusDetails {
+ details: vec![detail],
+ };
+ tonic::Status::with_details(code, "retry",
details.encode_to_vec().into())
+ }
+
+ #[test]
+ fn test_default_schedule_without_jitter() {
+ // The waits of PySpark's DefaultPolicy with the jitter off: 50 ms,
quadrupling up to
+ // the 60 s maximum, over the 15 retries.
+ let policy = RetryPolicy {
+ jitter_ms: 0,
+ min_jitter_threshold_ms: 0,
+ ..RetryPolicy::default()
+ };
+ let mut state = RetryPolicyState::new(policy);
+ let mut waits = Vec::new();
+ while let Some(wait) = state.next_attempt(None) {
+ waits.push(wait);
+ }
+ let mut expected = vec![50, 200, 800, 3200, 12800, 51200];
+ expected.extend([60000; 9]);
+ assert_eq!(waits, expected);
+ assert_eq!(waits.iter().sum::<u64>(), 608250);
+ }
+
+ #[test]
+ fn test_default_jitter_applies_only_at_or_above_the_threshold() {
+ // The waits below the 2 s threshold get no jitter. The 3.2 s wait
gets one in [0, 500) ms.
+ let mut jittered = Vec::new();
+ for _ in 0..20 {
+ let mut state = RetryPolicyState::new(RetryPolicy::default());
+ assert_eq!(state.next_attempt(None), Some(50));
+ assert_eq!(state.next_attempt(None), Some(200));
+ assert_eq!(state.next_attempt(None), Some(800));
+ let wait = state.next_attempt(None).expect("fourth retry allowed");
+ assert!(
+ (3200..3700).contains(&wait),
+ "expected 3200..3700, got {wait}"
+ );
+ jittered.push(wait);
+ std::thread::sleep(std::time::Duration::from_millis(1));
+ }
+ assert!(jittered.iter().any(|&wait| wait > 3200), "{jittered:?}");
+ // A wait of the max backoff is jittered too, in [60000, 60500).
+ let mut state = RetryPolicyState::new(RetryPolicy::default());
+ for _ in 0..8 {
+ state.next_attempt(None);
+ }
+ let wait = state.next_attempt(None).expect("last retry allowed");
+ assert!(
+ (60000..60500).contains(&wait),
+ "expected 60000..60500, got {wait}"
+ );
+ }
+
+ #[test]
+ fn test_server_retry_delay_from_retry_info_is_honored() {
+ let policy = RetryPolicy {
+ jitter_ms: 0,
+ min_jitter_threshold_ms: 0,
+ ..RetryPolicy::default()
+ };
+ // A RetryInfo of 2.5 s is the delay of the retry, above the 50 ms
base wait.
+ let status = status_with_retry_info(tonic::Code::Unavailable, 2,
500_000_000);
+ assert_eq!(retry_delay_ms(&status), Some(2500));
+ let mut state = RetryPolicyState::new(policy.clone());
+ assert_eq!(state.next_attempt(retry_delay_ms(&status)), Some(2500));
+ // A delay above max_server_retry_delay (10 minutes) is capped to it.
+ let status = status_with_retry_info(tonic::Code::Unavailable, 3600, 0);
+ assert_eq!(retry_delay_ms(&status), Some(3_600_000));
+ assert_eq!(state.next_attempt(retry_delay_ms(&status)), Some(600_000));
+ // A status without a RetryInfo has no delay, and the base wait
applies.
+ let status = tonic::Status::unavailable("server restarting");
+ assert_eq!(retry_delay_ms(&status), None);
+ assert_eq!(state.next_attempt(retry_delay_ms(&status)), Some(800));
+ // The delay is ignored when the policy does not recognize it.
+ let policy = RetryPolicy {
+ recognize_server_retry_delay: false,
+ ..policy
+ };
+ let status = status_with_retry_info(tonic::Code::Unavailable, 2, 0);
+ let mut state = RetryPolicyState::new(policy);
+ assert_eq!(state.next_attempt(retry_delay_ms(&status)), Some(50));
+ }
+
+ #[test]
+ fn
test_server_retry_delay_with_default_jitter_is_jittered_above_the_threshold() {
+ // The 2.5 s delay is above the 2 s threshold, so it gets the jitter
of [0, 500) ms.
+ let status = status_with_retry_info(tonic::Code::Unavailable, 2,
500_000_000);
+ for _ in 0..20 {
+ let mut state = RetryPolicyState::new(RetryPolicy::default());
+ let wait = state
+ .next_attempt(retry_delay_ms(&status))
+ .expect("allowed");
+ assert!(
+ (2500..3000).contains(&wait),
+ "expected 2500..3000, got {wait}"
+ );
+ }
+ }
+
+ #[test]
+ fn test_can_retry_a_status_with_retry_info_whatever_its_code() {
+ // As PySpark's DefaultPolicy, a RetryInfo of a failure makes it
retryable.
+ let p = RetryPolicy::default();
+ assert!(p.can_retry(&status_with_retry_info(
+ tonic::Code::ResourceExhausted,
+ 1,
+ 0
+ )));
+ assert!(p.can_retry(&status_with_retry_info(tonic::Code::Internal, 0,
0)));
+ // The same codes without the RetryInfo are not retried.
+
assert!(!p.can_retry(&tonic::Status::new(tonic::Code::ResourceExhausted,
"retry")));
+ // Another detail of the status is not a RetryInfo.
+ let detail = prost_types::Any {
+ type_url: "type.googleapis.com/google.rpc.ErrorInfo".to_string(),
+ value: Vec::new(),
+ };
+ let details = StatusDetails {
+ details: vec![detail],
+ };
+ let status = tonic::Status::with_details(
+ tonic::Code::ResourceExhausted,
+ "retry",
+ details.encode_to_vec().into(),
+ );
+ assert!(!p.can_retry(&status));
+ assert_eq!(retry_delay_ms(&status), None);
+ }
+
#[test]
fn test_attempt_count() {
let policy = RetryPolicy {
diff --git a/python/tests/_mock_connect_server.py
b/python/tests/_mock_connect_server.py
index 43d7d381..2f23d65a 100644
--- a/python/tests/_mock_connect_server.py
+++ b/python/tests/_mock_connect_server.py
@@ -291,6 +291,7 @@ def serve(connection):
self.execute_payload = b""
self.execute_failure = None
self.execute_error = None
+ self.retry_info_failures = []
# The InterruptRequests of each Interrupt, and the operations that
they interrupt.
self.interrupt_requests = []
self.interrupted_operations = set()
@@ -423,6 +424,9 @@ def serve(connection):
# 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.
execute_error = None
+ # Each (code name, delay in ms) of this list fails an ExecutePlan,
once, as the server
+ # does for a failure with a google.rpc.RetryInfo that asks for the
delay.
+ retry_info_failures = ()
# FetchErrorDetails returns `error_details` (raw
FetchErrorDetailsResponse fields)
# and records the error id asked for. Config Get returns the values in
`confs`, or
# else those of `default_confs`, the defaults of SQL configs of the
server, and
@@ -616,6 +620,24 @@ def serve(connection):
grpc.StatusCode.DEADLINE_EXCEEDED,
"Python thread could not run while the statement ran",
)
+ 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)),
+ )
+ )
+ context.set_trailing_metadata((("grpc-status-details-bin",
status),))
+ context.abort(getattr(grpc.StatusCode, code), "retry later")
if self.execute_failure:
code, message = (
self.execute_failure
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index b253b4e2..0831d1d6 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -16664,6 +16664,18 @@ def
test_grpc_errors_without_details_are_spark_connect_grpc_exceptions(mock_conn
assert error.value.operation_id ==
_request_operation_id(service.execute_requests[-1])
+def
test_a_failure_with_retry_info_is_retried_after_the_delay_of_the_server(mock_connect):
+ # As PySpark's DefaultPolicy: a failure that carries a RetryInfo is
retried whatever its
+ # code, after the retry delay that the server asks for (300 ms, above the
50 ms base wait).
+ spark, service = mock_connect
+ service.retry_info_failures = [("RESOURCE_EXHAUSTED", 300)]
+ start = time.monotonic()
+ spark.range(3).count() # the mock returns no rows, so only the success of
the call is checked
+ assert time.monotonic() - start >= 0.3
+ assert len(service.execute_requests) == 2
+ assert not service.retry_info_failures
+
+
def
test_analyze_errors_without_details_are_spark_connect_grpc_exceptions(mock_connect):
from pyspark.errors.exceptions.connect import SparkConnectGrpcException,
StatusCode
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]