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 dba7e53c [SPARK-61261][CONNECT] Reattach after a dropped connection 
instead of failing the query, in Spark Connect Rust as PySpark does
dba7e53c is described below

commit dba7e53c3e9104c3a3b78c8d09043e2282c8edf0
Author: Timothy Meehan <[email protected]>
AuthorDate: Tue Nov 10 10:28:22 2026 +0900

    [SPARK-61261][CONNECT] Reattach after a dropped connection instead of 
failing the query, in Spark Connect Rust as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61261](https://issues.apache.org/jira/browse/SPARK-61261): when the 
connection drops in the middle of a result, reattach to the execution and keep 
reading, as PySpark does, instead of failing the query.
    
    - `RetryPolicy::can_retry` (`crates/spark-connect-core/src/retries.rs`) 
retries a status with code `UNKNOWN` when tonic built it from a transport 
error. A connection reset during a response reaches the client as `UNKNOWN`, 
with an `h2::Error` or `hyper::Error` in the status's source chain. grpc-python 
reports the same reset as `UNAVAILABLE`, which PySpark retries. A status the 
server sent has no source, so a server-sent `UNKNOWN` (for example an 
exception) stays non-retryable.
    - The reattach loop in `crates/spark-connect-core/src/client.rs` already 
retries the statuses that `can_retry` accepts, so no change is needed there.
    - `h2` and `hyper` become direct dependencies of 
`apache-spark-connect-core`, to name the transport error types. Both are 
already in the lock file through tonic.
    
    ### Why are the changes needed?
    
    With a connection reset once after about 2 MB of a result, 
`spark.range(3_000_000).collect()` through the Rust client fails after about 
0.4 seconds with `[Unknown error] h2 protocol error: error reading a body from 
connection`. PySpark 4.3.0 reconnects, reattaches and returns all rows. The 
status that tonic reports for the reset is `UNKNOWN`, which the retry policy 
did not retry, so the reattach loop never ran. Matching on the status code 
alone would also retry server-sent `UNKNOWN` e [...]
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. A query whose connection drops in the middle of its result is now 
resumed by reattaching, and returns every row, instead of failing with 
`[Unknown error] h2 protocol error`. Server-sent errors are unchanged.
    
    ### How was this patch tested?
    
    Repro against a local Spark 4.3.0 Connect server, through a TCP proxy that 
resets the client connection after about 2 MB of the response, for 
`spark.range(3_000_000).collect()`:
    
    - pyspark-client 4.3.0, 1 reset: 3000000 rows, sum 4499998500000, 9.8 s. 3 
resets: 3000000 rows, sum 4499998500000, 8.0 s.
    - Rust client before this change, 1 reset: `SparkConnectGrpcException: 
[Unknown error] h2 protocol error: error reading a body from connection`, after 
0.4 s.
    - Rust client with this change, 1 reset: 3000000 rows, sum 4499998500000, 
6.4 s. 3 resets: 3000000 rows, sum 4499998500000, 5.6 s.
    
    Tests added:
    
    - `retries::tests::test_can_retry_a_connection_reset_during_a_response`: a 
local HTTP/2 server cuts a response off in the middle of a gRPC message and 
resets the connection. The status is `UNKNOWN` from tonic, and `can_retry` 
accepts it. It fails without the change.
    - `retries::tests::test_cannot_retry_an_unknown_the_server_sent`: the same 
server ends the response with a status the server sent, `UNKNOWN` "boom". 
`can_retry` rejects it. This passes with and without the change, and guards the 
server-sent case.
    - `crates/spark-connect/tests/e2e_reattach_drop.rs`: a TCP proxy in front 
of the server (gated on `SPARK_REMOTE`) resets the connection once and three 
times; each run collects every row and checks the count and the sum of ids. 
Both fail without the change with the error above, and pass with it.
    
    Checks: `cargo test -p apache-spark-connect --release --lib` 528 passed; 
`--no-run` builds, with and without `wasm-udf`; `cargo fmt --all --check` 
clean; `cargo test -p apache-spark-connect-core --release` with `SPARK_REMOTE` 
set, all suites pass (lib 152 passed, including the 2 new tests); clippy 
reports no diagnostic on the changed lines; offline Python suites 
`tests/test_dropin_offline.py tests/test_ml_offline.py 
tests/test_arrow_handoff.py` 2927 passed, 8 skipped; live drop-in, Ar [...]
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5 and Claude Haiku 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #435 from tdcmeehan/SPARK-61261-reattach-after-reset.
    
    Lead-authored-by: Timothy Meehan <[email protected]>
    Co-authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 .github/workflows/build_python_connect.yml      |   1 +
 Cargo.lock                                      |   2 +
 crates/spark-connect-core/Cargo.toml            |   3 +
 crates/spark-connect-core/src/retries.rs        |  91 ++++++++++++++++++
 crates/spark-connect/tests/e2e_reattach_drop.rs | 118 ++++++++++++++++++++++++
 5 files changed, 215 insertions(+)

diff --git a/.github/workflows/build_python_connect.yml 
b/.github/workflows/build_python_connect.yml
index eef6bf28..960fac10 100644
--- a/.github/workflows/build_python_connect.yml
+++ b/.github/workflows/build_python_connect.yml
@@ -559,6 +559,7 @@ jobs:
             --test e2e_coverage --test e2e_linear_svc --test 
e2e_linear_regression --test e2e_kmeans --test e2e_integration \
             --test arrow_map_input --test array_literal --test 
execute_plan_hook --test raw_relation \
             --test types_roundtrip \
+            --test e2e_reattach_drop \
             -- --test-threads=1
 
       - name: Rust WASM UDF e2e test (against the live server)
diff --git a/Cargo.lock b/Cargo.lock
index 0e6dd6e7..acc805f0 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -85,6 +85,8 @@ dependencies = [
  "bytes",
  "crc32fast",
  "futures",
+ "h2",
+ "hyper",
  "prost",
  "prost-types",
  "regex",
diff --git a/crates/spark-connect-core/Cargo.toml 
b/crates/spark-connect-core/Cargo.toml
index e7266250..717d6f07 100644
--- a/crates/spark-connect-core/Cargo.toml
+++ b/crates/spark-connect-core/Cargo.toml
@@ -29,6 +29,9 @@ regex = "1"
 prost-types.workspace = true
 crc32fast = "1"
 sha2 = "0.10"
+# Transport errors that tonic keeps as a status's source, for 
`RetryPolicy::can_retry`.
+h2 = "0.4"
+hyper = "1"
 
 [target.'cfg(all(target_arch = "aarch64", not(target_os = 
"windows")))'.dependencies]
 # sha2 0.10 requires this feature for ARM hardware acceleration; sha2-asm 
excludes Windows.
diff --git a/crates/spark-connect-core/src/retries.rs 
b/crates/spark-connect-core/src/retries.rs
index 75eaaaac..7c6b191c 100644
--- a/crates/spark-connect-core/src/retries.rs
+++ b/crates/spark-connect-core/src/retries.rs
@@ -70,15 +70,31 @@ impl RetryPolicy {
     /// Mirrors `pyspark.sql.connect.client.retries.DefaultPolicy.can_retry`:
     /// retry transient `UNAVAILABLE`, and `INTERNAL` errors whose message 
carries
     /// `INVALID_CURSOR.DISCONNECTED` (a mid-stream cursor drop resumed via 
reattach).
+    /// A connection reset is `UNKNOWN` in tonic but `UNAVAILABLE` in 
grpc-python, so it
+    /// is retried too.
     pub fn can_retry(&self, status: &tonic::Status) -> bool {
         match status.code() {
             tonic::Code::Unavailable => true,
             tonic::Code::Internal => 
status.message().contains("INVALID_CURSOR.DISCONNECTED"),
+            tonic::Code::Unknown => is_transport_error(status),
             _ => false,
         }
     }
 }
 
+/// Whether tonic built the status from a transport error, which it keeps as 
the status's
+/// source. A status the server sent has no source.
+fn is_transport_error(status: &tonic::Status) -> bool {
+    let mut source = std::error::Error::source(status);
+    while let Some(error) = source {
+        if error.is::<h2::Error>() || error.is::<hyper::Error>() {
+            return true;
+        }
+        source = error.source();
+    }
+    false
+}
+
 /// Stateful retry attempt tracker.
 ///
 /// Mirrors `pyspark.sql.connect.client.retries.RetryPolicyState`.
@@ -447,4 +463,79 @@ mod tests {
         // max_retries exhausted
         assert_eq!(state.next_attempt(None), None);
     }
+
+    /// Serves one response over HTTP/2, as a server does, and returns the 
address to call.
+    /// With `reset`, the response is cut off by a connection reset in the 
middle of a gRPC
+    /// message. Otherwise it ends with a status that the server sent: UNKNOWN 
"boom".
+    async fn serve_one_response(reset: bool) -> std::net::SocketAddr {
+        let listener = 
tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+        let address = listener.local_addr().unwrap();
+        tokio::spawn(async move {
+            let (socket, _) = listener.accept().await.unwrap();
+            if reset {
+                // Closing the socket now sends a RST instead of a FIN.
+                socket.set_zero_linger().unwrap();
+            }
+            let mut connection = h2::server::handshake(socket).await.unwrap();
+            let (_request, mut respond) = 
connection.accept().await.unwrap().unwrap();
+            let headers = tonic::codegen::http::Response::builder()
+                .header("content-type", "application/grpc")
+                .body(())
+                .unwrap();
+            let mut stream = respond.send_response(headers, false).unwrap();
+            if reset {
+                // The first 2 bytes of a 1000-byte gRPC message.
+                let partial = bytes::Bytes::from_static(&[0, 0, 0, 3, 232, 1, 
2]);
+                stream.send_data(partial, false).unwrap();
+            } else {
+                let mut trailers = tonic::codegen::http::HeaderMap::new();
+                trailers.insert("grpc-status", "2".parse().unwrap());
+                trailers.insert("grpc-message", "boom".parse().unwrap());
+                stream.send_trailers(trailers).unwrap();
+            }
+            // Keep the connection driven until the frames are written, then 
drop it.
+            let _ =
+                tokio::time::timeout(std::time::Duration::from_millis(200), 
connection.accept())
+                    .await;
+        });
+        address
+    }
+
+    /// The status that ends the first response of a call to `address`.
+    async fn status_of_first_response(address: std::net::SocketAddr) -> 
tonic::Status {
+        let channel = 
tonic::transport::Endpoint::from_shared(format!("http://{address}";))
+            .unwrap()
+            .connect()
+            .await
+            .unwrap();
+        let mut stub =
+            
spark_connect_proto::spark_connect_service_client::SparkConnectServiceClient::new(
+                channel,
+            );
+        let mut responses = stub
+            .execute_plan(spark_connect_proto::ExecutePlanRequest::default())
+            .await
+            .unwrap()
+            .into_inner();
+        responses
+            .message()
+            .await
+            .expect_err("the response ends with an error")
+    }
+
+    #[tokio::test]
+    async fn test_can_retry_a_connection_reset_during_a_response() {
+        let status = 
status_of_first_response(serve_one_response(true).await).await;
+        // tonic reports the reset as UNKNOWN, with the transport error as its 
source.
+        assert_eq!(status.code(), tonic::Code::Unknown);
+        assert!(RetryPolicy::default().can_retry(&status), "{status:?}");
+    }
+
+    #[tokio::test]
+    async fn test_cannot_retry_an_unknown_the_server_sent() {
+        let status = 
status_of_first_response(serve_one_response(false).await).await;
+        assert_eq!(status.code(), tonic::Code::Unknown);
+        assert_eq!(status.message(), "boom");
+        assert!(!RetryPolicy::default().can_retry(&status));
+    }
 }
diff --git a/crates/spark-connect/tests/e2e_reattach_drop.rs 
b/crates/spark-connect/tests/e2e_reattach_drop.rs
new file mode 100644
index 00000000..56d1772f
--- /dev/null
+++ b/crates/spark-connect/tests/e2e_reattach_drop.rs
@@ -0,0 +1,118 @@
+//! Server-gated end-to-end test of reattaching after a dropped connection. A 
TCP proxy in
+//! front of the server resets the connection in the middle of a large result, 
and the
+//! query still returns every row.
+//!
+//! Run with: `SPARK_REMOTE=sc://localhost:15002 cargo test --test 
e2e_reattach_drop`
+
+use std::sync::{Arc, Mutex};
+
+use spark_connect::SparkSession;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::{TcpListener, TcpStream};
+
+const ROWS: i64 = 3_000_000;
+/// The response bytes that a connection carries before the proxy resets it.
+const RESET_AFTER: usize = 2_000_000;
+
+/// Takes one of the resets that are still due, if any.
+fn take_reset(resets_due: &Mutex<usize>) -> bool {
+    let mut due = resets_due.lock().unwrap();
+    if *due == 0 {
+        return false;
+    }
+    *due -= 1;
+    true
+}
+
+/// Relays one client connection to the server. Once it has carried 
`RESET_AFTER` response
+/// bytes, and a reset is still due, it aborts the client connection with a 
RST.
+async fn relay(mut client: TcpStream, mut server: TcpStream, resets_due: 
Arc<Mutex<usize>>) {
+    let mut from_client = vec![0; 64 * 1024];
+    let mut from_server = vec![0; 64 * 1024];
+    let mut received = 0;
+    loop {
+        tokio::select! {
+            read = client.read(&mut from_client) => {
+                let n = match read {
+                    Ok(n) if n > 0 => n,
+                    _ => return,
+                };
+                if server.write_all(&from_client[..n]).await.is_err() {
+                    return;
+                }
+            }
+            read = server.read(&mut from_server) => {
+                let n = match read {
+                    Ok(n) if n > 0 => n,
+                    _ => return,
+                };
+                received += n;
+                if client.write_all(&from_server[..n]).await.is_err() {
+                    return;
+                }
+                if received >= RESET_AFTER && take_reset(&resets_due) {
+                    // With SO_LINGER 0, closing the client socket sends a RST 
instead of a FIN.
+                    client.set_zero_linger().unwrap();
+                    return;
+                }
+            }
+        }
+    }
+}
+
+/// Starts the proxy in front of the server at `remote`, and returns the URL 
to connect to
+/// and the number of resets that have not happened yet.
+async fn start_proxy(remote: &str, resets: usize) -> (String, 
Arc<Mutex<usize>>) {
+    let server = remote
+        .trim_start_matches("sc://")
+        .split(['/', ';'])
+        .next()
+        .unwrap()
+        .to_string();
+    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+    let address = listener.local_addr().unwrap();
+    let resets_due = Arc::new(Mutex::new(resets));
+    let due = resets_due.clone();
+    tokio::spawn(async move {
+        loop {
+            let (client, _) = listener.accept().await.unwrap();
+            let upstream = TcpStream::connect(&server).await.unwrap();
+            tokio::spawn(relay(client, upstream, due.clone()));
+        }
+    });
+    (format!("sc://{address}"), resets_due)
+}
+
+/// Collects `spark.range(ROWS)` through a proxy that resets the connection 
`resets` times,
+/// and checks that every row arrives.
+fn collect_through_resets(resets: usize) {
+    let Ok(remote) = std::env::var("SPARK_REMOTE") else {
+        return;
+    };
+    let runtime = tokio::runtime::Runtime::new().unwrap();
+    let (url, resets_due) = runtime.block_on(start_proxy(&remote, resets));
+
+    let spark = SparkSession::builder()
+        .remote(&url)
+        .get_or_create()
+        .unwrap();
+    let rows = spark.range(ROWS).unwrap().collect().unwrap();
+
+    assert_eq!(*resets_due.lock().unwrap(), 0, "the proxy did not reset");
+    assert_eq!(rows.len(), ROWS as usize);
+    let sum: i64 = rows
+        .iter()
+        .map(|row| row.get(0).unwrap().as_i64().unwrap())
+        .sum();
+    assert_eq!(sum, ROWS * (ROWS - 1) / 2);
+}
+
+#[test]
+fn collect_reattaches_after_a_connection_reset() {
+    collect_through_resets(1);
+}
+
+#[test]
+fn collect_reattaches_after_three_connection_resets() {
+    collect_through_resets(3);
+}


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

Reply via email to