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 a868d204 [SPARK-61319][CONNECT][PYTHON] Connection-layer parity: 
ChannelBuilder keepalive and userAgent, retried release_session, no token in 
connection-string errors
a868d204 is described below

commit a868d2044d014209aa7b653b508af59af7b2fe64
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 09:42:38 2026 +0900

    [SPARK-61319][CONNECT][PYTHON] Connection-layer parity: ChannelBuilder 
keepalive and userAgent, retried release_session, no token in connection-string 
errors
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61319](https://issues.apache.org/jira/browse/SPARK-61319): Close 
three connection-layer gaps: the ChannelBuilder keepalive and userAgent 
members, the retry of `release_session`, and the token in connection-string 
errors.
    
    - **ChannelBuilder (drop-in shim)**: adds the `keepalive_enabled`, 
`keepalive_time_ms`, `keepalive_timeout_ms` and `keepalive_without_calls` 
properties, the `userAgent` property, the `PARAM_USER_AGENT` / 
`PARAM_GRPC_KEEPALIVE_*` and `GRPC_DEFAULT_KEEPALIVE_*` constants, 
`GRPC_MAX_MESSAGE_LENGTH_DEFAULT`, `GRPC_DEFAULT_OPTIONS`, and 
`_effective_channel_options()`. Defaults and semantics are those of `core.py` 
in PySpark 4.3.0: the keepalive is on with 60000 ms / 20000 ms / without-call 
[...]
    - **`pyspark/sql/connect/client/core.py`**: a thin re-export of 
`ChannelBuilder`, `DefaultChannelBuilder` and `SparkConnectClient`, the names 
that official code and tests import from there. The rest of `core` is still 
absent.
    - **`release_session` (Rust core)**: now goes through `with_retry`, as 
`interrupt`, `config` and `analyze` do, and as PySpark's `release_session` does 
with `self._retrying()`. `SparkSession::stop()` is unchanged: it releases first 
and closes the client after the release, whether or not the release succeeded, 
so a retry never runs on a closed client.
    - **Connection-string errors (Rust `ChannelBuilder::parse`)**: a bad port 
gives `Port could not be cast to integer value as '<port>'`, urllib's wording 
(PySpark raises it as a plain `ValueError`; ours keeps the 
`INVALID_CONNECT_URL` class), with no URL. A malformed parameter names its key 
only. A missing host quotes the URL with the value of `token` and 
`authorization` replaced by `<redacted>`, the same rule as the `Debug` of 
`ChannelBuilder`. The Python shim's `DefaultChannelBuilder` [...]
    - **Official suite**: `test_connect_channel.py` was skipped as a whole 
file. It now runs against the drop-in: 10 of its 14 tests pass; the other four 
are per-test entries in `scripts/dropin_known_failures.txt` for 
`channelOptions` (`NOT_IMPLEMENTED` by design, two tests), `toChannel` (the 
gRPC channel is the Rust transport's, one test), and a client built from a 
channel builder (one test).
    - **Dead-port sessions in tests**: a session on a refused port now waits 
for the retry policy when it is stopped, as PySpark's does (measured: a 
`stop()` on official PySpark against `sc://127.0.0.1:1` did not finish within 
170 s). The offline suites therefore set `release_session_on_close = False` on 
the sessions they build on a dead port, and the Rust unit tests 
`stop_is_idempotent_and_marks_stopped` and 
`requests_of_a_stopped_session_raise_no_active_session` close those sessions 
ins [...]
    - `dev/parity/known-differences.md`: the keepalive properties and 
`userAgent` are no longer listed as absent. `userAgent` reports PySpark's 
`python/<version>`; the transport sends `python/rust` as the client type, which 
is the identifiability change of SPARK-59136.
    
    ### Why are the changes needed?
    
    - 
`DefaultChannelBuilder("sc://localhost/;grpc_keepalive_time_ms=30000").keepalive_time_ms`
 raised `AttributeError` on the drop-in; PySpark returns `30000`. `userAgent` 
was missing too (PySpark returns `abc spark/4.3.0 os/darwin python/3.11.8` for 
`user_agent=abc`).
    - A transient `UNAVAILABLE` at `stop()` was not retried, so the server 
session stayed until its idle timeout. The failure is only logged, so nothing 
showed it.
    - A bad port put the whole URL into the error, including `;token=...`: 
`sc://localhost:notaport/;token=SECRET` gave `Port 'notaport' in URL 
'sc://localhost:notaport/;token=SECRET' is not a valid integer.` A missing host 
and a malformed parameter echoed the token value too. The Debug output already 
redacted it, so the errors were inconsistent with that.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes.
    - The keepalive properties, `userAgent`, the constants and 
`_effective_channel_options()` exist on the drop-in's `ChannelBuilder` and 
`DefaultChannelBuilder`, with PySpark's values.
    - `pyspark.sql.connect.client.core` imports, with the three re-exported 
names.
    - `stop()` of a session whose server is unreachable waits for the retries 
of `release_session` before it returns, as PySpark's `stop()` does (the default 
policy allows about 11 minutes). Before, it returned after one failed call. A 
session whose server is reachable is released as before.
    - The bad-port and missing-host messages no longer contain the token; the 
port message text changes to PySpark's wording.
    
    ### How was this patch tested?
    
    - New Rust unit tests, which fail on the base code and pass with the fix:
      - `channel::tests::parse_errors_do_not_echo_the_token` (before 
`scheme_is_tls_for_a_token_on_any_host_but_localhost`): the port message names 
only the port, a malformed parameter names only its key, and the missing-host 
message shows `token=<redacted>`.
      - 
`client::tests::release_session_is_retried_on_unavailable_as_the_reference` 
(before `test_add_artifacts_request_structure`): a loopback ReleaseSession 
server answers UNAVAILABLE once; the release is retried and the second call 
succeeds. It fails on the base `release_session` with the UNAVAILABLE error.
    - New offline test 
`test_dropin_offline.py::test_channel_builder_keepalive_and_user_agent_as_pyspark`
 (before `test_spatial_types_take_the_srids_that_pyspark_knows`): defaults, 
tuned parameters, the disabled keepalive, the bad integer, the user-agent 
override by parameter and by environment, the 2049-character error, and the 
`_effective_channel_options()` lists. The expected values were taken from 
official PySpark 4.3.0 on the same inputs. It fails on the base shim 
(`AttributeError`)  [...]
    - Official `test_connect_channel.py` against the drop-in 
(`run_official_tests.py --dropin --only ...`): 10 passed, 4 deselected by 
design; the drift check reports no test that now passes among the deselected 
ones.
    - Rust: `apache-spark-connect-core` lib 152 passed; `apache-spark-connect` 
lib 528 passed; core integration tests `artifact_uploads` 6, `deadlines` 15, 
`reattach_cleanup` 15, `server_session` 4, `user_context` 4 passed 
(`integration_test`: 3 pre-existing `#[ignore]`d); `cargo test -p 
apache-spark-connect --release --no-run` compiles all targets; `cargo fmt --all 
--check` clean.
    - Clippy (`--workspace --all-targets`): the run stops on pre-existing lints 
of the current toolchain (`approx_constant`, `needless_borrow`, 
`empty_line_after_outer_attr`) in files this PR does not touch; no warning in 
the changed lines except `field_reassign_with_default` in `release_session`, 
which is the request construction that predates this change.
    - Offline Python suites (`test_dropin_offline.py`, `test_arrow_handoff.py`, 
`test_ml_offline.py`): 2928 passed, 8 skipped.
    - Live (`test_dropin_e2e.py -k "stop or session"` on a Spark Connect 
server): 11 passed.
    - The lib tests of both crates (152 and 528 passed), the transport crate's 
integration tests, the build of all tests, the offline Python suites (2928 
passed, 8 skipped) with the rebuilt extension, the new offline test also under 
pytest 9.2, the official `test_connect_channel.py` through the drop-in gate (10 
passed, 4 deselected by design), and the live drop-in tests `-k "stop or 
session"` (11 passed) against a local Spark 4.3.0 server. Clippy reports no new 
diagnostics in 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 #439 from HyukjinKwon/SPARK-61319-channel-builder-release.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/spark-connect-core/src/channel.rs      |  75 ++++++++++++--
 crates/spark-connect-core/src/client.rs       | 140 ++++++++++++++++++++++++--
 crates/spark-connect/src/session.rs           |  10 +-
 dev/parity/known-differences.md               |   6 +-
 python/pyspark/sql/connect/client/__init__.py | 111 +++++++++++++++++++-
 python/pyspark/sql/connect/client/core.py     |  23 +++++
 python/tests/interval_input_cases.py          |   9 ++
 python/tests/test_dropin_offline.py           |  92 ++++++++++++++++-
 scripts/dropin_known_failures.txt             |   6 +-
 9 files changed, 436 insertions(+), 36 deletions(-)

diff --git a/crates/spark-connect-core/src/channel.rs 
b/crates/spark-connect-core/src/channel.rs
index b168ecf4..9d073976 100644
--- a/crates/spark-connect-core/src/channel.rs
+++ b/crates/spark-connect-core/src/channel.rs
@@ -61,11 +61,13 @@ impl std::fmt::Debug for ChannelBuilder {
             .params
             .iter()
             .map(|(key, value)| {
-                let secret = key.eq_ignore_ascii_case(PARAM_TOKEN)
-                    || key.eq_ignore_ascii_case("authorization");
                 (
                     key.as_str(),
-                    if secret { "<redacted>" } else { value.as_str() },
+                    if is_secret_param(key) {
+                        "<redacted>"
+                    } else {
+                        value.as_str()
+                    },
                 )
             })
             .collect();
@@ -124,12 +126,14 @@ impl ChannelBuilder {
             for p in params_str.split(';') {
                 let kv: Vec<&str> = p.split('=').collect();
                 if kv.len() != 2 {
+                    // The key only: the value of a parameter may be the token.
+                    let key = p.split_once('=').map_or(p, |(key, _)| key);
                     return Err(SparkError::value(
                         "INVALID_CONNECT_URL",
                         &[(
                             "detail",
                             &format!(
-                                "Parameter '{p}' should be provided as a 
key-value pair \
+                                "Parameter '{key}' should be provided as a 
key-value pair \
                                  separated by an equal sign (=). Please update 
the parameter \
                                  to follow the correct format, e.g., 
'key=value'."
                             ),
@@ -140,7 +144,7 @@ impl ChannelBuilder {
             }
         }
 
-        let (host_raw, port) = parse_authority(authority, url)?;
+        let (host_raw, port) = parse_authority(authority, &redact_url(url))?;
         // urllib lowercases the hostname.
         let hostname = host_raw.to_ascii_lowercase();
         let host = if hostname.contains(':') {
@@ -339,15 +343,35 @@ fn split_params(path: &str) -> (&str, &str) {
     }
 }
 
-/// Parse `host`, `host:port`, `[ipv6]`, or `[ipv6]:port` into (host, port).
-fn parse_authority(authority: &str, full_url: &str) -> Result<(String, u16)> {
+/// Whether a parameter is a secret: its value is shown redacted, and never in 
an error.
+fn is_secret_param(key: &str) -> bool {
+    key.eq_ignore_ascii_case(PARAM_TOKEN) || 
key.eq_ignore_ascii_case("authorization")
+}
+
+/// The URL with the value of each secret parameter replaced by `<redacted>`, 
for the error
+/// messages that quote the URL.
+fn redact_url(url: &str) -> String {
+    url.split(';')
+        .map(|part| match part.split_once('=') {
+            Some((key, _)) if 
is_secret_param(key.rsplit('/').next().unwrap_or(key)) => {
+                format!("{key}=<redacted>")
+            }
+            _ => part.to_string(),
+        })
+        .collect::<Vec<_>>()
+        .join(";")
+}
+
+/// Parse `host`, `host:port`, `[ipv6]`, or `[ipv6]:port` into (host, port). 
`shown_url` is the
+/// URL for the messages, with its secrets redacted.
+fn parse_authority(authority: &str, shown_url: &str) -> Result<(String, u16)> {
     let missing_host = || {
         SparkError::value(
             "INVALID_CONNECT_URL",
             &[(
                 "detail",
                 &format!(
-                    "Hostname is missing in the URL: '{full_url}'. Please 
update the URL \
+                    "Hostname is missing in the URL: '{shown_url}'. Please 
update the URL \
                      to follow the correct format, e.g., 'sc://hostname:port'."
                 ),
             )],
@@ -373,12 +397,13 @@ fn parse_authority(authority: &str, full_url: &str) -> 
Result<(String, u16)> {
 
     let port = match port_str {
         None | Some("") => DEFAULT_PORT,
+        // As urllib's message (`Port could not be cast to integer value as 
'...'`), with no URL.
         Some(p) => p.parse::<u16>().map_err(|_| {
             SparkError::value(
                 "INVALID_CONNECT_URL",
                 &[(
                     "detail",
-                    &format!("Port '{p}' in URL '{full_url}' is not a valid 
integer."),
+                    &format!("Port could not be cast to integer value as 
'{p}'"),
                 )],
             )
         })?,
@@ -541,6 +566,38 @@ mod tests {
         assert_eq!(c.token().as_deref(), Some("SECRET123"));
     }
 
+    #[test]
+    fn parse_errors_do_not_echo_the_token() {
+        // A bad port names the port only, as PySpark's message does; the URL 
is not quoted.
+        let e = 
ChannelBuilder::parse("sc://localhost:notaport/;token=SECRET").unwrap_err();
+        assert_eq!(e.error_class, "INVALID_CONNECT_URL");
+        let shown = e.to_string();
+        assert!(
+            shown.contains("Port could not be cast to integer value as 
'notaport'"),
+            "{shown}"
+        );
+        assert!(
+            !shown.contains("SECRET") && !shown.contains("localhost"),
+            "{shown}"
+        );
+        // A malformed parameter names its key only: its value may be the 
token.
+        let e = 
ChannelBuilder::parse("sc://localhost/;token=SE=CRET").unwrap_err();
+        let shown = e.to_string();
+        assert!(shown.contains("Parameter 'token' should be"), "{shown}");
+        assert!(
+            !shown.contains("SE=CRET") && !shown.contains("CRET"),
+            "{shown}"
+        );
+        // A missing host quotes the URL with the token value redacted, as the 
Debug does.
+        let e = 
ChannelBuilder::parse("sc://:15002/;token=SECRET;user_id=bob").unwrap_err();
+        let shown = e.to_string();
+        assert!(
+            shown.contains("sc://:15002/;token=<redacted>;user_id=bob"),
+            "{shown}"
+        );
+        assert!(!shown.contains("SECRET"), "{shown}");
+    }
+
     #[test]
     fn scheme_is_tls_for_a_token_on_any_host_but_localhost() {
         let _env = set_env(&[("SPARK_CONNECT_AUTHENTICATE_TOKEN", None)]);
diff --git a/crates/spark-connect-core/src/client.rs 
b/crates/spark-connect-core/src/client.rs
index 6ff337b3..24e4cb2b 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -1513,6 +1513,11 @@ impl SparkConnectClient {
         Ok(cloned)
     }
 
+    /// Release this session on the server.
+    ///
+    /// Mirrors 
`pyspark.sql.connect.client.core.SparkConnectClient.release_session`, which
+    /// retries it under the retry policy: a transient failure at stop does 
not leave the
+    /// session on the server until its timeout.
     pub async fn release_session(&self) -> Result<()> {
         let mut request = ReleaseSessionRequest::default();
         request.session_id = self.session_id.clone();
@@ -1521,16 +1526,20 @@ impl SparkConnectClient {
             ..Default::default()
         });
 
-        let deadline = self.rpc_deadlines.release_session;
-        let mut req = with_deadline(Request::new(request), deadline);
-        self._attach_metadata(&mut req);
-        match within_deadline(deadline, 
self.stub.clone().release_session(req)).await {
-            Ok(response) => {
-                let response = response.into_inner();
-                self.verify_response(&response.session_id, 
&response.server_side_session_id)
-            }
-            Err(status) => Err(self.error_from_status(status).await),
-        }
+        let response = self
+            .with_retry(|| {
+                let deadline = self.rpc_deadlines.release_session;
+                let mut req = with_deadline(Request::new(request.clone()), 
deadline);
+                self._attach_metadata(&mut req);
+                let mut stub = self.stub.clone();
+                async move {
+                    within_deadline(deadline, stub.release_session(req))
+                        .await
+                        .map(Response::into_inner)
+                }
+            })
+            .await?;
+        self.verify_response(&response.session_id, 
&response.server_side_session_id)
     }
 
     /// Add artifacts to this session.
@@ -2551,6 +2560,117 @@ mod tests {
         let _result = client.release_session();
     }
 
+    /// A loopback service of ReleaseSession only: its first `unavailable` 
calls answer
+    /// UNAVAILABLE, the later ones succeed. `calls` counts every call.
+    struct ReleaseCalls {
+        calls: std::sync::atomic::AtomicUsize,
+        unavailable: usize,
+    }
+
+    #[derive(Clone)]
+    struct ReleaseService(std::sync::Arc<ReleaseCalls>);
+
+    impl tonic::server::NamedService for ReleaseService {
+        const NAME: &'static str = "spark.connect.SparkConnectService";
+    }
+
+    impl 
tonic::codegen::Service<tonic::codegen::http::Request<tonic::body::Body>> for 
ReleaseService {
+        type Response = tonic::codegen::http::Response<tonic::body::Body>;
+        type Error = std::convert::Infallible;
+        type Future = tonic::codegen::BoxFuture<Self::Response, Self::Error>;
+
+        fn poll_ready(
+            &mut self,
+            _: &mut std::task::Context<'_>,
+        ) -> std::task::Poll<std::result::Result<(), Self::Error>> {
+            std::task::Poll::Ready(Ok(()))
+        }
+
+        fn call(
+            &mut self,
+            request: tonic::codegen::http::Request<tonic::body::Body>,
+        ) -> Self::Future {
+            let state = self.0.clone();
+            Box::pin(async move {
+                if request.uri().path() == 
"/spark.connect.SparkConnectService/ReleaseSession" {
+                    let mut grpc = 
tonic::server::Grpc::new(tonic_prost::ProstCodec::default());
+                    return Ok(grpc.unary(ReleaseRpc(state), request).await);
+                }
+                Ok(tonic::codegen::http::Response::builder()
+                    .status(200)
+                    .header("grpc-status", "12")
+                    .header("content-type", "application/grpc")
+                    .body(tonic::body::Body::empty())
+                    .unwrap())
+            })
+        }
+    }
+
+    struct ReleaseRpc(std::sync::Arc<ReleaseCalls>);
+
+    impl tonic::server::UnaryService<ReleaseSessionRequest> for ReleaseRpc {
+        type Response = spark_connect_proto::ReleaseSessionResponse;
+        type Future = 
tonic::codegen::BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
+
+        fn call(&mut self, request: tonic::Request<ReleaseSessionRequest>) -> 
Self::Future {
+            let state = self.0.clone();
+            let request = request.into_inner();
+            Box::pin(async move {
+                let call = state
+                    .calls
+                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+                if call < state.unavailable {
+                    return Err(tonic::Status::unavailable("the server is 
restarting"));
+                }
+                Ok(tonic::Response::new(
+                    spark_connect_proto::ReleaseSessionResponse {
+                        session_id: request.session_id,
+                        ..Default::default()
+                    },
+                ))
+            })
+        }
+    }
+
+    #[tokio::test]
+    async fn release_session_is_retried_on_unavailable_as_the_reference() {
+        // A transient UNAVAILABLE at stop is retried under the policy, so the 
server session is
+        // released by the second call; the reference's `release_session` runs 
in `Retrying`.
+        let calls = std::sync::Arc::new(ReleaseCalls {
+            calls: std::sync::atomic::AtomicUsize::new(0),
+            unavailable: 1,
+        });
+        let listener = 
tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+        let address = listener.local_addr().unwrap();
+        let incoming = futures::stream::unfold(listener, |listener| async {
+            Some((listener.accept().await.map(|(socket, _)| socket), listener))
+        });
+        let service = ReleaseService(calls.clone());
+        let server = tokio::spawn(async move {
+            tonic::transport::Server::builder()
+                .add_service(service)
+                .serve_with_incoming(incoming)
+                .await
+                .unwrap();
+        });
+        let builder = {
+            let _env = 
crate::channel::set_env(&[("SPARK_CONNECT_AUTHENTICATE_TOKEN", None)]);
+            ChannelBuilder::parse(&format!("sc://127.0.0.1:{}", 
address.port())).unwrap()
+        };
+        let mut client = SparkConnectClient::connect(&builder).await.unwrap();
+        client.set_retry_policy(RetryPolicy {
+            max_retries: Some(2),
+            initial_backoff_ms: 1,
+            max_backoff_ms: Some(2),
+            ..RetryPolicy::default()
+        });
+
+        let released = client.release_session().await;
+        server.abort();
+        released.unwrap();
+        assert_eq!(calls.calls.load(std::sync::atomic::Ordering::SeqCst), 2);
+    }
+
     #[tokio::test]
     async fn test_add_artifacts_request_structure() {
         let builder = ChannelBuilder::parse("sc://localhost").unwrap();
diff --git a/crates/spark-connect/src/session.rs 
b/crates/spark-connect/src/session.rs
index d244dd22..63cd1f96 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -2959,15 +2959,15 @@ mod tests {
 
     #[test]
     fn stop_is_idempotent_and_marks_stopped() {
-        // Port 1: nothing listens, so the ReleaseSession RPC fails fast. The 
session is
-        // still marked stopped (pyspark's stop() is best-effort) and a second 
stop() is a
-        // no-op that does not retry the release.
+        // Port 1: nothing listens, and a release there waits for the retry 
policy, as PySpark's
+        // does, so the session is closed without it: stop() then only marks 
it stopped, which
+        // is what a second stop() must find.
         let spark = SparkSession::builder()
             .remote("sc://localhost:1")
             .get_or_create()
             .expect("failed to build session");
         let other = spark.clone();
-        let _ = spark.stop();
+        spark.close();
         assert!(spark.is_stopped());
         assert!(other.is_stopped(), "stopped flag is shared across clones");
         assert!(spark.stop().is_ok());
@@ -2981,7 +2981,7 @@ mod tests {
             .remote("sc://localhost:1")
             .get_or_create()
             .expect("failed to build session");
-        let _ = spark.stop();
+        spark.close();
         let err = spark
             .conf()
             .get("spark.sql.shuffle.partitions")
diff --git a/dev/parity/known-differences.md b/dev/parity/known-differences.md
index 3fcb44cb..4edeac01 100644
--- a/dev/parity/known-differences.md
+++ b/dev/parity/known-differences.md
@@ -201,8 +201,10 @@ difference is intentional or tracked for a fix.
   `DefaultChannelBuilder` parse the connection string and hold its parameters, 
`host`,
   `port`, `endpoint`, `get`, `set`, `userId`, `token`, `session_id`, 
`use_ssl`, `secure`
   and `metadata()`. The transport reads them as a `sc://` URL, so they apply. 
The gRPC
-  channel members do not: `toChannel`, `add_interceptor`, `setChannelOption`, 
the
-  keepalive properties and `userAgent`. A `channelOptions` argument raises
+  channel members do not: `toChannel`, `add_interceptor`, `setChannelOption`. 
The keepalive
+  properties and `userAgent` read the parameters as PySpark does, but 
`userAgent` reports
+  PySpark's `python/<version>` where the transport sends `python/rust` as the 
client type.
+  The Rust channel applies the keepalive from the same parameters. A 
`channelOptions` argument raises
   `NOT_IMPLEMENTED` instead of being ignored. A subclass that overrides 
`userId` or
   `token` is not read by the transport, which uses the parameters.
 - **Retry and reattach** (intentional; DESIGN). `RpcDeadlines`, 
`client.retries`
diff --git a/python/pyspark/sql/connect/client/__init__.py 
b/python/pyspark/sql/connect/client/__init__.py
index 9fb30a07..8fb06d92 100644
--- a/python/pyspark/sql/connect/client/__init__.py
+++ b/python/pyspark/sql/connect/client/__init__.py
@@ -23,6 +23,7 @@ __all__ = ["ChannelBuilder", "DefaultChannelBuilder", 
"SparkConnectClient"]
 
 import copy
 import os
+import platform
 import sys
 import urllib.parse
 import uuid
@@ -30,7 +31,9 @@ import weakref
 from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple
 
 from pyspark.errors import PySparkNotImplementedError, PySparkValueError
+from pyspark.errors.exceptions.connect import SparkConnectException
 from pyspark.sql.metrics import ObservedMetrics
+from pyspark.version import __version__
 
 
 class ChannelBuilder:
@@ -45,6 +48,23 @@ class ChannelBuilder:
     PARAM_TOKEN = "token"
     PARAM_USER_ID = "user_id"
     PARAM_SESSION_ID = "session_id"
+    PARAM_USER_AGENT = "user_agent"
+    PARAM_GRPC_KEEPALIVE_ENABLED = "grpc_keepalive_enabled"
+    PARAM_GRPC_KEEPALIVE_TIME_MS = "grpc_keepalive_time_ms"
+    PARAM_GRPC_KEEPALIVE_TIMEOUT_MS = "grpc_keepalive_timeout_ms"
+    PARAM_GRPC_KEEPALIVE_WITHOUT_CALLS = "grpc_keepalive_without_calls"
+
+    # The keepalive PINGs that detect a silently-dead connection, as PySpark's 
(SPARK-58094).
+    GRPC_DEFAULT_KEEPALIVE_ENABLED = True
+    GRPC_DEFAULT_KEEPALIVE_TIME_MS = 60 * 1000
+    GRPC_DEFAULT_KEEPALIVE_TIMEOUT_MS = 20 * 1000
+    GRPC_DEFAULT_KEEPALIVE_WITHOUT_CALLS = True
+
+    GRPC_MAX_MESSAGE_LENGTH_DEFAULT = 128 * 1024 * 1024
+    GRPC_DEFAULT_OPTIONS = [
+        ("grpc.max_send_message_length", GRPC_MAX_MESSAGE_LENGTH_DEFAULT),
+        ("grpc.max_receive_message_length", GRPC_MAX_MESSAGE_LENGTH_DEFAULT),
+    ]
 
     def __init__(
         self,
@@ -89,6 +109,63 @@ class ChannelBuilder:
             ChannelBuilder.PARAM_TOKEN, 
os.environ.get("SPARK_CONNECT_AUTHENTICATE_TOKEN")
         )
 
+    @property
+    def keepalive_enabled(self) -> bool:
+        """Whether the client sends gRPC/HTTP2 keepalive PINGs to detect a 
silently-dead
+        connection. Enabled by default."""
+        return (
+            self.getDefault(
+                ChannelBuilder.PARAM_GRPC_KEEPALIVE_ENABLED,
+                str(ChannelBuilder.GRPC_DEFAULT_KEEPALIVE_ENABLED),
+            ).lower()
+            == "true"
+        )
+
+    @property
+    def keepalive_time_ms(self) -> int:
+        """Idle time (in milliseconds) before sending a gRPC/HTTP2 keepalive 
PING."""
+        return int(
+            self.getDefault(
+                ChannelBuilder.PARAM_GRPC_KEEPALIVE_TIME_MS,
+                ChannelBuilder.GRPC_DEFAULT_KEEPALIVE_TIME_MS,
+            )
+        )
+
+    @property
+    def keepalive_timeout_ms(self) -> int:
+        """Time (in milliseconds) to wait for a keepalive PING ack before 
failing."""
+        return int(
+            self.getDefault(
+                ChannelBuilder.PARAM_GRPC_KEEPALIVE_TIMEOUT_MS,
+                ChannelBuilder.GRPC_DEFAULT_KEEPALIVE_TIMEOUT_MS,
+            )
+        )
+
+    @property
+    def keepalive_without_calls(self) -> bool:
+        """Whether to keep sending keepalive PINGs when there are no in-flight 
RPCs."""
+        return (
+            self.getDefault(
+                ChannelBuilder.PARAM_GRPC_KEEPALIVE_WITHOUT_CALLS,
+                str(ChannelBuilder.GRPC_DEFAULT_KEEPALIVE_WITHOUT_CALLS),
+            ).lower()
+            == "true"
+        )
+
+    def _effective_channel_options(self) -> List[Tuple[str, Any]]:
+        """The gRPC options of the channel: the defaults, and the keepalive 
options unless the
+        keepalive is disabled. The Rust channel applies the same keepalive, 
from the same
+        parameters, and the same message lengths."""
+        options = list(ChannelBuilder.GRPC_DEFAULT_OPTIONS)
+        if not self.keepalive_enabled:
+            return options
+        options += [
+            ("grpc.keepalive_time_ms", self.keepalive_time_ms),
+            ("grpc.keepalive_timeout_ms", self.keepalive_timeout_ms),
+            ("grpc.keepalive_permit_without_calls", 1 if 
self.keepalive_without_calls else 0),
+        ]
+        return options
+
     @property
     def session_id(self) -> Optional[str]:
         """The session_id of the parameters, or None if it is not set."""
@@ -103,18 +180,42 @@ class ChannelBuilder:
                 )
         return session_id
 
+    @property
+    def userAgent(self) -> str:
+        """The user agent: the ``user_agent`` parameter, else the environment 
variable
+        ``SPARK_CONNECT_USER_AGENT``, else ``_SPARK_CONNECT_PYTHON``, with the 
versions of
+        Spark, the operating system and Python. Its URL-escaped form is at 
most 2048 characters."""
+        user_agent = self._params.get(
+            ChannelBuilder.PARAM_USER_AGENT,
+            os.getenv("SPARK_CONNECT_USER_AGENT", "_SPARK_CONNECT_PYTHON"),
+        )
+        ua_len = len(urllib.parse.quote(user_agent))
+        if ua_len > 2048:
+            raise SparkConnectException(
+                f"'user_agent' parameter should not exceed 2048 characters 
after URL "
+                f"escaping, found {ua_len} characters."
+            )
+        return " ".join(
+            [
+                user_agent,
+                f"spark/{__version__}",
+                f"os/{platform.uname().system.lower()}",
+                f"python/{platform.python_version()}",
+            ]
+        )
+
     def metadata(self) -> Iterable[Tuple[str, str]]:
         """The parameters that are not used by the channel, as gRPC metadata 
of each request."""
         reserved = [
             ChannelBuilder.PARAM_TOKEN,
             ChannelBuilder.PARAM_USE_SSL,
             ChannelBuilder.PARAM_USER_ID,
-            "user_agent",
+            ChannelBuilder.PARAM_USER_AGENT,
             ChannelBuilder.PARAM_SESSION_ID,
-            "grpc_keepalive_enabled",
-            "grpc_keepalive_time_ms",
-            "grpc_keepalive_timeout_ms",
-            "grpc_keepalive_without_calls",
+            ChannelBuilder.PARAM_GRPC_KEEPALIVE_ENABLED,
+            ChannelBuilder.PARAM_GRPC_KEEPALIVE_TIME_MS,
+            ChannelBuilder.PARAM_GRPC_KEEPALIVE_TIMEOUT_MS,
+            ChannelBuilder.PARAM_GRPC_KEEPALIVE_WITHOUT_CALLS,
         ]
         return [(k, self._params[k]) for k in self._params if k not in 
reserved]
 
diff --git a/python/pyspark/sql/connect/client/core.py 
b/python/pyspark/sql/connect/client/core.py
new file mode 100644
index 00000000..3da775b4
--- /dev/null
+++ b/python/pyspark/sql/connect/client/core.py
@@ -0,0 +1,23 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Thin re-export of the client classes of 
``pyspark.sql.connect.client.core``, which official
+PySpark code and tests import from there. The gRPC client itself is the Rust 
transport: the
+drop-in does not provide the rest of ``core`` (``RpcDeadlines``, the gRPC 
stub)."""
+
+__all__ = ["ChannelBuilder", "DefaultChannelBuilder", "SparkConnectClient"]
+
+from pyspark.sql.connect.client import ChannelBuilder, DefaultChannelBuilder, 
SparkConnectClient
diff --git a/python/tests/interval_input_cases.py 
b/python/tests/interval_input_cases.py
index 6d80e5c2..cd148cd6 100644
--- a/python/tests/interval_input_cases.py
+++ b/python/tests/interval_input_cases.py
@@ -47,6 +47,9 @@ INFERENCE_CONFS = {
 class IntervalInputConversionTests(unittest.TestCase):
     def test_overflow_is_checked_recursively_before_rpc(self):
         spark = SparkSession.builder.remote("sc://127.0.0.1:1").create()
+        # No server to release the session on: stop() closes the client 
without the release
+        # retries of a refused port.
+        spark.release_session_on_close = False
         self.addCleanup(spark.stop)
         interval = T.DayTimeIntervalType()
         for micros in (-(2**63) - 1, 2**63, -(2**63) - 86400000000):
@@ -74,6 +77,9 @@ class IntervalInputConversionTests(unittest.TestCase):
 
     def test_inference_rejects_mixed_interval_and_numeric_values(self):
         spark = SparkSession.builder.remote("sc://127.0.0.1:1").create()
+        # No server to release the session on: stop() closes the client 
without the release
+        # retries of a refused port.
+        spark.release_session_on_close = False
         self.addCleanup(spark.stop)
         delta = timedelta(microseconds=-1)
         with self.assertRaises(PySparkTypeError) as error:
@@ -103,6 +109,9 @@ class IntervalInputConversionTests(unittest.TestCase):
 
     def test_bounds_and_null_first_inputs_build_without_rpc(self):
         spark = SparkSession.builder.remote("sc://127.0.0.1:1").create()
+        # No server to release the session on: stop() closes the client 
without the release
+        # retries of a refused port.
+        spark.release_session_on_close = False
         self.addCleanup(spark.stop)
         for schema in (None, ["interval"], T.StructType([
                 T.StructField("interval", T.DayTimeIntervalType())])):
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 684dffa7..7285dd48 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -950,6 +950,8 @@ assert seen == {"active": None, "default": first, "got": 
first}, seen
 created = SparkSession.builder.remote("sc://localhost:1").create()
 assert created is not first and SparkSession.getActiveSession() is first
 
+# No server at localhost:1 to release on: a release would wait for the retries 
of a refused port.
+first.release_session_on_close = False
 first.stop()
 assert SparkSession.getActiveSession() is None
 assert condition(SparkSession.active) == "NO_ACTIVE_OR_DEFAULT_SESSION"
@@ -2768,6 +2770,80 @@ def test_type_class_hierarchy():
     assert issubclass(T.AtomicType, T.DataType)
 
 
+def test_channel_builder_keepalive_and_user_agent_as_pyspark(monkeypatch):
+    # The keepalive properties, the user agent and the constants of PySpark's 
ChannelBuilder:
+    # the defaults of core.py, and the values of the parameters of the 
connection string.
+    import platform
+
+    from pyspark.errors.exceptions.connect import SparkConnectException
+    from pyspark.sql.connect.client import ChannelBuilder, 
DefaultChannelBuilder
+
+    monkeypatch.delenv("SPARK_CONNECT_USER_AGENT", raising=False)
+    assert ChannelBuilder.PARAM_USER_AGENT == "user_agent"
+    assert ChannelBuilder.PARAM_GRPC_KEEPALIVE_ENABLED == 
"grpc_keepalive_enabled"
+    assert ChannelBuilder.PARAM_GRPC_KEEPALIVE_TIME_MS == 
"grpc_keepalive_time_ms"
+    assert ChannelBuilder.PARAM_GRPC_KEEPALIVE_TIMEOUT_MS == 
"grpc_keepalive_timeout_ms"
+    assert ChannelBuilder.PARAM_GRPC_KEEPALIVE_WITHOUT_CALLS == 
"grpc_keepalive_without_calls"
+    assert ChannelBuilder.GRPC_DEFAULT_KEEPALIVE_ENABLED is True
+    assert ChannelBuilder.GRPC_DEFAULT_KEEPALIVE_TIME_MS == 60000
+    assert ChannelBuilder.GRPC_DEFAULT_KEEPALIVE_TIMEOUT_MS == 20000
+    assert ChannelBuilder.GRPC_DEFAULT_KEEPALIVE_WITHOUT_CALLS is True
+
+    default = DefaultChannelBuilder("sc://localhost")
+    assert default.keepalive_enabled is True
+    assert default.keepalive_time_ms == 60000
+    assert default.keepalive_timeout_ms == 20000
+    assert default.keepalive_without_calls is True
+    assert default.userAgent == (
+        f"_SPARK_CONNECT_PYTHON spark/4.3.0 
os/{platform.uname().system.lower()} "
+        f"python/{platform.python_version()}"
+    )
+
+    tuned = DefaultChannelBuilder(
+        
"sc://localhost/;grpc_keepalive_enabled=FALSE;grpc_keepalive_time_ms=30000"
+        ";grpc_keepalive_timeout_ms=5000;grpc_keepalive_without_calls=false"
+    )
+    assert tuned.keepalive_enabled is False
+    assert tuned.keepalive_time_ms == 30000
+    assert tuned.keepalive_timeout_ms == 5000
+    assert tuned.keepalive_without_calls is False
+    assert list(tuned.metadata()) == []  # the keepalive params are channel 
options, not metadata
+    # The gRPC options of the channel, as PySpark's: the keepalive of the 
defaults, and none
+    # of the keepalive when it is disabled.
+    message_lengths = [
+        ("grpc.max_send_message_length", 134217728),
+        ("grpc.max_receive_message_length", 134217728),
+    ]
+    assert default._effective_channel_options() == message_lengths + [
+        ("grpc.keepalive_time_ms", 60000),
+        ("grpc.keepalive_timeout_ms", 20000),
+        ("grpc.keepalive_permit_without_calls", 1),
+    ]
+    assert tuned._effective_channel_options() == message_lengths  # disabled: 
none of it
+    enabled = DefaultChannelBuilder(
+        
"sc://localhost/;grpc_keepalive_time_ms=30000;grpc_keepalive_timeout_ms=5000"
+        ";grpc_keepalive_without_calls=false"
+    )
+    assert enabled._effective_channel_options() == message_lengths + [
+        ("grpc.keepalive_time_ms", 30000),
+        ("grpc.keepalive_timeout_ms", 5000),
+        ("grpc.keepalive_permit_without_calls", 0),
+    ]
+    with pytest.raises(ValueError):
+        
DefaultChannelBuilder("sc://localhost/;grpc_keepalive_time_ms=abc").keepalive_time_ms
+
+    named = DefaultChannelBuilder("sc://localhost/;user_agent=abc")
+    assert named.userAgent == (
+        f"abc spark/4.3.0 os/{platform.uname().system.lower()} 
python/{platform.python_version()}"
+    )
+    monkeypatch.setenv("SPARK_CONNECT_USER_AGENT", "env-agent")
+    assert default.userAgent.startswith("env-agent spark/4.3.0 ")
+    too_long = DefaultChannelBuilder("sc://localhost")
+    too_long.set("user_agent", "a" * 2049)
+    with pytest.raises(SparkConnectException, match="should not exceed 2048 
characters"):
+        too_long.userAgent
+
+
 @pytest.mark.parametrize("make, expected", [
     (lambda: T.GeometryType("ANY"), "GeometryType(ANY)"),
     (lambda: T.GeographyType("ANY"), "GeographyType(ANY)"),
@@ -11689,6 +11765,9 @@ def _no_session_left_active():
 
     session = SparkSession.getActiveSession()
     if session is not None:
+        # The servers of these sessions are mocks or unreachable: a release 
would wait for the
+        # retries of a refused port, so the session is closed without it.
+        session.release_session_on_close = False
         session.stop()
 
 
@@ -14527,8 +14606,11 @@ def test_variant_delete_requires_paths():
 
 
 def _offline_session():
-    # Port 1: nothing listens; the channel is lazy, so the session builds 
offline.
-    return SparkSession.builder.remote("sc://localhost:1").getOrCreate()
+    # Port 1: nothing listens; the channel is lazy, so the session builds 
offline. Nothing is
+    # released on it: a release would wait for the retries of a refused port.
+    spark = SparkSession.builder.remote("sc://localhost:1").getOrCreate()
+    spark.release_session_on_close = False
+    return spark
 
 
 def test_nearest_by_join_checks_its_arguments_as_pyspark():
@@ -14692,8 +14774,7 @@ def test_session_context_manager_stops_session():
     with spark as s:
         assert s is spark
         assert not s.is_stopped
-    # __exit__ stops it; stop() is best-effort (the release RPC fails offline) 
and
-    # idempotent.
+    # __exit__ stops it, and stop() is idempotent.
     assert spark.is_stopped
     spark.stop()
     assert SparkSession.getActiveSession() is None
@@ -14732,6 +14813,7 @@ def test_sql_context_connect_backed():
         assert ctx.udf is not None and ctx.read is not None
         # Stopping a different session leaves the cache; stopping its own 
clears it.
         other = spark.newSession()
+        other.release_session_on_close = False  # no server to release on, as 
spark
         other.stop()
         assert cctx.SQLContext._instantiatedContext is ctx
         spark.stop()
@@ -15999,6 +16081,8 @@ def 
test_requests_of_a_stopped_session_raise_no_active_session_as_pyspark():
 
     spark = _offline_session()
     other = spark.newSession()
+    # No server to release on, as the sessions of _offline_session().
+    other.release_session_on_close = False
     other.stop()
     assert other.is_stopped
     requests = [
diff --git a/scripts/dropin_known_failures.txt 
b/scripts/dropin_known_failures.txt
index 82a88357..09ce1b6f 100644
--- a/scripts/dropin_known_failures.txt
+++ b/scripts/dropin_known_failures.txt
@@ -15,7 +15,11 @@
 pyspark/sql/tests/connect/client/test_client.py  # tests grpcio channel/stub 
internals; this client's transport is Rust (SPARK-61111 module audit)
 pyspark/sql/tests/connect/client/test_client_retries.py  # tests the grpcio 
retry policy of the Python client; the Rust transport has its own
 pyspark/sql/tests/connect/client/test_client_call_stack_trace.py  # tests the 
Python client's call-stack trace plumbing, which the Rust transport replaces
-pyspark/sql/tests/connect/test_connect_channel.py  # tests the grpcio channel 
builder; ChannelBuilder is Rust-backed here
+# --- test_connect_channel.py runs against the drop-in; these four need a 
grpcio channel or a client built from a channel builder ---
+pyspark/sql/tests/connect/test_connect_channel.py::ChannelBuilderTests::test_channel_options
  # passes channelOptions, which raises NOT_IMPLEMENTED by design 
(dev/parity/known-differences.md, custom gRPC channels)
+pyspark/sql/tests/connect/test_connect_channel.py::ChannelBuilderTests::test_keepalive_explicit_channel_option_wins
  # passes channelOptions, as above
+pyspark/sql/tests/connect/test_connect_channel.py::ChannelBuilderTests::test_valid_channel_creation
  # toChannel builds a grpcio channel; the gRPC channel is the Rust 
transport's, by design
+pyspark/sql/tests/connect/test_connect_channel.py::ChannelBuilderTests::test_metadata_with_session_id
  # builds SparkConnectClient from a channel builder; ours is built from a 
session, which checks session_id when the session is built
 pyspark/sql/tests/connect/test_connect_retry.py  # tests the grpcio retry 
policy of the Python client; the Rust transport has its own
 pyspark/sql/tests/connect/test_connect_local_server.py  # starts a local 
grpcio server for the Python client; the Rust transport has no such server
 pyspark/sql/tests/connect/test_connect_plan.py  # tests the Python client's 
proto plan internals (LogicalPlan classes), built in Rust here


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

Reply via email to