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 efed9502 [SPARK-61440][CONNECT][FOLLOWUP] Send a deadline too long for
gRPC as the longest one, let a Ctrl-C end an unanswered artifact upload, and
keep the retry helpers crate-private
efed9502 is described below
commit efed95028aa80a6ebf3e0bd38ec9e2f3542ebf93
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 10:45:11 2026 +0900
[SPARK-61440][CONNECT][FOLLOWUP] Send a deadline too long for gRPC as the
longest one, let a Ctrl-C end an unanswered artifact upload, and keep the retry
helpers crate-private
### What changes were proposed in this pull request?
A follow-up of #508 / #536 (SPARK-61440), from a review of it:
- `with_deadline` (`crates/spark-connect-core/src/client.rs`) sends a
per-RPC deadline longer than gRPC's `grpc-timeout` can encode as the longest
timeout it encodes, 99,999,999 hours. tonic's `Request::set_timeout` panics
with "duration is unrealistically large" on a longer one, and `with_deadline`
runs before `stream_deadline_in` on every call, so the `Duration::MAX` deadline
that #508 made "no longer panic" still panicked there. No call reaches the
clamped timeout, so such a call r [...]
- `Retrying`, `Backoff`, `RetryError` and `retrying` in `retries.rs` are
`pub(crate)`: nothing outside the crate uses them, and #508 did not mean to add
them to the public API of `apache-spark-connect-core`. `RetryPolicy` and
`RetryPolicyState` stay public.
- **A Ctrl-C ends an artifact upload that the server does not answer.** The
backoffs of the upload's retries already ended with a signal, but the
AddArtifacts RPC of an attempt was not under `until_abort`, so `addArtifacts` /
`copyFromLocalToFs` against a server that accepts the connection and never
answers held until its deadline (about 80 s), where PySpark's blocking gRPC
call raises `KeyboardInterrupt` at once. The attempt now waits for its RPC
under `until_abort(ABORT_RETRIES)`, a [...]
- `test_backoff_waits_the_delay_of_the_attempt_before_a_retry` no longer
asserts that a backoff with no retry left returns within 40 ms, which a loaded
CI runner can miss; the `Backoff::GiveUp` result already shows that no retry is
made.
### Why are the changes needed?
`RpcDeadlines { reattachable_execute_plan: Some(Duration::MAX),
reattach_execute: Some(Duration::MAX), .. }` made `execute_plan_reattachable`
panic at tonic's `request.rs`, although #508 says that such deadlines no longer
panic.
### Does this PR introduce _any_ user-facing change?
Yes, on unreleased changes: a deadline longer than about 11,400 years no
longer panics, and the call runs to its result; a Ctrl-C during an unanswered
artifact upload raises `KeyboardInterrupt` at once in the Python client. The
four retry helpers leave the public API of the core crate, which has not been
released with them.
### How was this patch tested?
- `deadlines_too_long_for_the_grpc_timeout_are_sent_and_the_calls_run` in
`crates/spark-connect-core/tests/deadlines.rs`: a reattachable execution and
its reattach with `Duration::MAX` deadlines against the loopback server. It
panics without the fix and passes with it.
-
`test_with_deadline_too_long_for_the_grpc_timeout_is_the_longest_one_sent` in
`client.rs`: no header without a deadline, `600000m` for 600 s, `99999999H` for
`Duration::MAX`. It panics without the fix.
-
`test_sigint_while_an_artifact_upload_is_unanswered_raises_keyboard_interrupt`
in `python/tests/test_dropin_offline.py`: the mock server holds the
AddArtifacts call, and a SIGINT raises `KeyboardInterrupt` within about 1 s.
Without the change it waits for the mock's 15 s gate.
- `cargo test -p apache-spark-connect-core --release` (lib 215 passed;
`deadlines`, `reattach_cleanup`, `artifact_uploads`), `cargo test -p
apache-spark-connect --release --lib` (613 passed), the offline drop-in suites
(1991 passed), the artifact tests of `test_dropin_e2e.py`, `cargo test -p
apache-spark-connect -p apache-spark-connect-core --release --no-run`, `cargo
build -p pyspark-rs --release`, `cargo fmt --all -- --check`,
`scripts/audit_no_stubs.sh`, and `e2e_reattach_drop` aga [...]
### 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 #541 from HyukjinKwon/SPARK-61440-followup-deadlines-upload.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/spark-connect-core/src/client.rs | 41 ++++++++++++++++++++++++++--
crates/spark-connect-core/src/retries.rs | 21 +++++++-------
crates/spark-connect-core/tests/deadlines.rs | 26 ++++++++++++++++++
python/tests/_mock_connect_server.py | 35 +++++++++++++++++++++++-
python/tests/test_dropin_offline.py | 25 +++++++++++++++++
5 files changed, 134 insertions(+), 14 deletions(-)
diff --git a/crates/spark-connect-core/src/client.rs
b/crates/spark-connect-core/src/client.rs
index 3fa7fb25..6892c423 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -173,10 +173,14 @@ impl RpcDeadlines {
}
}
+/// The longest timeout gRPC encodes in its `grpc-timeout`, 99,999,999 hours.
tonic panics on a
+/// longer one, and no call reaches this one, so a longer deadline is sent as
this one.
+const LONGEST_GRPC_TIMEOUT: Duration = Duration::from_secs(99_999_999 * 60 *
60);
+
/// `request` with the timeout `deadline`, which gRPC sends as its
`grpc-timeout`.
fn with_deadline<T>(mut request: Request<T>, deadline: Option<Duration>) ->
Request<T> {
if let Some(deadline) = deadline {
- request.set_timeout(deadline);
+ request.set_timeout(deadline.min(LONGEST_GRPC_TIMEOUT));
}
request
}
@@ -2123,7 +2127,16 @@ impl SparkConnectClient {
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;
+ // An RPC that a signal ends is not answered, as an attempt of
with_retry.
+ let result = crate::runtime::until_abort(
+ crate::runtime::ABORT_RETRIES,
+ self.add_artifacts_rpc(frames),
+ )
+ .await;
+ let result = match result {
+ Some(result) => result,
+ None => return Err(RetryError::Aborted(wait_aborted())),
+ };
// 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)
@@ -2846,6 +2859,30 @@ mod tests {
assert_eq!(stream_deadline_in(Some(Duration::MAX)), None);
}
+ #[test]
+ fn
test_with_deadline_too_long_for_the_grpc_timeout_is_the_longest_one_sent() {
+ let timeout = |request: Request<()>| {
+ request
+ .metadata()
+ .get("grpc-timeout")
+ .map(|value| value.to_str().unwrap().to_string())
+ };
+ assert_eq!(timeout(with_deadline(Request::new(()), None)), None);
+ assert_eq!(
+ timeout(with_deadline(
+ Request::new(()),
+ Some(Duration::from_secs(600))
+ )),
+ Some("600000m".to_string())
+ );
+ // gRPC encodes at most 99,999,999 hours; tonic panics on a longer
timeout, so a longer
+ // deadline is sent as that, which no call reaches.
+ assert_eq!(
+ timeout(with_deadline(Request::new(()), Some(Duration::MAX))),
+ Some("99999999H".to_string())
+ );
+ }
+
#[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 da5dea79..f75567a0 100644
--- a/crates/spark-connect-core/src/retries.rs
+++ b/crates/spark-connect-core/src/retries.rs
@@ -294,7 +294,7 @@ impl RetryPolicyState {
///
/// [`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 {
+pub(crate) struct Retrying {
state: RetryPolicyState,
/// When the first retry made at once was asked for.
retry_exception_since: Option<std::time::Instant>,
@@ -304,7 +304,7 @@ pub struct Retrying {
/// What [`Retrying::backoff`] decides for a failed attempt.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum Backoff {
+pub(crate) 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
@@ -317,7 +317,7 @@ pub enum Backoff {
impl Retrying {
/// The retries of a call under `policy`, whose backoffs are waited whole.
- pub fn new(policy: &RetryPolicy) -> Self {
+ pub(crate) fn new(policy: &RetryPolicy) -> Self {
Self {
state: RetryPolicyState::new(policy.clone()),
retry_exception_since: None,
@@ -329,7 +329,7 @@ impl Retrying {
/// 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 {
+ pub(crate) fn ending_with_abort(mut self) -> Self {
self.ends_with_abort = true;
self
}
@@ -337,7 +337,7 @@ impl Retrying {
/// 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 {
+ pub(crate) async fn backoff(&mut self, status: &tonic::Status) -> Backoff {
if !self.state.policy().can_retry(status) {
return Backoff::GiveUp;
}
@@ -358,7 +358,7 @@ impl Retrying {
/// 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 {
+ pub(crate) fn retry_at_once(&mut self) -> bool {
let since = *self
.retry_exception_since
.get_or_insert_with(std::time::Instant::now);
@@ -372,7 +372,7 @@ impl Retrying {
/// Why a call made by [`retrying`] failed, and what an attempt of it fails
with.
#[derive(Debug)]
-pub enum RetryError<E> {
+pub(crate) 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),
@@ -395,7 +395,7 @@ pub enum RetryError<E> {
/// 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>(
+pub(crate) async fn retrying<T, E, Fut>(
mut retrying: Retrying,
mut before_retry: impl FnMut() -> Result<(), E>,
mut attempt: impl FnMut() -> Fut,
@@ -1321,10 +1321,9 @@ mod tests {
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();
+ // The retries are spent: no retry. (How long that takes is not
asserted: a loaded runner
+ // can deschedule the thread for longer than any bound.)
assert_eq!(retrying.backoff(&status).await, Backoff::GiveUp);
- assert!(started.elapsed() < std::time::Duration::from_millis(40));
}
#[tokio::test]
diff --git a/crates/spark-connect-core/tests/deadlines.rs
b/crates/spark-connect-core/tests/deadlines.rs
index 10dba6c6..3d749914 100644
--- a/crates/spark-connect-core/tests/deadlines.rs
+++ b/crates/spark-connect-core/tests/deadlines.rs
@@ -312,6 +312,32 @@ async fn
unary_call_past_its_deadline_is_deadline_exceeded() {
assert!(!error.message.contains("Timeout expired"), "{error:?}");
}
+#[tokio::test]
+async fn deadlines_too_long_for_the_grpc_timeout_are_sent_and_the_calls_run() {
+ // A deadline that gRPC cannot encode is never reached, so the execution
and its reattach
+ // run to their results, instead of the client panicking while it sets the
deadline.
+ let mut fixture = Fixture::start(
+ vec![streamed(vec![response("r1", false)])],
+ vec![streamed(vec![response("r2", true)])],
+ quick_retries(),
+ )
+ .await;
+ fixture.client.set_rpc_deadlines(RpcDeadlines {
+ reattachable_execute_plan: Some(Duration::MAX),
+ reattach_execute: Some(Duration::MAX),
+ ..RpcDeadlines::default()
+ });
+ let mut stream =
bounded(fixture.client.execute_plan_reattachable(execute_request()))
+ .await
+ .unwrap();
+ let ids = drain(&mut stream).await.unwrap();
+ assert_eq!(ids, ["r1", "r2"]);
+
+ assert_eq!(*fixture.state.executes.lock().unwrap(), 1);
+ assert_eq!(fixture.state.reattaches.lock().unwrap().len(), 1);
+ fixture.assert_release_all_count(1).await;
+}
+
#[tokio::test]
async fn execute_plan_past_its_deadline_is_bounded_as_the_reference_retries() {
// As the reference: the deadline of the initial ExecutePlan is a
RetryException, which is
diff --git a/python/tests/_mock_connect_server.py
b/python/tests/_mock_connect_server.py
index 8a783fc0..21309dfb 100644
--- a/python/tests/_mock_connect_server.py
+++ b/python/tests/_mock_connect_server.py
@@ -281,6 +281,9 @@ def serve(connection):
# execution released by close with one released by normal completion.
block_result_complete = False
result_complete_operations = []
+ # With `block_add_artifacts` set, AddArtifacts holds its answer until
the gate is released.
+ block_add_artifacts = False
+ add_artifacts_gate = Event()
# Each AnalyzePlanRequest, recorded.
analyze_requests = []
@@ -300,6 +303,7 @@ def serve(connection):
self.block_result_complete = False
self.result_complete_operations = []
self.analyze_requests = []
+ self.block_add_artifacts = False
# The isLocal answer of a test, or None for the answer of the
plan, and a failure.
self.local = None
self.local_failure = False
@@ -350,7 +354,12 @@ def serve(connection):
self.listener_removals = 0
self.listener_streams_finished = 0
self.listener_condition.notify_all()
- for name in ("listener_register_gate", "listener_remove_gate",
"release_session_gate"):
+ for name in (
+ "listener_register_gate",
+ "listener_remove_gate",
+ "release_session_gate",
+ "add_artifacts_gate",
+ ):
gate = getattr(self, name, None)
if gate is not None:
gate.set()
@@ -368,6 +377,7 @@ def serve(connection):
self.release_session_events = []
self.release_session_blocked = False
self.release_session_gate = Event()
+ self.add_artifacts_gate = Event()
def analyze(self, request, context):
# AnalyzePlanRequest.session_id=1, echoed as
AnalyzePlanResponse.session_id=1, as the
@@ -496,6 +506,20 @@ def serve(connection):
rpc_events = []
set_confs = []
+ def add_artifacts(self, requests, context):
+ # AddArtifactsRequest.session_id=1, echoed as
AddArtifactsResponse.session_id=2 with
+ # no artifact summary. With `block_add_artifacts` set, the answer
waits for the gate,
+ # as a server that accepts an upload and does not answer it.
+ session_id = b""
+ for request in requests:
+ session_id = parse_message(request).get(1, [b""])[0]
+ break
+ if self.block_add_artifacts and not
self.add_artifacts_gate.wait(15):
+ context.abort(
+ grpc.StatusCode.INVALID_ARGUMENT, "artifact upload gate
was not released"
+ )
+ return message_field(2, session_id)
+
def release_session(self, request, context):
with self.listener_condition:
self.release_session_calls += 1
@@ -869,6 +893,7 @@ def serve(connection):
"Config": grpc.unary_unary_rpc_method_handler(service.config),
"CloneSession":
grpc.unary_unary_rpc_method_handler(service.clone_session),
"Interrupt":
grpc.unary_unary_rpc_method_handler(service.interrupt),
+ "AddArtifacts":
grpc.stream_unary_rpc_method_handler(service.add_artifacts),
}
server.add_generic_rpc_handlers(
(grpc.method_handlers_generic_handler("spark.connect.SparkConnectService",
handlers),)
@@ -928,6 +953,9 @@ def serve(connection):
elif command[0] == "release_session_release":
service.release_session_gate.set()
connection.send(None)
+ elif command[0] == "release_add_artifacts":
+ service.add_artifacts_gate.set()
+ connection.send(None)
finally:
server.stop(0).wait()
@@ -1012,6 +1040,11 @@ class RemoteService:
assert self.connection.poll(10), "Mock server did not respond"
self.connection.recv()
+ def release_add_artifacts(self):
+ self.connection.send(("release_add_artifacts",))
+ assert self.connection.poll(10), "Mock server did not respond"
+ self.connection.recv()
+
@contextmanager
def mock_connect_session():
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 9572fdad..24e0283a 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -18951,6 +18951,31 @@ def
test_sigint_while_an_unavailable_execute_is_retried_raises_keyboard_interrup
assert time.monotonic() - started < 3
+def
test_sigint_while_an_artifact_upload_is_unanswered_raises_keyboard_interrupt(
+ mock_connect, tmp_path
+):
+ # As PySpark's: the call of an upload that the server accepts and does not
answer waits in
+ # grpc's blocking call, which the signal interrupts, so KeyboardInterrupt
is raised at once.
+ import signal
+ import threading
+
+ spark, service = mock_connect
+ note = tmp_path / "note.txt"
+ note.write_bytes(b"x")
+ service.block_add_artifacts = True
+ timer = threading.Timer(0.5, os.kill, (os.getpid(), signal.SIGINT))
+ started = time.monotonic()
+ timer.start()
+ try:
+ with pytest.raises(KeyboardInterrupt):
+ spark.addArtifacts(str(note), file=True)
+ finally:
+ timer.cancel()
+ service.block_add_artifacts = False
+ service.release_add_artifacts()
+ 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
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]