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 f02c091a [SPARK-61234][CONNECT] Apply the gRPC keepalive of the
connection string to the channel, as PySpark does, and redact the token in the
Debug of ChannelBuilder
f02c091a is described below
commit f02c091a445f60104006e1adfcd2b6c58a67dada
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Mon Nov 9 20:40:58 2026 +0900
[SPARK-61234][CONNECT] Apply the gRPC keepalive of the connection string to
the channel, as PySpark does, and redact the token in the Debug of
ChannelBuilder
### What changes were proposed in this pull request?
[SPARK-61234](https://issues.apache.org/jira/browse/SPARK-61234): apply the
gRPC keepalive of the connection string to the channel, as PySpark does, and
redact the token in the `Debug` of `ChannelBuilder`.
- The channel (both the TLS and the plaintext endpoint) now sends HTTP2
keepalive PINGs as PySpark's `ChannelBuilder._effective_channel_options`
configures gRPC (SPARK-58094): `grpc.keepalive_time_ms` (default 60 s),
`grpc.keepalive_timeout_ms` (default 20 s) and
`grpc.keepalive_permit_without_calls` (default on) become tonic's
`http2_keep_alive_interval`, `keep_alive_timeout` and `keep_alive_while_idle`.
With `grpc_keepalive_enabled=false`, as in PySpark, none is set. The new
`Channe [...]
- The `Debug` of the public `ChannelBuilder` was derived and printed the
token of the connection string (`params: {"token": "SECRET"}`). It now shows
the values of `token` and of an `authorization` param as `<redacted>`; the
other params, the host and the port as before.
The Spark 4.3.0 server tolerates client PINGs as often as every 10 s
regardless of its own keepalive settings (`spark.connect.grpc.keepAlive.*`), so
that a client with PySpark's default-on keepalive is never rejected with
`too_many_pings`.
### Why are the changes needed?
The keepalive params were parsed (`ChannelBuilder::keepalive_*`, and
`dev/parity/inventory.csv` lists them as done) but never applied: the tonic
channel had only a connect timeout. A connection that a NAT gateway or load
balancer drops without a TCP RST/FIN then leaves a blocked call, such as a long
`collect` or `awaitTermination`, waiting forever, where PySpark's PINGs fail it
with `UNAVAILABLE`, which is retried or reattached. And
`format!("{builder:?}")` put the token into logs.
### Does this PR introduce _any_ user-facing change?
Yes. The Rust client and the Python drop-in send keepalive PINGs as PySpark
does, configurable with the same connection-string params, and
`ChannelBuilder`'s `Debug` no longer shows the token.
### How was this patch tested?
- New unit tests in `crates/spark-connect-core/src/channel.rs`:
`keepalive_is_that_of_the_channel_options_of_pyspark` (PySpark's defaults,
overrides, turned off, a zero time, and that the params are not request
metadata) and `debug_of_a_builder_redacts_its_token`.
- The tests of the transport crate (188 passed) and the live Rust
`e2e_integration` tests (17 passed), with the keepalive on, against a local
Spark 4.3.0 server.
- The lib tests of both crates (666 passed), the build of all tests, also
with `wasm-udf`, the offline Python suites (2819 passed, 8 skipped), and the
live drop-in and Arrow suites (233 passed) and live cases (13 passed) against a
local Spark 4.3.0 server. Clippy reports no 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 #415 from HyukjinKwon/SPARK-61234-keepalive.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/spark-connect-core/src/channel.rs | 103 ++++++++++++++++++++++++++++++-
crates/spark-connect-core/src/client.rs | 41 +++++++++---
2 files changed, 133 insertions(+), 11 deletions(-)
diff --git a/crates/spark-connect-core/src/channel.rs
b/crates/spark-connect-core/src/channel.rs
index 6f1045b2..b168ecf4 100644
--- a/crates/spark-connect-core/src/channel.rs
+++ b/crates/spark-connect-core/src/channel.rs
@@ -36,13 +36,47 @@ const GRPC_DEFAULT_KEEPALIVE_TIMEOUT_MS: i64 = 20 * 1000;
const GRPC_DEFAULT_KEEPALIVE_WITHOUT_CALLS: bool = true;
/// Parsed Spark Connect connection string plus channel parameters.
-#[derive(Debug, Clone)]
+#[derive(Clone)]
pub struct ChannelBuilder {
params: BTreeMap<String, String>,
host: String, // display host; IPv6 wrapped in [ ]
port: u16,
}
+/// The gRPC/HTTP2 keepalive of a channel: PINGs after `time` without
activity, a connection that
+/// does not acknowledge one within `timeout` is dead, and `without_calls`
sends them also when
+/// no call is in flight.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Keepalive {
+ pub time: std::time::Duration,
+ pub timeout: std::time::Duration,
+ pub without_calls: bool,
+}
+
+/// Shows the params with the values of the token and of an `authorization`
header redacted:
+/// they are secrets, which a log of the builder must not hold.
+impl std::fmt::Debug for ChannelBuilder {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let params: BTreeMap<&str, &str> = self
+ .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() },
+ )
+ })
+ .collect();
+ f.debug_struct("ChannelBuilder")
+ .field("params", ¶ms)
+ .field("host", &self.host)
+ .field("port", &self.port)
+ .finish()
+ }
+}
+
impl ChannelBuilder {
/// Parse a `sc://host[:port][/;k=v;...]` connection string.
///
@@ -220,6 +254,23 @@ impl ChannelBuilder {
)
}
+ /// The keepalive that the channel applies, as PySpark's
`_effective_channel_options` sets
+ /// `grpc.keepalive_time_ms`, `grpc.keepalive_timeout_ms` and
+ /// `grpc.keepalive_permit_without_calls`: none when
`grpc_keepalive_enabled` is false (or the
+ /// time is not positive, which no PING interval can be).
+ pub fn keepalive(&self) -> Option<Keepalive> {
+ let millis = |ms: i64|
std::time::Duration::from_millis(u64::try_from(ms).unwrap_or(0));
+ let time = self.keepalive_time_ms();
+ if !self.keepalive_enabled() || time <= 0 {
+ return None;
+ }
+ Some(Keepalive {
+ time: millis(time),
+ timeout: millis(self.keepalive_timeout_ms()),
+ without_calls: self.keepalive_without_calls(),
+ })
+ }
+
/// The user-agent string, matching Python's format and 2048-char cap.
pub fn user_agent(&self) -> Result<String> {
let ua = self
@@ -440,6 +491,56 @@ mod tests {
assert!(c.keepalive_enabled());
}
+ #[test]
+ fn keepalive_is_that_of_the_channel_options_of_pyspark() {
+ use std::time::Duration;
+ // PySpark's defaults (SPARK-58094): a PING after 60 s, 20 s for its
ack, also idle.
+ assert_eq!(
+ ChannelBuilder::parse("sc://localhost").unwrap().keepalive(),
+ Some(Keepalive {
+ time: Duration::from_secs(60),
+ timeout: Duration::from_secs(20),
+ without_calls: true,
+ })
+ );
+ let custom = ChannelBuilder::parse(
+
"sc://localhost/;grpc_keepalive_time_ms=30000;grpc_keepalive_timeout_ms=5000;\
+ grpc_keepalive_without_calls=false",
+ )
+ .unwrap();
+ assert_eq!(
+ custom.keepalive(),
+ Some(Keepalive {
+ time: Duration::from_secs(30),
+ timeout: Duration::from_secs(5),
+ without_calls: false,
+ })
+ );
+ // Turned off, as PySpark then adds none of the keepalive options.
+ let off =
ChannelBuilder::parse("sc://localhost/;grpc_keepalive_enabled=FALSE").unwrap();
+ assert_eq!(off.keepalive(), None);
+ let zero =
ChannelBuilder::parse("sc://localhost/;grpc_keepalive_time_ms=0").unwrap();
+ assert_eq!(zero.keepalive(), None);
+ // The keepalive params are channel options, not request metadata.
+ assert!(custom.metadata().is_empty());
+ }
+
+ #[test]
+ fn debug_of_a_builder_redacts_its_token() {
+ let c = ChannelBuilder::parse(
+
"sc://spark.example.com:443/;token=SECRET123;authorization=Bearer%20XYZ;x-custom=1",
+ )
+ .unwrap();
+ let shown = format!("{c:?}");
+ assert!(!shown.contains("SECRET123"), "{shown}");
+ assert!(!shown.contains("XYZ"), "{shown}");
+ assert!(shown.contains("<redacted>"), "{shown}");
+ assert!(shown.contains("x-custom"), "{shown}");
+ assert!(shown.contains("spark.example.com"), "{shown}");
+ // The token itself is unchanged.
+ assert_eq!(c.token().as_deref(), Some("SECRET123"));
+ }
+
#[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 a1382ef6..233052e2 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -35,6 +35,23 @@ use crate::thread_entries::forget_when_thread_ends;
/// to a down server would hang forever instead of raising `UNAVAILABLE`.
const READY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
+/// Apply the keepalive of the connection string, as PySpark's channel options
do (SPARK-58094):
+/// HTTP2 PINGs detect a connection that a NAT gateway or load balancer
dropped silently, so that
+/// a blocked call fails with `UNAVAILABLE`, which the client retries or
reattaches, instead of
+/// waiting on the dead connection forever.
+fn with_keepalive(
+ endpoint: tonic::transport::Endpoint,
+ builder: &ChannelBuilder,
+) -> tonic::transport::Endpoint {
+ match builder.keepalive() {
+ Some(keepalive) => endpoint
+ .http2_keep_alive_interval(keepalive.time)
+ .keep_alive_timeout(keepalive.timeout)
+ .keep_alive_while_idle(keepalive.without_calls),
+ None => endpoint,
+ }
+}
+
/// gRPC/HTTP header carrying the connection-string `token` as `Bearer
<token>`.
/// Named here (rather than as a string literal) so the key is written once.
const AUTHORIZATION_HEADER: &str = "authorization";
@@ -346,18 +363,22 @@ impl SparkConnectClient {
.domain_name(domain)
.with_native_roots();
-
tonic::transport::Channel::from_shared(format!("https://{endpoint}"))
- .map_err(|e| SparkError::connect_msg(format!("Invalid
endpoint: {}", e)))?
- .tls_config(tls_config)
- .map_err(|e| SparkError::connect_msg(format!("Failed to
configure TLS: {}", e)))?
- .connect_timeout(READY_TIMEOUT)
- .connect_lazy()
+ let tls_endpoint =
+
tonic::transport::Channel::from_shared(format!("https://{endpoint}"))
+ .map_err(|e| SparkError::connect_msg(format!("Invalid
endpoint: {}", e)))?
+ .tls_config(tls_config)
+ .map_err(|e| {
+ SparkError::connect_msg(format!("Failed to configure
TLS: {}", e))
+ })?
+ .connect_timeout(READY_TIMEOUT);
+ with_keepalive(tls_endpoint, builder).connect_lazy()
} else {
// Plaintext connection (for localhost development)
-
tonic::transport::Channel::from_shared(format!("http://{endpoint}"))
- .map_err(|e| SparkError::connect_msg(format!("Invalid
endpoint: {}", e)))?
- .connect_timeout(READY_TIMEOUT)
- .connect_lazy()
+ let plain_endpoint =
+
tonic::transport::Channel::from_shared(format!("http://{endpoint}"))
+ .map_err(|e| SparkError::connect_msg(format!("Invalid
endpoint: {}", e)))?
+ .connect_timeout(READY_TIMEOUT);
+ with_keepalive(plain_endpoint, builder).connect_lazy()
};
// Raise the message-size cap from tonic's 4 MiB default (too small
for real Arrow
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]