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 f8cc3790 [SPARK-61362][CONNECT] Report and retry transport failures as
grpc-python does, and send the request fields, keepalive errors and user agent
of PySpark
f8cc3790 is described below
commit f8cc379023dd7d636b7e638eb9e5fb2ab694dffb
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 06:50:01 2026 +0900
[SPARK-61362][CONNECT] Report and retry transport failures as grpc-python
does, and send the request fields, keepalive errors and user agent of PySpark
### What changes were proposed in this pull request?
[SPARK-61362](https://issues.apache.org/jira/browse/SPARK-61362):
low-priority transport findings of a review of the Rust core, each checked
against PySpark 4.3.0 and grpc-python 1.76.
- **Codes and retries** (`crates/spark-connect-core/src/retries.rs`,
`error.rs`):
- The new `retries::grpc_python_code` gives a failed call the code that
grpc-python reports for it.
- A status that the server sent keeps its code.
- A dropped connection, a GOAWAY that processed no stream, and a call
that a closing connection canceled before sending are `UNAVAILABLE`.
- A stream reset of a reason that tonic leaves `UNKNOWN`
(`STREAM_CLOSED`, `FRAME_SIZE_ERROR`, `HTTP_1_1_REQUIRED`) is `INTERNAL`.
- `RetryPolicy::can_retry` and `SparkError::from_grpc_status` (so
`grpc_code()`, and the drop-in's `getGrpcStatusCode()`) use this code.
- **The transport seam** (`crates/pyspark-rs/src/transport.rs`), which the
pandas-parity gate runs official PySpark over, reports the per-message errors
of a stream with that code too.
- **Request fields** (`client.rs`), as PySpark sets them per request type:
- `client_type` on ExecutePlan, AnalyzePlan, Config, Interrupt,
FetchErrorDetails, ReattachExecute, ReleaseExecute and ReleaseSession;
`"python"` on CloneSession.
- No `client_observed_server_side_session_id` on ReleaseExecute,
CloneSession, AddArtifacts and ArtifactStatus. It is set on the first
ExecutePlan of a session, after the lookup that gives the server-side session
ID.
- No `user_id` gRPC header: PySpark sends the user ID in the user context
only.
- **Channel** (`channel.rs`):
- With the keepalive enabled, a `grpc_keepalive_time_ms` or
`grpc_keepalive_timeout_ms` that Python's `int()` does not read raises
PySpark's `ValueError` ("invalid literal for int() with base 10: 'abc'") when
the client connects. The values are read as `int()` reads them.
- The user agent names the OS as Python's
`platform.uname().system.lower()` does: `darwin`, not `macos`.
- **Plan compression** (`client.rs`):
- Plans are sized with `encoded_len()` and encoded only when over the
threshold.
- The plan of an execution is compressed again after an `on_execute_plan`
hook ran. The drop-in's hook resolves there the placeholder of a DataFrame that
a hook put in.
### Why are the changes needed?
- grpc-python reports a stream reset with `STREAM_CLOSED`,
`FRAME_SIZE_ERROR` or `HTTP_1_1_REQUIRED` as `INTERNAL`, which PySpark does not
retry. Ours retried it 15 times, over about 10 minutes.
- A GOAWAY that processed no stream was retried only when tonic happened to
report it as `UNKNOWN`: in most runs it was `INTERNAL` or `RESOURCE_EXHAUSTED`.
grpc-python reports `UNAVAILABLE`, and PySpark retries it.
- The Rust transport passed a dropped connection on as `UNKNOWN`, so
official PySpark over it did not reattach. Through a proxy that resets a
`range(3_000_000).collect()` mid-result, it now reattaches and returns all
rows. Before, it raised `UNKNOWN`.
- PySpark sends no `user_id` header and no observed session ID on these
requests, and sends `client_type` on all of them. A bad keepalive parameter was
ignored, and the OS name differed.
- Plans were encoded only to be measured. And the plan of a DataFrame that
a hook put in went uncompressed over the threshold, where PySpark's hook puts
in the plan of `to_proto`, which compresses it.
### Does this PR introduce _any_ user-facing change?
Yes:
- `SparkError::grpc_code` and the drop-in's `getGrpcStatusCode()` give the
codes of grpc-python for transport failures: `UNAVAILABLE` where they were
`UNKNOWN` or `CANCELLED`, and `INTERNAL` for the stream resets above. These
resets are no longer retried, and GOAWAYs always are. `docs/compatibility.md`
notes it.
- The request fields and the user agent above change.
- A non-integer keepalive parameter raises `ValueError` at connect.
- The new public function `spark_connect_core::retries::grpc_python_code`.
### How was this patch tested?
- Rust unit tests, each failing without its change:
- `retries.rs`:
`test_cannot_retry_a_stream_the_server_resets_as_grpc_python` and
`test_can_retry_a_connection_the_server_ends_with_a_goaway_as_grpc_python`. A
raw HTTP/2 server answers a call with RST_STREAM or GOAWAY frames of each
reason. Asserts are added to the existing reset, CANCELLED and server-status
tests.
- `client.rs` `request_fields_tests`:
- `requests_carry_the_client_type_and_the_observed_session_of_pyspark`:
a recording server, over every RPC;
- `requests_carry_no_user_id_header_as_pyspark`;
-
`connect_raises_for_a_keepalive_param_that_is_not_an_integer_as_pyspark`;
- `the_plan_that_a_hook_puts_in_is_compressed_as_pyspark`.
- `channel.rs`: `keepalive_params_are_read_with_python_int_as_pyspark`
and `user_agent_names_the_os_as_pyspark`.
- Offline Python (`python/tests/test_dropin_offline.py`, placed before
`test_broadcast_type_check`):
-
`test_the_transport_reports_a_dropped_connection_as_unavailable_as_grpc_python`;
-
`test_create_raises_for_a_keepalive_param_that_is_not_an_integer_as_pyspark`;
-
`test_the_plan_of_a_dataframe_that_a_hook_puts_in_is_compressed_as_pyspark`.
`_sent_relation` takes the kind of its request now: an ExecutePlan
request has `client_type` as its field 4.
- Live:
-
`test_the_server_runs_the_compressed_plans_of_a_session_as_pyspark_sends_them`
(`crates/spark-connect/tests/e2e_integration.rs`): under a threshold of 1000, a
statement, a schema analysis, a collect and a temp view run compressed on a
local Spark 4.3.0 server.
- `e2e_reattach_drop` passes.
- A wire probe (fake server) of official PySpark and of ours now gives the
same fields per request. Two exceptions: the `client_type` of AddArtifacts and
ArtifactStatus, which the Scala client sends and the server reads nowhere, and
the `python/rust` of the user agent, a documented difference.
- Checks:
- lib tests of both crates (739 passed);
- the build of all tests, also with `wasm-udf` and `datafusion,polars`,
without warnings;
- `cargo fmt --all --check`, and clippy with no diagnostics on the
changed lines;
- offline Python suites (3039 passed, 8 skipped, before the helper fix of
the one failing test);
- live drop-in, Arrow and ML suites against a local Spark 4.3.0 server
(265 passed).
### 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 #469 from HyukjinKwon/p3-core.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/transport.rs | 9 +-
crates/spark-connect-core/src/channel.rs | 173 ++++++-
crates/spark-connect-core/src/client.rs | 527 +++++++++++++++++++--
crates/spark-connect-core/src/error.rs | 14 +-
crates/spark-connect-core/src/retries.rs | 187 +++++++-
.../spark-connect-core/tests/reattach_cleanup.rs | 3 +-
crates/spark-connect/tests/e2e_integration.rs | 62 +++
docs/compatibility.md | 6 +
python/tests/test_dropin_offline.py | 142 +++++-
9 files changed, 1059 insertions(+), 64 deletions(-)
diff --git a/crates/pyspark-rs/src/transport.rs
b/crates/pyspark-rs/src/transport.rs
index 8af5bb83..2615f26f 100644
--- a/crates/pyspark-rs/src/transport.rs
+++ b/crates/pyspark-rs/src/transport.rs
@@ -21,7 +21,7 @@ use tokio::sync::Notify;
use spark_connect_core::channel::ChannelBuilder;
use spark_connect_core::client::SparkConnectClient;
-use spark_connect_core::retries::RetryPolicy;
+use spark_connect_core::retries::{grpc_python_code, RetryPolicy};
use spark_connect_core::runtime::{block_on, POLL_INTERVAL};
use spark_connect_proto as proto;
@@ -37,7 +37,8 @@ fn err<E: std::fmt::Display>(e: E) -> PyErr {
fn spark_err_to_py(py: Python<'_>, e: spark_connect_core::error::SparkError)
-> PyErr {
// Any error that carries a gRPC status code (even a transport error like
a DNS
// failure, which has no status details) should become a RustRpcError so
the
- // reference client maps it to the right SparkConnectGrpcException with
the code.
+ // reference client maps it to the right SparkConnectGrpcException with
the code, which is
+ // the one grpc-python reports (`SparkError::from_grpc_status`).
match e.grpc_code() {
Some(code) => {
let details = e.grpc_details().unwrap_or(&[]);
@@ -160,8 +161,10 @@ impl ResponseStream {
Ok(Some(Err(status))) => {
// On error, also drop the stream.
self.stream = None;
+ // The code that grpc-python gives it, as the reference client
retries and
+ // reattaches a dropped connection only as UNAVAILABLE.
Err(RustRpcError::new_err((
- status.code() as i32,
+ grpc_python_code(&status) as i32,
PyBytes::new(py, status.details()).unbind(),
status.message().to_string(),
)))
diff --git a/crates/spark-connect-core/src/channel.rs
b/crates/spark-connect-core/src/channel.rs
index 9d073976..ba6e9d26 100644
--- a/crates/spark-connect-core/src/channel.rs
+++ b/crates/spark-connect-core/src/channel.rs
@@ -275,6 +275,30 @@ impl ChannelBuilder {
})
}
+ /// The error of a keepalive parameter that is not an integer, as
PySpark's client raises it
+ /// when it opens its channel: with the keepalive enabled, its channel
options read the time
+ /// and then the timeout with `int()`, which raises `ValueError`.
+ pub(crate) fn check_keepalive(&self) -> Result<()> {
+ if !self.keepalive_enabled() {
+ return Ok(());
+ }
+ for key in [
+ PARAM_GRPC_KEEPALIVE_TIME_MS,
+ PARAM_GRPC_KEEPALIVE_TIMEOUT_MS,
+ ] {
+ match self.params.get(key) {
+ Some(value) if python_int(value).is_none() => {
+ return Err(SparkError::value_msg(format!(
+ "invalid literal for int() with base 10: {}",
+ python_repr(value)
+ )));
+ }
+ _ => {}
+ }
+ }
+ Ok(())
+ }
+
/// The user-agent string, matching Python's format and 2048-char cap.
pub fn user_agent(&self) -> Result<String> {
let ua = self
@@ -290,8 +314,10 @@ impl ChannelBuilder {
escaping, found {ua_len} characters."
)));
}
- let os = std::env::consts::OS.to_lowercase();
- Ok(format!("{ua} spark/{SPARK_VERSION} os/{os} python/rust"))
+ Ok(format!(
+ "{ua} spark/{SPARK_VERSION} os/{} python/rust",
+ os_name(std::env::consts::OS)
+ ))
}
/// gRPC metadata: every param except the reserved channel-config keys.
@@ -324,11 +350,74 @@ impl ChannelBuilder {
fn int_param(&self, key: &str, default: i64) -> i64 {
self.params
.get(key)
- .and_then(|v| v.parse().ok())
+ .and_then(|v| python_int(v))
.unwrap_or(default)
}
}
+/// The name of the operating system `os` (of `std::env::consts::OS`) as
Python's
+/// `platform.uname().system.lower()` gives it, which PySpark's user agent
carries.
+fn os_name(os: &str) -> &str {
+ match os {
+ "macos" => "darwin",
+ "solaris" | "illumos" => "sunos",
+ "hurd" => "gnu",
+ os => os,
+ }
+}
+
+/// `text` as Python's `int(text)` reads it: an optional sign and digits,
which single
+/// underscores may separate, between whitespace. Python also takes the
decimal digits of other
+/// scripts, which this does not. A value past the range of `i64` saturates.
+fn python_int(text: &str) -> Option<i64> {
+ let text = text.trim_matches(|c: char| c.is_whitespace() ||
('\x1c'..='\x1f').contains(&c));
+ let (negative, digits) = match text.strip_prefix('-') {
+ Some(digits) => (true, digits),
+ None => (false, text.strip_prefix('+').unwrap_or(text)),
+ };
+ if digits.is_empty()
+ || digits.starts_with('_')
+ || digits.ends_with('_')
+ || digits.contains("__")
+ {
+ return None;
+ }
+ let mut value: i64 = 0;
+ for c in digits.chars().filter(|&c| c != '_') {
+ let digit = i64::from(c.to_digit(10)?);
+ value = value.saturating_mul(10).saturating_add(digit);
+ }
+ Some(if negative { -value } else { value })
+}
+
+/// `text` as Python's `repr` of a string shows it, as in the message of
`int()`: quoted with
+/// `'`, or with `"` when it has a `'` and no `"`, and with its backslashes
and control
+/// characters escaped.
+fn python_repr(text: &str) -> String {
+ let quote = if text.contains('\'') && !text.contains('"') {
+ '"'
+ } else {
+ '\''
+ };
+ let mut shown = String::from(quote);
+ for c in text.chars() {
+ match c {
+ '\\' => shown.push_str("\\\\"),
+ '\t' => shown.push_str("\\t"),
+ '\n' => shown.push_str("\\n"),
+ '\r' => shown.push_str("\\r"),
+ c if c == quote => {
+ shown.push('\\');
+ shown.push(c);
+ }
+ c if c.is_ascii_control() => shown.push_str(&format!("\\x{:02x}",
c as u32)),
+ c => shown.push(c),
+ }
+ }
+ shown.push(quote);
+ shown
+}
+
/// CPython `urllib.parse._splitparams`: params begin at the first `;` at or
/// after the last `/`; if there is no `/`, at the first `;` anywhere.
fn split_params(path: &str) -> (&str, &str) {
@@ -550,6 +639,84 @@ mod tests {
assert!(custom.metadata().is_empty());
}
+ #[test]
+ fn keepalive_params_are_read_with_python_int_as_pyspark() {
+ // As `int()` reads them: between whitespace, with a sign, and single
underscores.
+ for (value, ms) in [
+ ("%2030000%20", 30000),
+ ("3_0000", 30000),
+ ("+30000", 30000),
+ ("-5", -5),
+ ("007", 7),
+ ] {
+ let url =
format!("sc://localhost/;grpc_keepalive_time_ms={value}");
+ let c = ChannelBuilder::parse(&url).unwrap();
+ assert!(c.check_keepalive().is_ok(), "{value}");
+ assert_eq!(c.keepalive_time_ms(), ms, "{value}");
+ }
+ // The values that `int()` raises for, which PySpark's channel options
read when the
+ // keepalive is enabled: the time, then the timeout.
+ for (params, shown) in [
+ ("grpc_keepalive_time_ms=abc", "'abc'"),
+ ("grpc_keepalive_timeout_ms=abc", "'abc'"),
+ (
+ "grpc_keepalive_time_ms=abc;grpc_keepalive_timeout_ms=xyz",
+ "'abc'",
+ ),
+ ("grpc_keepalive_time_ms=", "''"),
+ ("grpc_keepalive_time_ms=1.5", "'1.5'"),
+ ("grpc_keepalive_time_ms=1__0", "'1__0'"),
+ ("grpc_keepalive_time_ms=_10", "'_10'"),
+ ("grpc_keepalive_time_ms=%2B%201", "'+ 1'"),
+ ("grpc_keepalive_time_ms=a'b", "\"a'b\""),
+ ("grpc_keepalive_time_ms=a%5Cb", "'a\\\\b'"),
+ ("grpc_keepalive_time_ms=%09", "'\\t'"),
+ ] {
+ let c =
ChannelBuilder::parse(&format!("sc://localhost/;{params}")).unwrap();
+ let error = c.check_keepalive().unwrap_err();
+ assert_eq!(
+ error.kind,
+ crate::error::SparkErrorKind::ValueError,
+ "{params}"
+ );
+ assert_eq!(
+ error.message(),
+ format!("invalid literal for int() with base 10: {shown}"),
+ "{params}"
+ );
+ }
+ // Neither is read when the keepalive is disabled.
+ for params in [
+ "grpc_keepalive_enabled=false;grpc_keepalive_time_ms=abc",
+ "grpc_keepalive_enabled=nope;grpc_keepalive_timeout_ms=abc",
+ "grpc_keepalive_without_calls=abc",
+ ] {
+ let c =
ChannelBuilder::parse(&format!("sc://localhost/;{params}")).unwrap();
+ assert!(c.check_keepalive().is_ok(), "{params}");
+ }
+ }
+
+ #[test]
+ fn user_agent_names_the_os_as_pyspark() {
+ // As Python's `platform.uname().system.lower()`.
+ for (os, name) in [
+ ("macos", "darwin"),
+ ("linux", "linux"),
+ ("windows", "windows"),
+ ("freebsd", "freebsd"),
+ ("illumos", "sunos"),
+ ] {
+ assert_eq!(os_name(os), name, "{os}");
+ }
+ let _env = set_env(&[("SPARK_CONNECT_USER_AGENT", None)]);
+ let c =
ChannelBuilder::parse("sc://localhost/;user_agent=abc").unwrap();
+ let shown = os_name(std::env::consts::OS);
+ assert_eq!(
+ c.user_agent().unwrap(),
+ format!("abc spark/4.3.0 os/{shown} python/rust")
+ );
+ }
+
#[test]
fn debug_of_a_builder_redacts_its_token() {
let c = ChannelBuilder::parse(
diff --git a/crates/spark-connect-core/src/client.rs
b/crates/spark-connect-core/src/client.rs
index 7dc74d31..9a026657 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -286,14 +286,20 @@ fn plan_compression_of(threshold: Option<&str>,
algorithm: Option<&str>) -> Plan
/// Replace the relation or command of `plan` with its zstd-compressed
operation, when it is over
/// `threshold` bytes and compression makes it smaller, as PySpark's
`_try_compress_and_set_plan`.
fn compress_over_threshold(plan: &mut Plan, threshold: usize) {
- let (op_type, message) = match &plan.op_type {
- Some(PlanOpType::Root(relation)) => (CompressedOpType::Relation,
relation.encode_to_vec()),
- Some(PlanOpType::Command(command)) => (CompressedOpType::Command,
command.encode_to_vec()),
+ let (op_type, size) = match &plan.op_type {
+ Some(PlanOpType::Root(relation)) => (CompressedOpType::Relation,
relation.encoded_len()),
+ Some(PlanOpType::Command(command)) => (CompressedOpType::Command,
command.encoded_len()),
_ => return,
};
- if message.len() <= threshold {
+ // The size of the encoding, without encoding the plans that are not over
the threshold.
+ if size <= threshold {
return;
}
+ let message = match &plan.op_type {
+ Some(PlanOpType::Root(relation)) => relation.encode_to_vec(),
+ Some(PlanOpType::Command(command)) => command.encode_to_vec(),
+ _ => return,
+ };
let Ok(data) = zstd::encode_all(message.as_slice(),
zstd::DEFAULT_COMPRESSION_LEVEL) else {
return;
};
@@ -477,6 +483,8 @@ impl SparkConnectClient {
Some(id) => id,
None => Uuid::new_v4().to_string(),
};
+ // As PySpark's client, whose channel options read the keepalive
parameters next.
+ builder.check_keepalive()?;
// Parse user-agent.
let user_agent = builder.user_agent()?;
@@ -746,6 +754,28 @@ impl SparkConnectClient {
Ok(request)
}
+ /// `request` as the hook of the executions returns it, with its plan
compressed again when a
+ /// hook ran: a hook may put in a plan, such as the drop-in's hook, which
resolves the plan of
+ /// a DataFrame there, as PySpark's hook would put in the plan of
`to_proto`, which compresses
+ /// it. A plan that is compressed already is kept.
+ async fn hooked_and_compressed(
+ &self,
+ request: ExecutePlanRequest,
+ ) -> Result<ExecutePlanRequest> {
+ let hook_set = self
+ .execute_plan_hook
+ .read()
+ .unwrap_or_else(|e| e.into_inner())
+ .is_some();
+ let mut request = self.hooked(request)?;
+ if hook_set {
+ if let Some(plan) = request.plan.as_mut() {
+ self.compress_plan(plan).await;
+ }
+ }
+ Ok(request)
+ }
+
/// Get the user ID, if set.
pub fn user_id(&self) -> Option<&str> {
self.user_id.as_deref()
@@ -975,11 +1005,14 @@ impl SparkConnectClient {
allow_arrow_batch_chunking(&mut request);
self.extend_user_context(&mut request.user_context);
self.fill_user_context(&mut request.user_context);
- self.observe_on(&mut request.client_observed_server_side_session_id);
+ self.fill_client_type(&mut request.client_type);
if let Some(plan) = request.plan.as_mut() {
self.compress_plan(plan).await;
}
- let request = self.hooked(request)?;
+ // After the lookup of the plan compression of the first plan, whose
response gives the
+ // 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?;
let mut req = Request::new(request);
self._attach_metadata(&mut req);
match self.stub.clone().execute_plan(req).await {
@@ -1039,6 +1072,7 @@ impl SparkConnectClient {
) -> Result<Streaming<ExecutePlanResponse>> {
self.ensure_open()?;
self.fill_user_context(&mut request.user_context);
+ self.fill_client_type(&mut request.client_type);
self.observe_on(&mut request.client_observed_server_side_session_id);
let mut req = Request::new(request);
self._attach_metadata(&mut req);
@@ -1050,14 +1084,15 @@ impl SparkConnectClient {
/// Release a (portion of a) running execution's response stream.
///
- /// Mirrors the `ReleaseExecute` RPC used by the reattachable execute path.
+ /// Mirrors the `ReleaseExecute` RPC used by the reattachable execute
path, whose requests
+ /// carry no observed server-side session ID in PySpark.
pub async fn release_execute(
&self,
mut request: ReleaseExecuteRequest,
) -> Result<ReleaseExecuteResponse> {
self.ensure_open()?;
self.fill_user_context(&mut request.user_context);
- self.observe_on(&mut request.client_observed_server_side_session_id);
+ self.fill_client_type(&mut request.client_type);
let mut req = Request::new(request);
self._attach_metadata(&mut req);
match self.stub.clone().release_execute(req).await {
@@ -1108,6 +1143,7 @@ impl SparkConnectClient {
self.ensure_open()?;
self.extend_user_context(&mut request.user_context);
self.fill_user_context(&mut request.user_context);
+ self.fill_client_type(&mut request.client_type);
if let Some(analyze) = request.analyze.as_mut() {
for plan in analyze_plans(analyze).into_iter().flatten() {
self.compress_plan(plan).await;
@@ -1177,14 +1213,17 @@ impl SparkConnectClient {
allow_arrow_batch_chunking(&mut request);
self.extend_user_context(&mut request.user_context);
// Before the iterator: its ReattachExecute and ReleaseExecute
requests take the
- // user context of this request, and the request of the hook, as
PySpark's iterator
- // is of the request that the hooks return.
+ // user context and the client type of this request, and the request
of the hook, as
+ // PySpark's iterator is of the request that the hooks return.
self.fill_user_context(&mut request.user_context);
- self.observe_on(&mut request.client_observed_server_side_session_id);
+ self.fill_client_type(&mut request.client_type);
if let Some(plan) = request.plan.as_mut() {
self.compress_plan(plan).await;
}
- let request = self.hooked(request)?;
+ // After the lookup of the plan compression of the first plan, whose
response gives the
+ // 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?;
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(
@@ -1248,6 +1287,7 @@ impl SparkConnectClient {
self.ensure_open()?;
self.extend_user_context(&mut request.user_context);
self.fill_user_context(&mut request.user_context);
+ self.fill_client_type(&mut request.client_type);
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);
@@ -1337,6 +1377,7 @@ impl SparkConnectClient {
keys: vec![key.to_string()],
})),
}),
+ client_type: Some(self.user_agent.clone()),
..Default::default()
};
let mut request = request;
@@ -1360,6 +1401,7 @@ impl SparkConnectClient {
self.ensure_open()?;
self.extend_user_context(&mut request.user_context);
self.fill_user_context(&mut request.user_context);
+ self.fill_client_type(&mut request.client_type);
let response = self
.with_retry(|| {
let deadline = self.rpc_deadlines.config;
@@ -1386,6 +1428,7 @@ impl SparkConnectClient {
self.ensure_open()?;
self.extend_user_context(&mut request.user_context);
self.fill_user_context(&mut request.user_context);
+ self.fill_client_type(&mut request.client_type);
let response = self
.with_retry(|| {
let deadline = self.rpc_deadlines.interrupt;
@@ -1695,22 +1738,22 @@ impl SparkConnectClient {
/// returned client, of the same channel, is of that session.
pub async fn clone_session(&self, new_session_id: Option<&str>) ->
Result<Self> {
self.ensure_open()?;
+ // As PySpark's request: of the client type "python", not of the user
agent, and with
+ // no observed server-side session ID.
let request = CloneSessionRequest {
session_id: self.session_id.clone(),
user_context: Some(UserContext {
user_id: self.user_id.clone().unwrap_or_default(),
..Default::default()
}),
- client_type: Some(self.user_agent.clone()),
+ client_type: Some("python".to_string()),
new_session_id: new_session_id.map(str::to_string),
..Default::default()
};
let response = self
.with_retry(|| {
let deadline = self.rpc_deadlines.clone_session;
- let mut request = request.clone();
- self.observe_on(&mut
request.client_observed_server_side_session_id);
- let mut req = with_deadline(Request::new(request), deadline);
+ let mut req = with_deadline(Request::new(request.clone()),
deadline);
self._attach_metadata(&mut req);
let mut stub = self.stub.clone();
async move {
@@ -1746,6 +1789,7 @@ impl SparkConnectClient {
user_id: self.user_id.clone().unwrap_or_default(),
..Default::default()
});
+ request.client_type = Some(self.user_agent.clone());
let response = self
.with_retry(|| {
@@ -1876,6 +1920,14 @@ impl SparkConnectClient {
}
}
+ /// The client type of a typed request that the caller built: the user
agent, unless it has
+ /// one, as PySpark's requests carry `client_type=self._builder.userAgent`.
+ fn fill_client_type(&self, client_type: &mut Option<String>) {
+ if client_type.is_none() {
+ *client_type = Some(self.user_agent.clone());
+ }
+ }
+
/// Build a fresh request context, even when no user ID is configured.
/// PySpark and Scala both send a present context on artifact requests.
fn new_user_context(&self) -> UserContext {
@@ -1919,18 +1971,17 @@ 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.
+ /// 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.
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 observed = std::sync::Arc::clone(&self.server_session_id);
let requests = requests.map(move |mut request| {
request.user_context = Some(user_context.clone());
request.client_type = Some(client_type.clone());
- request.client_observed_server_side_session_id =
observed_of(&observed);
request
});
let deadline = self.rpc_deadlines.add_artifacts;
@@ -1964,7 +2015,7 @@ impl SparkConnectClient {
}
/// The ArtifactStatus call of `names`, once: the response, which says
whether each artifact
- /// exists.
+ /// exists. As PySpark's, the request carries no observed server-side
session ID.
async fn artifact_status_rpc(
&self,
names: &[String],
@@ -1974,7 +2025,6 @@ impl SparkConnectClient {
request.user_context = Some(self.new_user_context());
request.client_type = Some(self.user_agent.clone());
request.names = names.to_vec();
- self.observe_on(&mut request.client_observed_server_side_session_id);
let deadline = self.rpc_deadlines.artifact_status;
let mut req = with_deadline(Request::new(request), deadline);
@@ -1998,12 +2048,8 @@ impl SparkConnectClient {
if let Ok(header_value) = MetadataValue::from_str(&self.user_agent) {
let _ = metadata.insert("user-agent", header_value);
}
- // Add user_id if present
- if let Some(user_id) = &self.user_id {
- if let Ok(header_value) = MetadataValue::from_str(user_id) {
- let _ = metadata.insert("user_id", header_value);
- }
- }
+ // No user_id header: as PySpark's `ChannelBuilder.metadata()`, which
leaves the user ID
+ // to the user context of the requests.
// Add custom metadata
for (k, v) in &self.metadata {
if let Ok(header_value) = MetadataValue::from_str(v) {
@@ -2066,11 +2112,6 @@ impl SparkConnectClient {
if let Ok(v) = MetadataValue::from_str(&self.user_agent) {
let _ = metadata.insert("user-agent", v);
}
- if let Some(user_id) = &self.user_id {
- if let Ok(v) = MetadataValue::from_str(user_id) {
- let _ = metadata.insert("user_id", v);
- }
- }
for (k, v) in &self.metadata {
if let Ok(v) = MetadataValue::from_str(v) {
if let Ok(key) =
tonic::metadata::MetadataKey::from_bytes(k.as_bytes()) {
@@ -2084,9 +2125,9 @@ impl SparkConnectClient {
/// Sends `request` in the background, so that reading is not delayed,
retrying under the
/// client's retry policy. Like the reference client, a failure is only
logged: the server
/// removes an execution that is never released once it has been detached
for
- /// `spark.connect.execute.manager.detachedTimeout`.
- fn spawn_release(&self, metadata: MetadataMap, mut request:
ReleaseExecuteRequest) {
- self.observe_on(&mut request.client_observed_server_side_session_id);
+ /// `spark.connect.execute.manager.detachedTimeout`. As the reference's,
the request carries
+ /// no observed server-side session ID.
+ fn spawn_release(&self, metadata: MetadataMap, request:
ReleaseExecuteRequest) {
let mut stub = self.stub.clone();
let policy = self.retry_policy.clone();
let release = async move {
@@ -3228,3 +3269,419 @@ mod plan_compression_tests {
assert!(analyze_plans(&mut Analyze::SparkVersion(SparkVersion
{})).is_empty());
}
}
+
+/// The fields of the requests of each RPC, which a server records.
+#[cfg(test)]
+mod request_fields_tests {
+ use super::*;
+ use crate::bytes_codec::BytesCodec;
+ use spark_connect_proto::execute_plan_response::{ResponseType,
ResultComplete};
+ use tonic::codegen::{http, BoxFuture};
+ use tonic::server::{
+ ClientStreamingService, NamedService, ServerStreamingService,
UnaryService,
+ };
+
+ const SERVER_ID: &str = "server-1";
+
+ /// The method and the bytes of each request that the server received, in
order.
+ type Received = std::sync::Arc<std::sync::Mutex<Vec<(String, Vec<u8>)>>>;
+
+ #[derive(Clone)]
+ struct Recorder(Received);
+
+ impl NamedService for Recorder {
+ const NAME: &'static str = "spark.connect.SparkConnectService";
+ }
+
+ impl tonic::codegen::Service<http::Request<tonic::body::Body>> for
Recorder {
+ type Response = http::Response<tonic::body::Body>;
+ type Error = std::convert::Infallible;
+ type Future = 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: http::Request<tonic::body::Body>) ->
Self::Future {
+ let method = request
+ .uri()
+ .path()
+ .trim_start_matches("/spark.connect.SparkConnectService/")
+ .to_string();
+ let rpc = Rpc(self.0.clone(), method.clone());
+ Box::pin(async move {
+ let mut grpc = tonic::server::Grpc::new(BytesCodec);
+ Ok(match method.as_str() {
+ "ExecutePlan" => grpc.server_streaming(rpc, request).await,
+ "AddArtifacts" => grpc.client_streaming(rpc,
request).await,
+ _ => grpc.unary(rpc, request).await,
+ })
+ })
+ }
+ }
+
+ /// The response of `method`, of the server-side session `SERVER_ID`.
+ fn response_of(method: &str) -> Vec<u8> {
+ let id = SERVER_ID.to_string();
+ match method {
+ "ExecutePlan" => ExecutePlanResponse {
+ server_side_session_id: id,
+ response_id: "complete".into(),
+ response_type:
Some(ResponseType::ResultComplete(ResultComplete {})),
+ ..Default::default()
+ }
+ .encode_to_vec(),
+ "AnalyzePlan" => AnalyzePlanResponse {
+ server_side_session_id: id,
+ ..Default::default()
+ }
+ .encode_to_vec(),
+ "Config" => ConfigResponse {
+ server_side_session_id: id,
+ ..Default::default()
+ }
+ .encode_to_vec(),
+ "Interrupt" => InterruptResponse {
+ server_side_session_id: id,
+ ..Default::default()
+ }
+ .encode_to_vec(),
+ "FetchErrorDetails" => FetchErrorDetailsResponse {
+ server_side_session_id: id,
+ ..Default::default()
+ }
+ .encode_to_vec(),
+ "ReleaseExecute" => ReleaseExecuteResponse {
+ server_side_session_id: id,
+ ..Default::default()
+ }
+ .encode_to_vec(),
+ "ReleaseSession" => spark_connect_proto::ReleaseSessionResponse {
+ server_side_session_id: id,
+ ..Default::default()
+ }
+ .encode_to_vec(),
+ "CloneSession" => spark_connect_proto::CloneSessionResponse {
+ server_side_session_id: id,
+ ..Default::default()
+ }
+ .encode_to_vec(),
+ "ArtifactStatus" => spark_connect_proto::ArtifactStatusesResponse {
+ server_side_session_id: id,
+ ..Default::default()
+ }
+ .encode_to_vec(),
+ "AddArtifacts" => spark_connect_proto::AddArtifactsResponse {
+ server_side_session_id: id,
+ ..Default::default()
+ }
+ .encode_to_vec(),
+ other => panic!("unexpected method {other}"),
+ }
+ }
+
+ /// An RPC of the recorder, of a method.
+ struct Rpc(Received, String);
+
+ impl Rpc {
+ fn record(&self, bytes: Vec<u8>) {
+ self.0.lock().unwrap().push((self.1.clone(), bytes));
+ }
+ }
+
+ impl UnaryService<Vec<u8>> for Rpc {
+ type Response = Vec<u8>;
+ type Future = BoxFuture<tonic::Response<Vec<u8>>, tonic::Status>;
+
+ fn call(&mut self, request: tonic::Request<Vec<u8>>) -> Self::Future {
+ self.record(request.into_inner());
+ let response = response_of(&self.1);
+ Box::pin(async move { Ok(tonic::Response::new(response)) })
+ }
+ }
+
+ type Frames =
+ futures::stream::Iter<std::vec::IntoIter<std::result::Result<Vec<u8>,
tonic::Status>>>;
+
+ impl ServerStreamingService<Vec<u8>> for Rpc {
+ type Response = Vec<u8>;
+ type ResponseStream = Frames;
+ type Future = BoxFuture<tonic::Response<Frames>, tonic::Status>;
+
+ fn call(&mut self, request: tonic::Request<Vec<u8>>) -> Self::Future {
+ self.record(request.into_inner());
+ let frames = futures::stream::iter(vec![Ok(response_of(&self.1))]);
+ Box::pin(async move { Ok(tonic::Response::new(frames)) })
+ }
+ }
+
+ impl ClientStreamingService<Vec<u8>> for Rpc {
+ type Response = Vec<u8>;
+ type Future = BoxFuture<tonic::Response<Vec<u8>>, tonic::Status>;
+
+ fn call(&mut self, request: tonic::Request<Streaming<Vec<u8>>>) ->
Self::Future {
+ let rpc = Rpc(self.0.clone(), self.1.clone());
+ Box::pin(async move {
+ let mut frames = request.into_inner();
+ while let Some(frame) = frames.message().await? {
+ rpc.record(frame);
+ }
+ Ok(tonic::Response::new(response_of(&rpc.1)))
+ })
+ }
+ }
+
+ /// 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>) {
+ macro_rules! fields {
+ ($request:ty) => {{
+ let request = <$request>::decode(bytes).unwrap();
+ (
+ request.client_type,
+ request.client_observed_server_side_session_id,
+ )
+ }};
+ }
+ match method {
+ "ExecutePlan" => fields!(ExecutePlanRequest),
+ "AnalyzePlan" => fields!(AnalyzePlanRequest),
+ "Config" => fields!(ConfigRequest),
+ "Interrupt" => fields!(InterruptRequest),
+ "FetchErrorDetails" => fields!(FetchErrorDetailsRequest),
+ "ReleaseExecute" => fields!(ReleaseExecuteRequest),
+ "CloneSession" => fields!(CloneSessionRequest),
+ "ArtifactStatus" => fields!(ArtifactStatusesRequest),
+ "AddArtifacts" =>
fields!(spark_connect_proto::AddArtifactsRequest),
+ // Of no observed server-side session ID.
+ "ReleaseSession" => (
+ ReleaseSessionRequest::decode(bytes).unwrap().client_type,
+ None,
+ ),
+ other => panic!("unexpected method {other}"),
+ }
+ }
+
+ /// 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]
+ async fn the_plan_that_a_hook_puts_in_is_compressed_as_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();
+ let incoming = futures::stream::unfold(listener, |listener| async {
+ Some((listener.accept().await.map(|(socket, _)| socket), listener))
+ });
+ let service = Recorder(received.clone());
+ 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 client = SparkConnectClient::connect(&builder).await.unwrap();
+ *client.plan_compression.lock().unwrap() = PlanCompression::Zstd {
threshold: 1000 };
+ let large = spark_connect_proto::Relation {
+ rel_type:
Some(spark_connect_proto::relation::RelType::LocalRelation(
+ spark_connect_proto::LocalRelation {
+ data: Some(vec![0; 64 * 1024].into()),
+ ..Default::default()
+ },
+ )),
+ ..Default::default()
+ };
+ client.set_execute_plan_hook(Some(std::sync::Arc::new(move |mut
request| {
+ request.plan = Some(Plan {
+ op_type: Some(PlanOpType::Root(large.clone())),
+ });
+ Ok(request)
+ })));
+ let small = || ExecutePlanRequest {
+ session_id: client.session_id().to_string(),
+ plan: Some(Plan {
+ op_type: Some(PlanOpType::Root(Default::default())),
+ }),
+ ..Default::default()
+ };
+ let mut stream = client.execute_plan(small()).await.unwrap();
+ while stream.message().await.unwrap().is_some() {}
+ let mut stream =
client.execute_plan_reattachable(small()).await.unwrap();
+ while stream.message().await.unwrap().is_some() {}
+ let executions: Vec<_> = received
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|(method, _)| method == "ExecutePlan")
+ .map(|(_, bytes)|
ExecutePlanRequest::decode(bytes.as_slice()).unwrap())
+ .collect();
+ assert_eq!(executions.len(), 2);
+ for request in executions {
+ let op_type = request.plan.and_then(|plan| plan.op_type);
+ assert!(
+ matches!(op_type, Some(PlanOpType::CompressedOperation(_))),
+ "{op_type:?}"
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn
requests_carry_the_client_type_and_the_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();
+ let incoming = futures::stream::unfold(listener, |listener| async {
+ Some((listener.accept().await.map(|(socket, _)| socket), listener))
+ });
+ let service = Recorder(received.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:{}/;user_id=u1",
address.port()))
+ .unwrap()
+ };
+ let client = SparkConnectClient::connect(&builder).await.unwrap();
+ let session_id = client.session_id().to_string();
+
+ // 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
+ // observes, as PySpark builds the plan before the request.
+ let mut stream = client
+ .execute_plan_reattachable(ExecutePlanRequest {
+ session_id: session_id.clone(),
+ plan: Some(Plan {
+ op_type: Some(PlanOpType::Root(Default::default())),
+ }),
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ while stream.message().await.unwrap().is_some() {}
+ client
+ .config(ConfigRequest {
+ session_id: session_id.clone(),
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ client
+ .analyze_plan(AnalyzePlanRequest {
+ session_id: session_id.clone(),
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ client
+ .interrupt(InterruptRequest {
+ session_id: session_id.clone(),
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ client
+ .fetch_error_details(FetchErrorDetailsRequest {
+ session_id: session_id.clone(),
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ client.artifact_status(&["files/a.txt"]).await.unwrap();
+ let file = tempfile::NamedTempFile::new().unwrap();
+ client
+ .add_named_artifact("files/a.txt", file.path().to_str().unwrap())
+ .await
+ .unwrap();
+ client.clone_session(None).await.unwrap();
+ client.release_session().await.unwrap();
+ // The release of the execution is sent in the background.
+ for _ in 0..200 {
+ if received
+ .lock()
+ .unwrap()
+ .iter()
+ .any(|(m, _)| m == "ReleaseExecute")
+ {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ server.abort();
+
+ let requests = received.lock().unwrap().clone();
+ let user_agent = client.user_agent.clone();
+ for method in [
+ "Config",
+ "ExecutePlan",
+ "ReleaseExecute",
+ "AnalyzePlan",
+ "Interrupt",
+ "FetchErrorDetails",
+ "ArtifactStatus",
+ "AddArtifacts",
+ "CloneSession",
+ "ReleaseSession",
+ ] {
+ assert!(requests.iter().any(|(m, _)| m == method), "no {method}");
+ }
+ 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.
+ let client_type = match method.as_str() {
+ "CloneSession" => "python",
+ _ => user_agent.as_str(),
+ };
+ let observed = match method.as_str() {
+ _ if index == 0 => None,
+ "ReleaseExecute" | "ReleaseSession" | "CloneSession" |
"ArtifactStatus"
+ | "AddArtifacts" => None,
+ _ => Some(SERVER_ID.to_string()),
+ };
+ assert_eq!(
+ fields_of(method, bytes),
+ (Some(client_type.to_string()), observed),
+ "{method}"
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn requests_carry_no_user_id_header_as_pyspark() {
+ // PySpark's `ChannelBuilder.metadata()` leaves the user_id parameter
out: the user ID is
+ // in the user context of the requests.
+ let builder =
ChannelBuilder::parse("sc://localhost/;user_id=u1;x-hdr=v").unwrap();
+ let client = SparkConnectClient::connect(&builder).await.unwrap();
+ let mut request = Request::new(());
+ client._attach_metadata(&mut request);
+ assert!(request.metadata().get("user_id").is_none());
+ assert_eq!(request.metadata().get("x-hdr").unwrap(), "v");
+ assert!(client.execution_metadata().get("user_id").is_none());
+ }
+
+ #[tokio::test]
+ async fn
connect_raises_for_a_keepalive_param_that_is_not_an_integer_as_pyspark() {
+ // As PySpark's client, whose channel options read the parameter with
`int()`.
+ let builder =
ChannelBuilder::parse("sc://localhost/;grpc_keepalive_time_ms=abc").unwrap();
+ let error = SparkConnectClient::connect(&builder)
+ .await
+ .err()
+ .expect("a keepalive time that is not an integer must raise");
+ assert_eq!(error.kind, SparkErrorKind::ValueError);
+ assert_eq!(
+ error.message(),
+ "invalid literal for int() with base 10: 'abc'"
+ );
+ }
+}
diff --git a/crates/spark-connect-core/src/error.rs
b/crates/spark-connect-core/src/error.rs
index afe560e6..71a2a6ed 100644
--- a/crates/spark-connect-core/src/error.rs
+++ b/crates/spark-connect-core/src/error.rs
@@ -465,12 +465,13 @@ impl SparkError {
/// `pyspark.errors.exceptions.connect.convert_exception` does, its
exception classes,
/// condition, message parameters, SQL state and stack trace are read from
the
/// `ErrorInfo`, and its kind from the classes.
[`SparkError::with_details`] completes it
- /// with what `FetchErrorDetails` returns.
+ /// with what `FetchErrorDetails` returns. The code is the one grpc-python
reports (see
+ /// [`crate::retries::grpc_python_code`]), so that a dropped connection is
`UNAVAILABLE`.
pub fn from_grpc_status(status: Status) -> Self {
let message = status.message().to_string();
- let code = status.code() as i32;
+ let code = crate::retries::grpc_python_code(&status);
let details = status.details().to_vec();
- let mut err = if status.code() == tonic::Code::DeadlineExceeded {
+ let mut err = if code == tonic::Code::DeadlineExceeded {
// As `SparkConnectClient._handle_rpc_error`, which raises this
for a call past its
// per-RPC deadline before it reads the error of the status.
Self::connect_msg(format!(
@@ -478,17 +479,16 @@ impl SparkError {
prevent silent hangs on broken connections. Deadlines can be
configured via \
the rpc_deadlines parameter of SparkConnectClient. To disable
all deadlines: \
SparkConnectClient(url,
rpc_deadlines=RpcDeadlines.disabled()).",
- status.code(),
- message
+ code, message
))
} else {
match parse_error_info(&details) {
Some(info) => Self::from_error_info(info, message),
- None => Self::connect_msg(format!("[{}] {}", status.code(),
message)),
+ None => Self::connect_msg(format!("[{}] {}", code, message)),
}
};
// Preserve the raw status so the PyO3 layer can rebuild the exact
pyspark exception.
- err.grpc_code = Some(code);
+ err.grpc_code = Some(code as i32);
if !details.is_empty() {
err.grpc_details = Some(details);
}
diff --git a/crates/spark-connect-core/src/retries.rs
b/crates/spark-connect-core/src/retries.rs
index 187c7da1..21f0bb1a 100644
--- a/crates/spark-connect-core/src/retries.rs
+++ b/crates/spark-connect-core/src/retries.rs
@@ -67,23 +67,42 @@ impl RetryPolicy {
/// Whether a failed RPC is retryable under this policy.
///
- /// Mirrors `pyspark.sql.connect.client.retries.DefaultPolicy.can_retry`:
- /// retry transient `UNAVAILABLE`, and `INTERNAL` errors whose message
carries
- /// `INVALID_CURSOR.DISCONNECTED` (a mid-stream cursor drop resumed via
reattach).
- /// A connection that closes under a call is `UNAVAILABLE` in grpc-python,
so it is retried
- /// too: tonic reports a reset during a call as `UNKNOWN`, and a call
queued on the
- /// connection but not sent yet as `CANCELLED`.
+ /// Mirrors `pyspark.sql.connect.client.retries.DefaultPolicy.can_retry`,
on the code that
+ /// grpc-python gives the failure (see [`grpc_python_code`]): retry
transient `UNAVAILABLE`,
+ /// and `INTERNAL` errors whose message carries
`INVALID_CURSOR.DISCONNECTED` (a mid-stream
+ /// cursor drop resumed via reattach).
pub fn can_retry(&self, status: &tonic::Status) -> bool {
- match status.code() {
+ match grpc_python_code(status) {
tonic::Code::Unavailable => true,
tonic::Code::Internal =>
status.message().contains("INVALID_CURSOR.DISCONNECTED"),
- tonic::Code::Unknown => is_transport_error(status),
- tonic::Code::Cancelled => is_unsent_request(status),
_ => false,
}
}
}
+/// The code of a failed RPC as grpc-python reports it, which PySpark's
retries and errors see.
+/// A status that the server sent keeps its code. tonic gives some transport
failures other
+/// codes: a connection that closes under a call is `UNAVAILABLE` in
grpc-python (tonic:
+/// `UNKNOWN`), and so are a connection that the server ends with a GOAWAY
(tonic: the code of
+/// its reason) and a call queued on the connection but not sent yet (tonic:
`CANCELLED`). A
+/// stream that the server resets has the code of its reason in both, except
for the reasons
+/// that tonic leaves `UNKNOWN`, such as `STREAM_CLOSED`, which grpc-python
reports as `INTERNAL`.
+pub fn grpc_python_code(status: &tonic::Status) -> tonic::Code {
+ let code = status.code();
+ match transport_errors(status).find_map(|error|
error.downcast_ref::<h2::Error>()) {
+ Some(error) if error.is_reset() => match code {
+ tonic::Code::Unknown => tonic::Code::Internal,
+ _ => code,
+ },
+ Some(error) if error.is_go_away() => tonic::Code::Unavailable,
+ _ => match code {
+ tonic::Code::Unknown if is_transport_error(status) =>
tonic::Code::Unavailable,
+ tonic::Code::Cancelled if is_unsent_request(status) =>
tonic::Code::Unavailable,
+ _ => code,
+ },
+ }
+}
+
/// The errors that tonic keeps as the source of a status that it built from a
transport error.
/// A status the server sent has none.
fn transport_errors(
@@ -539,9 +558,13 @@ mod tests {
#[tokio::test]
async fn test_can_retry_a_connection_reset_during_a_response() {
let status =
status_of_first_response(serve_one_response(true).await).await;
- // tonic reports the reset as UNKNOWN, with the transport error as its
source.
+ // tonic reports the reset as UNKNOWN, with the transport error as its
source, and
+ // grpc-python as UNAVAILABLE, which the error of the client reports
too.
assert_eq!(status.code(), tonic::Code::Unknown);
+ assert_eq!(grpc_python_code(&status), tonic::Code::Unavailable);
assert!(RetryPolicy::default().can_retry(&status), "{status:?}");
+ let error = crate::error::SparkError::from_grpc_status(status);
+ assert_eq!(error.grpc_code(), Some(tonic::Code::Unavailable as i32));
}
#[tokio::test]
@@ -549,7 +572,11 @@ mod tests {
let status =
status_of_first_response(serve_one_response(false).await).await;
assert_eq!(status.code(), tonic::Code::Unknown);
assert_eq!(status.message(), "boom");
+ // A status that the server sent keeps its code.
+ assert_eq!(grpc_python_code(&status), tonic::Code::Unknown);
assert!(!RetryPolicy::default().can_retry(&status));
+ let error = crate::error::SparkError::from_grpc_status(status);
+ assert_eq!(error.grpc_code(), Some(tonic::Code::Unknown as i32));
}
/// The error of a request queued on an HTTP/2 connection that closes
before sending it, as
@@ -576,9 +603,148 @@ mod tests {
// tonic reports it as CANCELLED, with hyper's error as its source.
let status = tonic::Status::from_error(Box::new(error));
assert_eq!(status.code(), tonic::Code::Cancelled);
+ assert_eq!(grpc_python_code(&status), tonic::Code::Unavailable);
+ assert!(RetryPolicy::default().can_retry(&status), "{status:?}");
+ }
+
+ /// How a server answers the request headers of a call with one HTTP/2
frame.
+ #[derive(Clone, Copy, Debug)]
+ enum Answer {
+ /// A RST_STREAM of the stream of the call, of this error code.
+ Reset(h2::Reason),
+ /// A GOAWAY of this error code that processed no stream.
+ GoAway(h2::Reason),
+ }
+
+ /// Serves one connection in raw HTTP/2 frames, which answers the request
of a call with
+ /// `answer`, and then reads the frames of the client until it closes the
connection: the
+ /// frame, not the end of the connection, ends the call.
+ async fn serve_one_frame(answer: Answer) -> std::net::SocketAddr {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ fn frame(kind: u8, flags: u8, stream: u32, payload: &[u8]) -> Vec<u8> {
+ let length = (payload.len() as u32).to_be_bytes();
+ let mut frame = vec![length[1], length[2], length[3], kind, flags];
+ frame.extend_from_slice(&stream.to_be_bytes());
+ frame.extend_from_slice(payload);
+ frame
+ }
+ let listener =
tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut preface = [0; 24];
+ socket.read_exact(&mut preface).await.unwrap();
+ // SETTINGS.
+ socket.write_all(&frame(0x4, 0, 0, &[])).await.unwrap();
+ loop {
+ let mut head = [0; 9];
+ if socket.read_exact(&mut head).await.is_err() {
+ return;
+ }
+ let mut payload =
+ vec![0; u32::from_be_bytes([0, head[0], head[1], head[2]])
as usize];
+ if socket.read_exact(&mut payload).await.is_err() {
+ return;
+ }
+ let stream = u32::from_be_bytes([head[5], head[6], head[7],
head[8]]) & 0x7fff_ffff;
+ let reply = match (head[3], answer) {
+ // The acknowledgement of the SETTINGS of the client.
+ (0x4, _) if head[4] & 0x1 == 0 => frame(0x4, 0x1, 0, &[]),
+ (0x1, Answer::Reset(reason)) => {
+ frame(0x3, 0, stream, &u32::from(reason).to_be_bytes())
+ }
+ (0x1, Answer::GoAway(reason)) => {
+ // Of last stream ID 0.
+ let mut payload = vec![0; 4];
+
payload.extend_from_slice(&u32::from(reason).to_be_bytes());
+ frame(0x7, 0, 0, &payload)
+ }
+ _ => continue,
+ };
+ if socket.write_all(&reply).await.is_err() {
+ return;
+ }
+ }
+ });
+ address
+ }
+
+ /// The status that ends a call to `address`, before or after its response
headers.
+ async fn status_of_a_call(address: std::net::SocketAddr) -> tonic::Status {
+ let channel =
tonic::transport::Endpoint::from_shared(format!("http://{address}"))
+ .unwrap()
+ .connect()
+ .await
+ .unwrap();
+ let mut stub =
+
spark_connect_proto::spark_connect_service_client::SparkConnectServiceClient::new(
+ channel,
+ );
+ match stub
+ .execute_plan(spark_connect_proto::ExecutePlanRequest::default())
+ .await
+ {
+ Err(status) => status,
+ Ok(response) => response
+ .into_inner()
+ .message()
+ .await
+ .expect_err("the response ends with an error"),
+ }
+ }
+
+ #[tokio::test]
+ async fn test_cannot_retry_a_stream_the_server_resets_as_grpc_python() {
+ // The code of the reason, as grpc-python reports it: tonic leaves
STREAM_CLOSED,
+ // FRAME_SIZE_ERROR and HTTP_1_1_REQUIRED UNKNOWN, which grpc-python
reports as INTERNAL.
+ // A reset is the answer of the server about the call, not a failure
of the connection.
+ for (reason, code) in [
+ (h2::Reason::NO_ERROR, tonic::Code::Internal),
+ (h2::Reason::PROTOCOL_ERROR, tonic::Code::Internal),
+ (h2::Reason::INTERNAL_ERROR, tonic::Code::Internal),
+ (h2::Reason::STREAM_CLOSED, tonic::Code::Internal),
+ (h2::Reason::FRAME_SIZE_ERROR, tonic::Code::Internal),
+ (h2::Reason::CANCEL, tonic::Code::Cancelled),
+ (h2::Reason::HTTP_1_1_REQUIRED, tonic::Code::Internal),
+ ] {
+ let status =
status_of_a_call(serve_one_frame(Answer::Reset(reason)).await).await;
+ assert_eq!(grpc_python_code(&status), code, "{reason:?}:
{status:?}");
+ assert!(
+ !RetryPolicy::default().can_retry(&status),
+ "{reason:?}: {status:?}"
+ );
+ }
+ // A stream that the server refused, which it did not process, is
retried.
+ let refused =
serve_one_frame(Answer::Reset(h2::Reason::REFUSED_STREAM)).await;
+ let status = status_of_a_call(refused).await;
+ assert_eq!(grpc_python_code(&status), tonic::Code::Unavailable);
assert!(RetryPolicy::default().can_retry(&status), "{status:?}");
}
+ #[tokio::test]
+ async fn
test_can_retry_a_connection_the_server_ends_with_a_goaway_as_grpc_python() {
+ // grpc-python reports a call that a GOAWAY ends as UNAVAILABLE,
whatever its reason:
+ // tonic gives it the code of the reason, such as INTERNAL for
NO_ERROR.
+ for reason in [
+ h2::Reason::NO_ERROR,
+ h2::Reason::INTERNAL_ERROR,
+ h2::Reason::ENHANCE_YOUR_CALM,
+ ] {
+ let status =
status_of_a_call(serve_one_frame(Answer::GoAway(reason)).await).await;
+ assert_eq!(
+ grpc_python_code(&status),
+ tonic::Code::Unavailable,
+ "{reason:?}: {status:?}"
+ );
+ assert!(
+ RetryPolicy::default().can_retry(&status),
+ "{reason:?}: {status:?}"
+ );
+ let error = crate::error::SparkError::from_grpc_status(status);
+ assert_eq!(error.grpc_code(), Some(tonic::Code::Unavailable as
i32));
+ }
+ }
+
#[test]
fn test_cannot_retry_a_cancellation_the_server_sent_or_a_timeout() {
let p = RetryPolicy::default();
@@ -586,6 +752,7 @@ mod tests {
// tonic's timeout of a request is CANCELLED too.
let timeout =
tonic::Status::from_error(Box::new(tonic::TimeoutExpired(())));
assert_eq!(timeout.code(), tonic::Code::Cancelled);
+ assert_eq!(grpc_python_code(&timeout), tonic::Code::Cancelled);
assert!(!p.can_retry(&timeout));
}
}
diff --git a/crates/spark-connect-core/tests/reattach_cleanup.rs
b/crates/spark-connect-core/tests/reattach_cleanup.rs
index cdc9a9e8..9827a2bd 100644
--- a/crates/spark-connect-core/tests/reattach_cleanup.rs
+++ b/crates/spark-connect-core/tests/reattach_cleanup.rs
@@ -254,7 +254,8 @@ fn assert_metadata(metadata: &MetadataMap) {
metadata.get("authorization").unwrap(),
"Bearer fixture-token"
);
- assert_eq!(metadata.get("user_id").unwrap(), "transport-user");
+ // As PySpark's, which sends the user ID in the user context only.
+ assert!(metadata.get("user_id").is_none());
assert_eq!(metadata.get("x-cleanup").unwrap(), "fixture-value");
assert!(metadata.get("user-agent").is_some());
}
diff --git a/crates/spark-connect/tests/e2e_integration.rs
b/crates/spark-connect/tests/e2e_integration.rs
index 11937a8e..08174994 100644
--- a/crates/spark-connect/tests/e2e_integration.rs
+++ b/crates/spark-connect/tests/e2e_integration.rs
@@ -821,3 +821,65 @@ fn test_day_time_interval_real_server() {
assert_eq!(streamed, rows);
}
}
+
+#[test]
+#[allow(clippy::result_large_err)] // The hook returns the client's large
SparkError.
+fn
test_the_server_runs_the_compressed_plans_of_a_session_as_pyspark_sends_them() {
+ if !should_run() {
+ println!(
+ "Skipping
test_the_server_runs_the_compressed_plans_of_a_session_as_pyspark_sends_them \
+ - set SPARK_REMOTE to run"
+ );
+ return;
+ }
+ use proto::plan::compressed_operation::OpType;
+
+ let session = SparkSession::builder()
+ .remote(&remote_url())
+ .get_or_create()
+ .expect("Failed to create session");
+ // Before the first plan of the session, with which the client reads the
threshold once.
+ session
+ .conf()
+ .set("spark.connect.session.planCompression.threshold", "1000")
+ .expect("Failed to set the threshold");
+ // The kinds of the compressed operations of the executions, which a hook
sees as sent.
+ let compressed: std::sync::Arc<std::sync::Mutex<Vec<i32>>> =
Default::default();
+ let recorded = std::sync::Arc::clone(&compressed);
+ session.set_execute_plan_hook(Some(std::sync::Arc::new(move |request| {
+ let operation = request.plan.as_ref().and_then(|plan|
plan.op_type.as_ref());
+ if let Some(proto::plan::OpType::CompressedOperation(operation)) =
operation {
+ recorded.lock().unwrap().push(operation.op_type);
+ }
+ Ok(request)
+ })));
+
+ // A string literal of 12000 bytes makes each plan of it larger than the
threshold.
+ let text = "Apache Spark".repeat(1000);
+ // A command, the statement.
+ let df = session
+ .sql(&format!("SELECT '{text}' AS s"))
+ .expect("Failed to run the statement");
+ // An analysis of the relation of the statement.
+ let schema = df.schema().expect("Failed to analyze");
+ assert_eq!(schema.field_names().expect("field names"), ["s"]);
+ // A query of it.
+ let rows = df.collect().expect("Failed to collect");
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].get(0), Some(&Value::String(text.clone())));
+ // A command of it, which is not SQL.
+ df.create_or_replace_temp_view("compressed_plan_view")
+ .expect("Failed to create the view");
+ let view = session
+ .sql("SELECT * FROM compressed_plan_view WHERE length(s) = 12000")
+ .expect("Failed to query the view");
+ assert_eq!(view.count().expect("Failed to count the view"), 1);
+
+ let kinds = compressed.lock().unwrap().clone();
+ assert!(
+ kinds.contains(&(OpType::Command as i32)) &&
kinds.contains(&(OpType::Relation as i32)),
+ "the commands and the query over the threshold are sent compressed:
{kinds:?}"
+ );
+ session.set_execute_plan_hook(None);
+ session.stop().expect("stop");
+}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 82b89387..fc96ff7d 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -27,6 +27,12 @@ with `NOT_EXPECTED_TYPE` and an empty map with
`CANNOT_BE_EMPTY`. Before, such a
value filled string columns with its debug text. `fillna`, `fillna_double`,
`fillna_string` and `fillna_bool` are unchanged.
+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.
+
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
constructs or matches these representations. The `Column` and `DataFrame` APIs,
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 6fc44878..da3bc94a 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -3279,6 +3279,137 @@ def
test_column_attributes_are_fields_and_slices_are_substrings_as_pyspark():
c[:3]
+def _serve_one_raw_http2_call(answer):
+ """The URL of a server of one connection, in raw HTTP/2 frames, that
answers the request of a
+ call with `answer`: "reset" sends the response headers and the start of a
message, and then
+ resets the connection; "reset_at_once" resets the connection on the
request; "status" ends the
+ response with the status UNKNOWN "boom" that the server sends."""
+ import socket
+ import struct
+ import threading
+
+ def frame(kind, flags, stream, payload=b""):
+ return struct.pack(">I", len(payload))[1:] + bytes([kind, flags]) +
struct.pack(
+ ">I", stream) + payload
+
+ def read_exact(conn, size):
+ data = b""
+ while len(data) < size:
+ chunk = conn.recv(size - len(data))
+ if not chunk:
+ raise EOFError
+ data += chunk
+ return data
+
+ def reset(conn):
+ # Closing the socket now sends a RST instead of a FIN.
+ conn.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii",
1, 0))
+ conn.close()
+
+ # HPACK: ":status: 200" (static entry 8), and "content-type:
application/grpc", a literal of
+ # the static name 31.
+ headers = b"\x88\x0f\x10\x10application/grpc"
+ trailers = b"\x00\x0bgrpc-status\x012\x00\x0cgrpc-message\x04boom"
+ listener = socket.socket()
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(4)
+
+ def serve():
+ conn, _ = listener.accept()
+ try:
+ read_exact(conn, 24)
+ conn.sendall(frame(0x4, 0, 0))
+ while True:
+ head = read_exact(conn, 9)
+ read_exact(conn, int.from_bytes(head[:3], "big"))
+ kind, flags = head[3], head[4]
+ stream = int.from_bytes(head[5:9], "big") & 0x7FFFFFFF
+ if kind == 0x4 and not flags & 0x1:
+ conn.sendall(frame(0x4, 0x1, 0))
+ elif kind == 0x1 and answer == "reset_at_once":
+ return reset(conn)
+ elif kind == 0x1:
+ conn.sendall(frame(0x1, 0x4, stream, headers))
+ if answer == "status":
+ conn.sendall(frame(0x1, 0x5, stream, trailers))
+ continue
+ # The first 2 bytes of a message of 1000 bytes.
+ conn.sendall(frame(0x0, 0, stream,
b"\x00\x00\x00\x03\xe8\x01\x02"))
+ time.sleep(0.3)
+ return reset(conn)
+ except (EOFError, OSError):
+ conn.close()
+ finally:
+ listener.close()
+
+ threading.Thread(target=serve, daemon=True).start()
+ return f"sc://127.0.0.1:{listener.getsockname()[1]}"
+
+
[email protected]("answer,call,code", [
+ ("reset", "next", 14),
+ ("reset_at_once", "execute_plan", 14),
+ ("reset_at_once", "config", 14),
+ ("status", "next", 2),
+ ("status", "config", 2),
+])
+def
test_the_transport_reports_a_dropped_connection_as_unavailable_as_grpc_python(
+ answer, call, code
+):
+ # As grpc-python, the code of the errors of the stub that the reference
client drives is
+ # UNAVAILABLE (14) for a connection that drops, which that client retries
and reattaches,
+ # where tonic says UNKNOWN (2). A status that the server sends keeps its
code.
+ from pyspark import _pyspark
+
+ stub = _pyspark.RustConnectStub(_serve_one_raw_http2_call(answer))
+ with pytest.raises(_pyspark.RustRpcError) as error:
+ if call == "config":
+ stub.config(b"")
+ else:
+ responses = stub.execute_plan(b"")
+ next(iter(responses))
+ assert error.value.args[0] == code, error.value.args
+ if answer == "status":
+ assert "boom" in error.value.args[2]
+
+
+def
test_create_raises_for_a_keepalive_param_that_is_not_an_integer_as_pyspark():
+ # As PySpark's client, whose channel options read the keepalive time with
int() as it opens
+ # its channel: the ValueError of int(), before a session is made.
+ from pyspark.sql import SparkSession
+
+ with pytest.raises(ValueError) as error:
+
SparkSession.builder.remote("sc://localhost:1/;grpc_keepalive_time_ms=abc").create()
+ assert str(error.value) == "invalid literal for int() with base 10: 'abc'"
+
+
+def
test_the_plan_of_a_dataframe_that_a_hook_puts_in_is_compressed_as_pyspark(mock_connect):
+ # As PySpark's hook, which would put in the plan of `to_proto`, which
compresses it: the plan
+ # of a DataFrame that an on_execute_plan hook puts in is sent compressed
over the threshold.
+ pytest.importorskip("google.protobuf")
+ from pyspark.sql import SparkSession
+
+ _, service = mock_connect
+ service.confs = _plan_confs("1024")
+ frames = []
+
+ class PlanHook(SparkSession.Hook):
+ def on_execute_plan(self, request):
+ request.plan.root.CopyFrom(frames[0]._plan.plan(None))
+ return request
+
+ builder = SparkSession.builder.remote(service.remote)
+ builder._registerHook(lambda _: PlanHook())
+ spark = builder.create()
+ try:
+ frames.append(_long_literal_frame(spark))
+ spark.range(1).collect()
+ finally:
+ spark.stop()
+ plan = _sent_plan(service.execute_requests)
+ assert 1 not in plan and 3 in plan
+
+
def test_broadcast_type_check():
from pyspark.sql import functions as F
from pyspark.errors import PySparkTypeError
@@ -17688,11 +17819,12 @@ def
test_reader_schema_is_sent_as_pyspark_sends_it(mock_connect, read):
"arg_name": "schema", "expected_type": "str or struct type",
"arg_type": "LongType"}
-def _sent_relation(request, field):
- """The relation `field` of the root of a captured AnalyzePlanRequest or
ExecutePlanRequest:
- AnalyzePlanRequest.schema=4 -> plan=1, or ExecutePlanRequest.plan=3; then
Plan.root=1."""
+def _sent_relation(request, field, execute=False):
+ """The relation `field` of the root of a captured AnalyzePlanRequest, or
ExecutePlanRequest with
+ `execute`: AnalyzePlanRequest.schema=4 -> plan=1, or
ExecutePlanRequest.plan=3 (its field 4 is
+ the client type); then Plan.root=1."""
message = parse_message(request)
- plan = parse_message(message[4][0])[1][0] if 4 in message else
message[3][0]
+ plan = message[3][0] if execute else parse_message(message[4][0])[1][0]
root = parse_message(parse_message(plan)[1][0])
assert field in root, sorted(root)
return parse_message(root[field][0])
@@ -17907,7 +18039,7 @@ def
test_writer_bucket_sort_and_cluster_columns_are_checked_as_pyspark(offline_s
def _sent_catalog(request, field):
# Relation.catalog=200 -> the Catalog operation `field`.
- return parse_message(_sent_relation(request, 200)[field][0])
+ return parse_message(_sent_relation(request, 200, execute=True)[field][0])
def test_catalog_creates_tables_eagerly_as_pyspark(mock_connect):
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]