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 74ee8108 [SPARK-61415][CONNECT] Back off and bound the reattaches of a 
result stream that keeps failing, and raise NO_ACTIVE_SESSION when the plan 
compression lookup closed the client, in Spark Connect Rust as PySpark does
74ee8108 is described below

commit 74ee81089336c69226a18d87ac18b535828aaaec
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 09:53:14 2026 +0900

    [SPARK-61415][CONNECT] Back off and bound the reattaches of a result stream 
that keeps failing, and raise NO_ACTIVE_SESSION when the plan compression 
lookup closed the client, in Spark Connect Rust as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61415](https://issues.apache.org/jira/browse/SPARK-61415): 
follow-ups of a review of the Rust core transport 
(`crates/spark-connect-core`), each checked against PySpark 4.3.0's 
`pyspark/sql/connect/client/{core,reattach,retries,artifact}.py`:
    
    - **Reattach backoff** (`ReattachableResponseStream::message`, 
`client.rs`): a retryable failure of a stream that has opened is now an attempt 
of the retry policy, as PySpark's 
`ExecutePlanResponseReattachableIterator._has_next` counts it. This also covers 
a stream that a reattach opened and that fails before its next response. The 
client waits the policy's backoff before it reattaches, and once the policy's 
retries are spent, that failure is the error of the stream. The count is kept 
[...]
    - **A client that the plan compression lookup closed** (`execute_plan`, 
`execute_plan_reattachable`, `analyze_plan`): after the plan is compressed and 
the hooks ran, they check again that the client is open, so they raise 
`NO_ACTIVE_SESSION` and send nothing. On the first plan of a client, the lookup 
of the plan compression confs can close the client: a response of another 
server-side session ID does, and so does `INVALID_HANDLE.SESSION_CHANGED`. 
These three are the only paths that ru [...]
    - **Request fields** (`client.rs`):
      - The FetchErrorDetails and the stack-trace Config that the client sends 
while it raises a server error (`error_details`, `conf_while_raising`) carry 
the user context extensions of the client, as all of the client's other 
FetchErrorDetails and Config requests do.
      - AddArtifacts and ArtifactStatus requests no longer carry `client_type` 
(`add_artifacts_rpc`, `artifact_status_rpc`). The user agent is still sent in 
the gRPC `user-agent` header.
    - **Docs** (`docs/compatibility.md`): the note on transport codes now gives 
the old code of each failure. A GOAWAY used to report the code of its reason, 
such as `INTERNAL` for `NO_ERROR` and `RESOURCE_EXHAUSTED` for 
`ENHANCE_YOUR_CALM`. The note said it was `UNKNOWN` or `CANCELLED`.
    
    ### Why are the changes needed?
    
    - **Reattach backoff.**
      - PySpark's `_has_next` (reattach.py:167-206) runs the `ReattachExecute` 
and the `next()` of its stream in one attempt of a `Retrying`. A retryable 
failure there costs an attempt, waits the policy's backoff (`Retrying._wait`), 
and is raised after `max_retries`, whether it came before or after the response 
headers.
      - Ours counted and waited only when the reattach call itself failed. If 
each reattach got its headers and its stream then failed, the client reattached 
at once, without end, and each time the server resent the response from its 
buffer.
      - The probe: `spark.range(1).select(repeat(lit("x"), 300000)).collect()` 
through a TCP proxy that resets every connection after 100 KB, for 3 s.
        - Before the fix (review run on the drop-in at 447dfab1): 197 
connections in 1.3 s, 2-5 ms apart.
        - With the fix, against a local 4.3.0 server: 2 connections, at 1.04 s 
and 3.05 s. These are the 1 s and 2 s backoffs of the client's default policy.
        - Official PySpark 4.3.0: 4 connections, at 0.12, 0.33, 1.15 and 4.69 
s. These are its `DefaultPolicy` backoffs of 50, 200, 800 and 3200 ms.
        - All three returned the 300000-character row.
    - **A client that the plan compression lookup closed.**
      - PySpark compresses a plan while it builds it, and 
`_get_plan_compression_threshold_and_algorithm` (core.py:2714-2740) swallows 
the lookup's error. The execution or analysis then reads `self._stub` 
(core.py:965-970), which raises `NO_ACTIVE_SESSION` for a closed client before 
any request is sent.
      - Ours sent the ExecutePlan or AnalyzePlan anyway. This happens when the 
server restarts between a session's first RPC and its first plan.
      - With an in-process fake server whose server-side session ID changes 
after the first response, `spark.conf.set(...)` and then 
`spark.range(1).collect()` gave:
        - before: `PySparkAssertionError: Received incorrect server side 
session identifier for request...`, with the calls `Config, Config, 
ExecutePlan`;
        - after, and official: `SparkConnectException [NO_ACTIVE_SESSION]`, 
with the calls `Config, Config`.
    - **Request fields.**
      - PySpark's `_fetch_enriched_error` (core.py:2349-2370) calls 
`_update_request_with_user_context_extensions`.
      - `_display_server_stack_trace` reads the conf through `RuntimeConf.get` 
→ `config()` → `_config_request_with_metadata` (core.py:2020-2031), which adds 
the extensions as well.
      - PySpark's `ArtifactManager` builds AddArtifacts and ArtifactStatus 
requests without a `client_type` (artifact.py:384-460).
      - A fake-server probe, with a global user context extension, an upload of 
a 40 KB file, and an ExecutePlan that fails with an `errorId`:
        - official: no `client_type` on the AddArtifacts frames or on 
ArtifactStatus; the extension on the FetchErrorDetails and on both stack-trace 
Configs;
        - ours before: `client_type` on the AddArtifacts frames; no extension 
on the FetchErrorDetails or the stack-trace Configs;
        - ours after: the same as official.
      - The existing test 
`requests_carry_the_client_type_and_the_observed_session_of_pyspark` asserted 
the `client_type` of the artifact requests under the comment "As PySpark". 
SPARK-60942 (#164) had added that field to follow the Scala client.
    - **Docs.** The codes were checked with tonic 0.14.6: 
`Status::code_from_h2` maps the reason of the error, and the GOAWAY test in 
`retries.rs`, printed in five runs, gave `Internal` for `NO_ERROR` and 
`INTERNAL_ERROR` and `ResourceExhausted` for `ENHANCE_YOUR_CALM`.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes:
    - **Reattaches.** A connection that keeps failing in the middle of a result 
is now reattached with the retry policy's backoff, and the stream fails once 
the policy's retries are spent. Before, it was reattached at once, without end. 
With the default policy, each reattach after a dropped connection now waits 1 s 
first, the first backoff of the client's default policy; with PySpark's 
`DefaultPolicy` of SPARK-61390 (#480) that is 50 ms, as in PySpark.
    - **Closed client.** An execution or analysis whose plan compression lookup 
finds that the server restarted raises `NO_ACTIVE_SESSION` without sending its 
request.
    - **Request fields.**
      - The FetchErrorDetails and stack-trace Config requests sent while 
raising an error carry the user context extensions.
      - AddArtifacts and ArtifactStatus requests carry no `client_type`.
    
    ### How was this patch tested?
    
    - **New Rust tests.** Each fails without the fix: the source hunks of 
`client.rs` were reverted with `patch -R`, the tests rebuilt and run, and the 
hunks applied again.
      - `crates/spark-connect-core/tests/deadlines.rs`, placed after 
`reattach_past_its_deadline_is_the_error_once_the_bound_passes`: 
`reattach_that_fails_after_it_opens_is_a_retry_of_the_policy_as_pyspark`.
        - The setup:
          - The ExecutePlan streams `r1` and fails with UNAVAILABLE.
          - Every reattach then opens and fails before a response, except the 
third, which streams `r2` and fails.
          - The policy has `max_retries` 3 and backoffs of 10, 20 and 40 ms.
        - It checks that `r1` and `r2` are read, and that the stream then fails 
with UNAVAILABLE. Each response gets three reattaches, six in all.
        - It checks that each reattach arrives at least its backoff after the 
failure before it. The fixture now records the time of each ReattachExecute 
(`reattached_at`).
        - Without the fix, the stream reattached past every failure and 
returned the server's `complete` response.
      - `crates/spark-connect-core/tests/server_session.rs`, placed after 
`a_restarted_server_raises_and_closes_the_client`: 
`a_restart_that_the_plan_compression_lookup_sees_sends_no_plan_as_pyspark`.
        - For a reattachable ExecutePlan, a plain ExecutePlan and an 
AnalyzePlan of a schema, each on a new client, the server restarts before the 
first plan.
        - The call raises `NO_ACTIVE_SESSION`, and the server receives only the 
two Configs of each client.
        - Without the fix, all three calls returned without an error.
    - **Adjusted Rust tests.**
      - `client.rs` `request_fields_tests`: 
`requests_carry_the_client_type_and_the_observed_session_of_pyspark` is now 
`requests_carry_the_client_type_extensions_and_observed_session_of_pyspark`.
        - The client has a global user context extension, and raises an error 
with an `errorId` through `error_from_status`, which sends a FetchErrorDetails 
and a Config.
        - For each request type, it checks the client type (none on the 
artifact requests), the observed server-side session ID, and the user context 
extensions. The extensions are on the requests of PySpark's 
`_update_request_with_user_context_extensions` and on the ReleaseExecute of the 
execution. They are not on ReleaseSession, CloneSession or the artifact 
requests.
        - Without the fix, the FetchErrorDetails of the error had no extension.
      - `crates/spark-connect-core/tests/artifact_uploads.rs` 
`a_large_file_is_uploaded_as_one_chunked_artifact`: the frames carry no client 
type. Without the fix, they carried the user agent.
    - **Adjusted Python test.** In `python/tests/test_arrow_handoff.py`, 
`_assert_artifact_contexts` checks that the artifact requests carry no client 
type, and checks the user agent on the gRPC header. Without the fix, all 6 
attribution tests failed at `assert not context["has_client_type"]`.
    - **Runs, all passed:**
      - `cargo test -p apache-spark-connect-core --release --lib`: 174 passed.
      - The core integration tests `deadlines` (16), `server_session` (6), 
`artifact_uploads` (6), `reattach_cleanup` (15), `user_context` (4) and 
`integration_test` (3 ignored, as before).
      - The two new tests, run 8 more times each.
      - `SPARK_REMOTE=sc://localhost:15014 cargo test -p apache-spark-connect 
--release --test e2e_reattach_drop`, against a local Spark 4.3.0 server: 2 
passed. This is SPARK-61261's reattach after one and three connection resets.
      - Offline Python:
        - `tests/test_arrow_handoff.py -k "attribution or cached_arrow_upload 
or artifact or file_upload"`: 12 passed;
        - `tests/test_dropin_offline.py -k "reattach or artifact or fetch_error 
or stacktrace or stack_trace or no_active or restart or server_side_session or 
compress or retry or unavailable or dropped or session_change or extension or 
error_detail or enriched"`: 31 passed.
      - The probes above, of both clients.
      - Checks:
        - `cargo test -p apache-spark-connect --release --no-run`, also with 
`--features wasm-udf`, and `cargo test -p apache-spark-connect-core --release 
--no-run`, all without warnings;
        - `cargo fmt --all --check`;
        - `cargo clippy -p apache-spark-connect-core --release --all-targets`, 
which reports nothing on the changed lines.
    
    ### 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 #488 from HyukjinKwon/SPARK-61415-reattach-backoff.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/spark-connect-core/src/client.rs            | 117 +++++++++++++++++----
 .../spark-connect-core/tests/artifact_uploads.rs   |   5 +-
 crates/spark-connect-core/tests/deadlines.rs       |  61 ++++++++++-
 crates/spark-connect-core/tests/server_session.rs  |  61 +++++++++++
 docs/compatibility.md                              |   9 +-
 python/tests/test_arrow_handoff.py                 |  15 ++-
 6 files changed, 233 insertions(+), 35 deletions(-)

diff --git a/crates/spark-connect-core/src/client.rs 
b/crates/spark-connect-core/src/client.rs
index 0f25f63a..125abdda 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -1105,6 +1105,10 @@ impl SparkConnectClient {
         // server-side session ID, as PySpark builds the plan before the 
request.
         self.observe_on(&mut request.client_observed_server_side_session_id);
         let request = self.hooked_and_compressed(request).await?;
+        // As PySpark reads its `_stub` once the plan is built and the hooks 
ran: the lookup of
+        // the plan compression of the first plan closes the client when it 
sees that the server
+        // restarted, and then the execution raises NO_ACTIVE_SESSION and 
sends nothing.
+        self.ensure_open()?;
         let mut req = Request::new(request);
         self._attach_metadata(&mut req);
         match self.stub.clone().execute_plan(req).await {
@@ -1241,6 +1245,8 @@ impl SparkConnectClient {
                 self.compress_plan(plan).await;
             }
         }
+        // As in `execute_plan`: the lookup of the plan compression may have 
closed the client.
+        self.ensure_open()?;
         let response = self
             .with_retry(|| {
                 let deadline = self.rpc_deadlines.analyze_plan;
@@ -1319,6 +1325,9 @@ impl SparkConnectClient {
         // server-side session ID, as PySpark builds the plan before the 
request.
         self.observe_on(&mut request.client_observed_server_side_session_id);
         let request = self.hooked_and_compressed(request).await?;
+        // As in `execute_plan`: the lookup of the plan compression may have 
closed the client,
+        // and PySpark reads its `_stub` before it makes the iterator, so 
nothing is released.
+        self.ensure_open()?;
         let iter = ExecutePlanResponseReattachableIterator::new(request);
         // Before the first RPC, so that an execution that waits for the 
server is in flight.
         let inflight = InflightGuard::register(
@@ -1427,6 +1436,8 @@ impl SparkConnectClient {
             ..Default::default()
         };
         let mut request = request;
+        // As `_fetch_enriched_error`, whose request carries the user context 
extensions.
+        self.extend_user_context(&mut request.user_context);
         self.observe_on(&mut request.client_observed_server_side_session_id);
         let deadline = self.rpc_deadlines.fetch_error_details;
         let mut req = with_deadline(Request::new(request), deadline);
@@ -1476,6 +1487,9 @@ impl SparkConnectClient {
             ..Default::default()
         };
         let mut request = request;
+        // As the request of PySpark's `RuntimeConf.get`, which carries the 
user context
+        // extensions, as every Config request.
+        self.extend_user_context(&mut request.user_context);
         self.observe_on(&mut request.client_observed_server_side_session_id);
         let deadline = self.rpc_deadlines.config;
         let mut req = with_deadline(Request::new(request), deadline);
@@ -2065,18 +2079,16 @@ impl SparkConnectClient {
         }
     }
 
-    /// The AddArtifacts call of `requests`, once. Stamps user_context and 
client_type on
-    /// every frame as it is sent; all upload paths must go through here. As 
PySpark's
-    /// ArtifactManager, the frames carry no observed server-side session ID.
+    /// The AddArtifacts call of `requests`, once. Stamps user_context on 
every frame as it is
+    /// sent; all upload paths must go through here. As PySpark's 
ArtifactManager, the frames
+    /// carry no client type and no observed server-side session ID.
     async fn add_artifacts_rpc(
         &self,
         requests: impl Iterator<Item = 
spark_connect_proto::AddArtifactsRequest> + Send + 'static,
     ) -> std::result::Result<spark_connect_proto::AddArtifactsResponse, 
tonic::Status> {
         let user_context = self.new_user_context();
-        let client_type = self.user_agent.clone();
         let requests = requests.map(move |mut request| {
             request.user_context = Some(user_context.clone());
-            request.client_type = Some(client_type.clone());
             request
         });
         let deadline = self.rpc_deadlines.add_artifacts;
@@ -2110,7 +2122,8 @@ impl SparkConnectClient {
     }
 
     /// The ArtifactStatus call of `names`, once: the response, which says 
whether each artifact
-    /// exists. As PySpark's, the request carries no observed server-side 
session ID.
+    /// exists. As PySpark's, the request carries no client type and no 
observed server-side
+    /// session ID.
     async fn artifact_status_rpc(
         &self,
         names: &[String],
@@ -2118,7 +2131,6 @@ impl SparkConnectClient {
         let mut request = ArtifactStatusesRequest::default();
         request.session_id = self.session_id.clone();
         request.user_context = Some(self.new_user_context());
-        request.client_type = Some(self.user_agent.clone());
         request.names = names.to_vec();
 
         let deadline = self.rpc_deadlines.artifact_status;
@@ -2386,6 +2398,17 @@ impl ReattachableResponseStream {
                     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
+                    // reattaching and is the error once the policy's retries 
are spent. Else a
+                    // connection that keeps failing after the headers of each 
reattach is
+                    // reattached at once, without end. As at the other 
retries, the server's
+                    // RetryInfo delay of the failure, if any, is the wait.
+                    match retry_state.next_attempt(retry_delay_ms(&status)) {
+                        Some(wait_ms) => 
tokio::time::sleep(Duration::from_millis(wait_ms)).await,
+                        None => return 
Err(self.fail_with_status(status).await),
+                    }
                     self.reattach(&mut retry_state, &mut retry_exception_since)
                         .await?;
                 }
@@ -3593,14 +3616,19 @@ mod request_fields_tests {
         }
     }
 
-    /// The client type and the observed server-side session ID of a request 
of `method`.
-    fn fields_of(method: &str, bytes: &[u8]) -> (Option<String>, 
Option<String>) {
+    /// The client type, the observed server-side session ID and the user 
context extensions of
+    /// a request of `method`.
+    fn fields_of(
+        method: &str,
+        bytes: &[u8],
+    ) -> (Option<String>, Option<String>, Vec<prost_types::Any>) {
         macro_rules! fields {
             ($request:ty) => {{
                 let request = <$request>::decode(bytes).unwrap();
                 (
                     request.client_type,
                     request.client_observed_server_side_session_id,
+                    request.user_context.unwrap_or_default().extensions,
                 )
             }};
         }
@@ -3615,14 +3643,43 @@ mod request_fields_tests {
             "ArtifactStatus" => fields!(ArtifactStatusesRequest),
             "AddArtifacts" => 
fields!(spark_connect_proto::AddArtifactsRequest),
             // Of no observed server-side session ID.
-            "ReleaseSession" => (
-                ReleaseSessionRequest::decode(bytes).unwrap().client_type,
-                None,
-            ),
+            "ReleaseSession" => {
+                let request = ReleaseSessionRequest::decode(bytes).unwrap();
+                (
+                    request.client_type,
+                    None,
+                    request.user_context.unwrap_or_default().extensions,
+                )
+            }
             other => panic!("unexpected method {other}"),
         }
     }
 
+    /// The status of an error that the server raised and keeps the details of 
under
+    /// `error_id`: a `google.rpc.Status` of an `ErrorInfo` of that `errorId`.
+    fn error_kept_under(error_id: &str) -> tonic::Status {
+        #[derive(Clone, PartialEq, prost::Message)]
+        struct ErrorInfo {
+            #[prost(map = "string, string", tag = "3")]
+            metadata: std::collections::HashMap<String, String>,
+        }
+        #[derive(Clone, PartialEq, prost::Message)]
+        struct RpcStatus {
+            #[prost(message, repeated, tag = "3")]
+            details: Vec<prost_types::Any>,
+        }
+        let info = ErrorInfo {
+            metadata: [("errorId".to_string(), error_id.to_string())].into(),
+        };
+        let status = RpcStatus {
+            details: vec![prost_types::Any {
+                type_url: "type.googleapis.com/google.rpc.ErrorInfo".into(),
+                value: info.encode_to_vec(),
+            }],
+        };
+        tonic::Status::with_details(tonic::Code::Internal, "boom", 
status.encode_to_vec().into())
+    }
+
     /// As PySpark's hook, which would put in the plan of `to_proto`, which 
compresses it: the plan
     /// that a hook puts in is compressed, and one that the hook keeps 
compressed is kept.
     #[tokio::test]
@@ -3691,7 +3748,7 @@ mod request_fields_tests {
     }
 
     #[tokio::test]
-    async fn 
requests_carry_the_client_type_and_the_observed_session_of_pyspark() {
+    async fn 
requests_carry_the_client_type_extensions_and_observed_session_of_pyspark() {
         let received: Received = Default::default();
         let listener = 
tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
         let address = listener.local_addr().unwrap();
@@ -3713,6 +3770,11 @@ mod request_fields_tests {
         };
         let client = SparkConnectClient::connect(&builder).await.unwrap();
         let session_id = client.session_id().to_string();
+        let extension = prost_types::Any {
+            type_url: "example.org/context".into(),
+            value: vec![1, 2, 3],
+        };
+        client.add_global_user_context_extension(extension.clone());
 
         // The first request reads the plan compression of the server for the 
plan of the
         // execution, and its response gives the server-side session ID, which 
the execution
@@ -3756,6 +3818,9 @@ mod request_fields_tests {
             })
             .await
             .unwrap();
+        // An error that the server keeps the details of: raising it fetches 
them, and reads the
+        // conf of the server's stack trace.
+        client.error_from_status(error_kept_under("error-1")).await;
         client.artifact_status(&["files/a.txt"]).await.unwrap();
         let file = tempfile::NamedTempFile::new().unwrap();
         client
@@ -3794,13 +3859,21 @@ mod request_fields_tests {
         ] {
             assert!(requests.iter().any(|(m, _)| m == method), "no {method}");
         }
+        // The lookup, the explicit Config and the stack trace conf of the 
error; the explicit
+        // FetchErrorDetails and that of the error.
+        let count = |method: &str| requests.iter().filter(|(m, _)| m == 
method).count();
+        assert_eq!((count("Config"), count("FetchErrorDetails")), (3, 2));
         for (index, (method, bytes)) in requests.iter().enumerate() {
-            // As PySpark: the user agent, but "python" for CloneSession, and 
the observed
-            // server-side session ID, once a response gave it, but on 
ReleaseExecute,
-            // ReleaseSession, CloneSession and the artifact requests.
+            // As PySpark: the user agent, but "python" for CloneSession and 
none for the requests
+            // of the ArtifactManager; the observed server-side session ID, 
once a response gave
+            // it, but on ReleaseExecute, ReleaseSession, CloneSession and the 
artifact requests;
+            // and the user context extensions on the requests of
+            // `_update_request_with_user_context_extensions`, those that an 
error sends too, and
+            // on the ReleaseExecute of the user context of the execution.
             let client_type = match method.as_str() {
-                "CloneSession" => "python",
-                _ => user_agent.as_str(),
+                "CloneSession" => Some("python".to_string()),
+                "ArtifactStatus" | "AddArtifacts" => None,
+                _ => Some(user_agent.clone()),
             };
             let observed = match method.as_str() {
                 _ if index == 0 => None,
@@ -3808,9 +3881,13 @@ mod request_fields_tests {
                 | "AddArtifacts" => None,
                 _ => Some(SERVER_ID.to_string()),
             };
+            let extensions = match method.as_str() {
+                "ReleaseSession" | "CloneSession" | "ArtifactStatus" | 
"AddArtifacts" => vec![],
+                _ => vec![extension.clone()],
+            };
             assert_eq!(
                 fields_of(method, bytes),
-                (Some(client_type.to_string()), observed),
+                (client_type, observed, extensions),
                 "{method}"
             );
         }
diff --git a/crates/spark-connect-core/tests/artifact_uploads.rs 
b/crates/spark-connect-core/tests/artifact_uploads.rs
index 62198a2c..b8fecebf 100644
--- a/crates/spark-connect-core/tests/artifact_uploads.rs
+++ b/crates/spark-connect-core/tests/artifact_uploads.rs
@@ -196,11 +196,12 @@ async fn 
a_large_file_is_uploaded_as_one_chunked_artifact() {
     for frame in frames.iter().skip(1) {
         assert!(matches!(frame.payload, Some(Payload::Chunk(_))));
     }
-    // Every frame carries the CRC of its chunk, and the session and user 
context of the client.
+    // Every frame carries the CRC of its chunk, and the session and user 
context of the client,
+    // and, as the frames of PySpark's ArtifactManager, no client type.
     for frame in frames {
         assert_eq!(frame.session_id, client.session_id());
         assert!(frame.user_context.is_some());
-        assert!(frame.client_type.is_some());
+        assert_eq!(frame.client_type, None);
     }
     let crcs: Vec<i64> = frames
         .iter()
diff --git a/crates/spark-connect-core/tests/deadlines.rs 
b/crates/spark-connect-core/tests/deadlines.rs
index 6fbedc2d..690da763 100644
--- a/crates/spark-connect-core/tests/deadlines.rs
+++ b/crates/spark-connect-core/tests/deadlines.rs
@@ -25,7 +25,7 @@ use std::future::Future;
 use std::pin::Pin;
 use std::sync::{Arc, Mutex};
 use std::task::{Context, Poll};
-use std::time::Duration;
+use std::time::{Duration, Instant};
 
 use futures::{stream, Stream};
 use spark_connect_core::{ChannelBuilder, RetryPolicy, RpcDeadlines, 
SparkConnectClient};
@@ -97,6 +97,8 @@ struct State {
     timeouts: Mutex<Vec<(&'static str, Option<String>)>>,
     executes: Mutex<usize>,
     reattaches: Mutex<Vec<ReattachExecuteRequest>>,
+    /// When each ReattachExecute call arrived, in order.
+    reattached_at: Mutex<Vec<Instant>>,
     releases: Mutex<Vec<CapturedRelease>>,
 }
 
@@ -109,6 +111,7 @@ impl State {
             timeouts: Mutex::new(Vec::new()),
             executes: Mutex::new(0),
             reattaches: Mutex::new(Vec::new()),
+            reattached_at: Mutex::new(Vec::new()),
             releases: Mutex::new(Vec::new()),
         }
     }
@@ -390,6 +393,61 @@ async fn 
reattach_past_its_deadline_is_the_error_once_the_bound_passes() {
     fixture.assert_release_all_count(1).await;
 }
 
+#[tokio::test]
+async fn 
reattach_that_fails_after_it_opens_is_a_retry_of_the_policy_as_pyspark() {
+    // As PySpark's `_has_next`, which reads the stream and reattaches in one 
attempt of a
+    // `Retrying` of its own for each response: a stream that fails after it 
opened, also one of
+    // a reattach, is an attempt of the policy, after the policy's backoff, 
and its failure is
+    // the error once the retries are spent. A response read starts the 
attempts again.
+    let reset = || Err(Status::unavailable("connection reset"));
+    let fails_after_opening = || Step::Stream(vec![reset()]);
+    let fixture = Fixture::start(
+        vec![Step::Stream(vec![Ok(response("r1", false)), reset()])],
+        vec![
+            fails_after_opening(),
+            fails_after_opening(),
+            Step::Stream(vec![Ok(response("r2", false)), reset()]),
+            fails_after_opening(),
+            fails_after_opening(),
+            fails_after_opening(),
+            // Not reached: the retries are spent before.
+            streamed(vec![response("complete", true)]),
+        ],
+        RetryPolicy {
+            max_retries: Some(3),
+            initial_backoff_ms: 10,
+            max_backoff_ms: Some(40),
+            ..quick_retries()
+        },
+    )
+    .await;
+    let mut stream = 
bounded(fixture.client.execute_plan_reattachable(execute_request()))
+        .await
+        .unwrap();
+    let read = |response: Option<ExecutePlanResponse>| 
response.unwrap().response_id;
+    assert_eq!(read(bounded(stream.message()).await.unwrap()), "r1");
+    let first = Instant::now();
+    assert_eq!(read(bounded(stream.message()).await.unwrap()), "r2");
+    let second = Instant::now();
+    let error = bounded(stream.message()).await.unwrap_err();
+    assert_eq!(error.grpc_code, Some(Code::Unavailable as i32), "{error:?}");
+
+    // Three reattaches for each response, each after the backoff of its 
attempt: 10, 20 and
+    // 40 ms from the failure before it.
+    let at = fixture.state.reattached_at.lock().unwrap().clone();
+    assert_eq!(at.len(), 6, "{at:?}");
+    for (start, reattaches) in [(first, &at[..3]), (second, &at[3..])] {
+        let mut failed = start;
+        for (reattached, backoff) in reattaches.iter().zip([10, 20, 40]) {
+            let waited = reattached.duration_since(failed);
+            assert!(waited >= Duration::from_millis(backoff), "{waited:?}");
+            failed = *reattached;
+        }
+    }
+    assert_eq!(*fixture.state.executes.lock().unwrap(), 1);
+    fixture.assert_release_all_count(1).await;
+}
+
 #[tokio::test]
 async fn operation_not_found_before_any_response_resends_the_execute_plan() {
     // As the reference: the ExecutePlan of the execution streams no response, 
so it is
@@ -742,6 +800,7 @@ impl ServerStreamingService<ReattachExecuteRequest> for 
Reattach {
         state.record_timeout("ReattachExecute", request.metadata());
         let request = request.into_inner();
         state.reattaches.lock().unwrap().push(request.clone());
+        state.reattached_at.lock().unwrap().push(Instant::now());
         let step = state
             .reattach_script
             .lock()
diff --git a/crates/spark-connect-core/tests/server_session.rs 
b/crates/spark-connect-core/tests/server_session.rs
index 5503d96f..6d9df9bb 100644
--- a/crates/spark-connect-core/tests/server_session.rs
+++ b/crates/spark-connect-core/tests/server_session.rs
@@ -421,6 +421,67 @@ async fn a_restarted_server_raises_and_closes_the_client() 
{
     assert_eq!(error.get_condition().as_deref(), Some("NO_ACTIVE_SESSION"));
 }
 
+#[tokio::test]
+async fn 
a_restart_that_the_plan_compression_lookup_sees_sends_no_plan_as_pyspark() {
+    use spark_connect_proto::analyze_plan_request::{Analyze, Schema};
+    use spark_connect_proto::{plan, AnalyzePlanRequest, Plan, Relation};
+
+    // As PySpark, which reads its `_stub` for an execution or an analysis 
once the plan is
+    // built: the lookup of the plan compression of the first plan gets a 
response of the
+    // restarted server, which closes the client, so the call raises 
NO_ACTIVE_SESSION and sends
+    // nothing.
+    let fixture = Fixture::start().await;
+    let a_plan = || {
+        Some(Plan {
+            op_type: Some(plan::OpType::Root(Relation::default())),
+        })
+    };
+    let mut conditions = Vec::new();
+    for call in ["reattachable ExecutePlan", "ExecutePlan", "AnalyzePlan"] {
+        *fixture.state.server_session_id.lock().unwrap() = 
FIRST_SERVER_ID.to_string();
+        let client = fixture.client().await;
+        client.config(config_request(&client)).await.unwrap();
+        *fixture.state.server_session_id.lock().unwrap() = 
RESTARTED_SERVER_ID.to_string();
+        let execution = ExecutePlanRequest {
+            plan: a_plan(),
+            ..execute_request(&client)
+        };
+        let error = match call {
+            "reattachable ExecutePlan" => 
client.execute_plan_reattachable(execution).await.err(),
+            "ExecutePlan" => client.execute_plan(execution).await.err(),
+            _ => client
+                .analyze_plan(AnalyzePlanRequest {
+                    session_id: client.session_id().to_string(),
+                    analyze: Some(Analyze::Schema(Schema { plan: a_plan() })),
+                    ..Default::default()
+                })
+                .await
+                .err(),
+        };
+        assert!(client.is_closed(), "{call}");
+        conditions.push((call, error.and_then(|error| error.get_condition())));
+    }
+    let no_active_session = Some("NO_ACTIVE_SESSION".to_string());
+    assert_eq!(
+        conditions,
+        [
+            ("reattachable ExecutePlan", no_active_session.clone()),
+            ("ExecutePlan", no_active_session.clone()),
+            ("AnalyzePlan", no_active_session),
+        ]
+    );
+    // Of each client, its Config and the lookup, and nothing after them.
+    let methods: Vec<String> = fixture
+        .state
+        .requests
+        .lock()
+        .unwrap()
+        .iter()
+        .map(|(method, _)| method.clone())
+        .collect();
+    assert_eq!(methods, ["Config"; 6]);
+}
+
 #[tokio::test]
 async fn a_session_changed_error_closes_the_client() {
     let fixture = Fixture::start().await;
diff --git a/docs/compatibility.md b/docs/compatibility.md
index f20463dd..ac1d31a7 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -53,9 +53,12 @@ value filled string columns with its debug text. `fillna`, 
`fillna_double`,
 
 A transport failure has the gRPC code that grpc-python gives it, which 
PySpark's errors and
 retries see. `SparkError::grpc_code` is `UNAVAILABLE` (14) for a connection 
that closes or is reset
-under a call, that the server ends with a GOAWAY, or that closes before 
sending a call, where it
-was `UNKNOWN` (2) or `CANCELLED` (1). It is `INTERNAL` (13) for a stream that 
the server resets with
-a reason that tonic leaves unmapped, such as `STREAM_CLOSED`, which is no 
longer retried.
+under a call, where it was `UNKNOWN` (2); for a call that its connection 
closes before sending it,
+where it was `CANCELLED` (1); and for a connection that the server ends with a 
GOAWAY, where it was
+the code of the reason of the GOAWAY, such as `INTERNAL` (13) for `NO_ERROR` 
and
+`RESOURCE_EXHAUSTED` (8) for `ENHANCE_YOUR_CALM`. It is `INTERNAL` (13) for a 
stream that the
+server resets with a reason that tonic leaves unmapped, such as 
`STREAM_CLOSED`, which is no
+longer retried.
 
 The 4.3 line changes the public Rust representation of expressions and logical
 plans to share immutable nodes. This is a breaking change for code that 
directly
diff --git a/python/tests/test_arrow_handoff.py 
b/python/tests/test_arrow_handoff.py
index 6d0150c0..a1851d98 100644
--- a/python/tests/test_arrow_handoff.py
+++ b/python/tests/test_arrow_handoff.py
@@ -603,7 +603,6 @@ def _arrow_input_service(
             "user_id": request.user_context.user_id,
             "user_name": request.user_context.user_name,
             "has_client_type": request.HasField("client_type"),
-            "client_type": request.client_type,
             "grpc_user_agent": grpc_user_agent,
         }
 
@@ -836,20 +835,18 @@ def _arrow_input_service(
 
 def _assert_artifact_contexts(contexts, *, session_id, user_id, user_agent):
     assert contexts
-    client_types = {context["client_type"] for context in contexts}
-    assert len(client_types) == 1
-    client_type = client_types.pop()
-    assert client_type
-    assert client_type.startswith(user_agent + " spark/")
+    # As PySpark's ArtifactManager, the requests carry the user agent in the 
gRPC header only,
+    # and no client type.
+    grpc_user_agents = {context["grpc_user_agent"] for context in contexts}
+    assert len(grpc_user_agents) == 1
+    assert grpc_user_agents.pop().startswith(user_agent + " spark/")
     for context in contexts:
-        grpc_user_agent = context["grpc_user_agent"]
-        assert grpc_user_agent == client_type or 
grpc_user_agent.startswith(client_type + " ")
         assert context["session_id"] == session_id
         # PySpark's ArtifactManager sends a present context even without a 
user ID.
         assert context["has_user_context"]
         assert context["user_id"] == user_id
         assert context["user_name"] == ""
-        assert context["has_client_type"]
+        assert not context["has_client_type"]
 
 
 @pytest.mark.parametrize("user_id,user_agent", [


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

Reply via email to