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 c1486d28 [SPARK-61263][CONNECT][PYTHON] Compress a plan over the
server's plan compression threshold, as PySpark does
c1486d28 is described below
commit c1486d286db17c97fb9ba1aca62def691c40e0c5
Author: Timothy Meehan <[email protected]>
AuthorDate: Tue Nov 10 10:44:41 2026 +0900
[SPARK-61263][CONNECT][PYTHON] Compress a plan over the server's plan
compression threshold, as PySpark does
### What changes were proposed in this pull request?
[SPARK-61263](https://issues.apache.org/jira/browse/SPARK-61263): compress
a plan over the server's plan compression threshold, as PySpark does.
- `crates/spark-connect-core/src/client.rs`: the client reads
`spark.connect.session.planCompression.threshold` and
`spark.connect.session.planCompression.defaultAlgorithm` with one `Config` Get
on its first plan, and keeps the result for the client (clones share it; a new
session starts fresh). A failed lookup, a missing, empty or invalid threshold,
or an algorithm other than `ZSTD` leaves plans uncompressed, as PySpark's
`_get_plan_compression_threshold_and_algorithm` does.
- A relation (`Plan.root`) or a command (`Plan.command`) whose serialized
size is over the threshold is replaced by a `Plan.compressed_operation` (zstd,
level 3, op type `OP_TYPE_RELATION` or `OP_TYPE_COMMAND`) when that makes it
smaller, as PySpark's `_try_compress_and_set_plan`.
- The compression is applied in `execute_plan` and
`execute_plan_reattachable` (before the execute hooks, as PySpark builds the
plan before its hooks) and in `analyze_plan` for the analyses that carry a
plan: schema, explain, tree string, is local, is streaming, input files, same
semantics and semantic hash. Persist, unpersist and storage level carry
relations in PySpark and are not compressed.
- A `CONNECT_INVALID_PLAN.CANNOT_PARSE` error disables compression for the
client, as PySpark's `_handle_rpc_error` does.
- `crates/spark-connect-core/Cargo.toml`: adds `zstd = "0.13"` (already in
the lock file at 0.13.3 through arrow and polars).
- Raw passthrough paths (`execute_plan_raw`, `analyze_plan_raw`) are
unchanged: their bytes are built by the caller, which compresses them itself.
### Why are the changes needed?
The Rust client never compressed plans. A plan whose encoding is over the
server's plan compression threshold (10 MB on OSS Spark 4.3.0, zstd) is sent by
PySpark as `Plan.compressed_operation`; the Rust client sent it uncompressed.
Uncompressed, a plan over the 128 MB gRPC message limit fails on the wire with
`[Internal error] h2 protocol error: http2 error`, and a plan between the
threshold and that limit goes over the wire uncompressed.
On a default OSS Spark 4.3.0 server, the decompressed plan is also limited,
by `spark.connect.grpc.maxInboundMessageSize` (128 MiB). So a 150 MiB literal
fails for both clients even with compression: the server rejects the
decompressed plan and returns a message header that declares 157286618 bytes.
The reference client reports this as `RESOURCE_EXHAUSTED` ("Received message
larger than max"), and the Rust client reports it as `decoded message length
too large` (tonic's own check of t [...]
With this change the Rust client sends the plan as PySpark does: the
request for the 150 MiB literal is about 5.7 KB on the wire (the reference
client's is about 6.5 KB), where before it was over 150 MB and failed in the
transport. The remaining failure at 150 MiB is the server's limit on the
decompressed plan, the same for both clients.
### Does this PR introduce _any_ user-facing change?
Yes, in behavior only, with no API change: plans over the server's plan
compression threshold are now sent compressed, as PySpark sends them, so they
take less of the network, and a plan whose encoding is over 128 MB fails with
the server's error about its decompressed size, as in PySpark, instead of a
transport error. The client makes one extra `Config` call per session, on its
first plan, as PySpark does.
### How was this patch tested?
- Rust unit tests in `client.rs` (`plan_compression_tests`): the threshold
parsing for the valid and the disabled confs; a relation and a command over the
threshold are sent as zstd operations that decode back to the original bytes;
the threshold boundary (a plan of exactly the threshold is sent as it is); a
payload that zstd does not shrink is sent as it is; the plan-bearing analyses.
`cargo test -p apache-spark-connect-core --release --lib plan_compression`: 5
passed.
- Offline Python tests in `python/tests/test_dropin_offline.py` against the
mock server: an over-threshold relation is sent as a zstd operation whose
decompressed relation has the same fields as the uncompressed one; the
threshold boundary at the size of the plan and one byte under; the threshold is
read once per session; an absent threshold value disables compression; a
`CANNOT_PARSE` error disables it for the session; an over-threshold schema
analysis is compressed.
- The mock does not record the plan-compression lookup
(`_mock_connect_server.py`), so the existing assertions about other requests
are unchanged.
- Live, against an OSS Spark 4.3.0 Connect server on
`sc://localhost:15002`: a 100 MiB and a 120 MiB literal return their lengths
(104857600 and 125829120) from both the reference client and the drop-in. A 150
MiB literal fails on both clients at the server's decompressed-plan limit, as
described above, so no e2e test of that size is added.
- The lib tests of both crates (528 and 155 passed), the build of all
tests, also with `wasm-udf`, `cargo fmt --all --check`, the offline Python
suites (2933 passed, 8 skipped), and the live drop-in, Arrow and ML suites
against a local Spark 4.3.0 server (236 passed, 1 skipped). 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 and Claude Haiku 5.5
This pull request and its description were written by Isaac.
Closes #445 from tdcmeehan/SPARK-61263-plan-compression.
Lead-authored-by: Timothy Meehan <[email protected]>
Co-authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
Cargo.lock | 1 +
crates/spark-connect-core/Cargo.toml | 1 +
crates/spark-connect-core/src/client.rs | 289 +++++++++++++++++++++++++++++++-
python/tests/_mock_connect_server.py | 24 ++-
python/tests/integer_tuple_cases.py | 5 +-
python/tests/test_arrow_handoff.py | 12 ++
python/tests/test_dropin_offline.py | 127 ++++++++++++++
7 files changed, 444 insertions(+), 15 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index acc805f0..1a0fdbe3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -101,6 +101,7 @@ dependencies = [
"tonic-prost",
"tracing",
"uuid",
+ "zstd",
]
[[package]]
diff --git a/crates/spark-connect-core/Cargo.toml
b/crates/spark-connect-core/Cargo.toml
index 717d6f07..99bdfd7c 100644
--- a/crates/spark-connect-core/Cargo.toml
+++ b/crates/spark-connect-core/Cargo.toml
@@ -26,6 +26,7 @@ tracing.workspace = true
serde = "1"
serde_json = "1"
regex = "1"
+zstd = "0.13"
prost-types.workspace = true
crc32fast = "1"
sha2 = "0.10"
diff --git a/crates/spark-connect-core/src/client.rs
b/crates/spark-connect-core/src/client.rs
index 1509315e..a83af0a7 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -10,13 +10,16 @@ use tonic::transport::{Channel, ClientTlsConfig};
use tonic::{Request, Response, Streaming};
use uuid::Uuid;
+use prost::Message;
+use spark_connect_proto::plan::compressed_operation::OpType as
CompressedOpType;
+use spark_connect_proto::plan::{CompressedOperation, OpType as PlanOpType};
use
spark_connect_proto::spark_connect_service_client::SparkConnectServiceClient;
use spark_connect_proto::{
- AnalyzePlanRequest, AnalyzePlanResponse, ArtifactStatusesRequest,
CloneSessionRequest,
- ConfigRequest, ConfigResponse, ExecutePlanRequest, ExecutePlanResponse,
- FetchErrorDetailsRequest, FetchErrorDetailsResponse, InterruptRequest,
InterruptResponse,
- ReattachExecuteRequest, ReleaseExecuteRequest, ReleaseExecuteResponse,
ReleaseSessionRequest,
- UserContext,
+ analyze_plan_request::Analyze, AnalyzePlanRequest, AnalyzePlanResponse,
+ ArtifactStatusesRequest, CloneSessionRequest, CompressionCodec,
ConfigRequest, ConfigResponse,
+ ExecutePlanRequest, ExecutePlanResponse, FetchErrorDetailsRequest,
FetchErrorDetailsResponse,
+ InterruptRequest, InterruptResponse, Plan, ReattachExecuteRequest,
ReleaseExecuteRequest,
+ ReleaseExecuteResponse, ReleaseSessionRequest, UserContext,
};
use crate::artifact::{
@@ -252,6 +255,79 @@ fn retry_exception_bound_passed(
.is_some_and(|ms| since.elapsed() >= Duration::from_millis(ms))
}
+const PLAN_COMPRESSION_THRESHOLD_CONF: &str =
"spark.connect.session.planCompression.threshold";
+const PLAN_COMPRESSION_ALGORITHM_CONF: &str =
+ "spark.connect.session.planCompression.defaultAlgorithm";
+
+/// How a client compresses its plans, as PySpark's client has it from the
confs of the server.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+enum PlanCompression {
+ /// Not looked up yet.
+ #[default]
+ Unknown,
+ /// The plans are sent as they are.
+ Disabled,
+ /// The plans of more than `threshold` bytes are sent zstd-compressed.
+ Zstd { threshold: usize },
+}
+
+/// The plan compression of the confs of the server, as PySpark reads them:
zstd above a threshold
+/// that is not negative. Any other algorithm, or a missing or invalid
threshold, disables it.
+fn plan_compression_of(threshold: Option<&str>, algorithm: Option<&str>) ->
PlanCompression {
+ let threshold = threshold
+ .filter(|threshold| !threshold.is_empty())
+ .and_then(|threshold| threshold.parse::<usize>().ok());
+ match (threshold, algorithm) {
+ (Some(threshold), Some("ZSTD")) => PlanCompression::Zstd { threshold },
+ _ => PlanCompression::Disabled,
+ }
+}
+
+/// 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()),
+ _ => return,
+ };
+ if message.len() <= threshold {
+ return;
+ }
+ let Ok(data) = zstd::encode_all(message.as_slice(),
zstd::DEFAULT_COMPRESSION_LEVEL) else {
+ return;
+ };
+ if data.len() >= message.len() {
+ return;
+ }
+ plan.op_type = Some(PlanOpType::CompressedOperation(CompressedOperation {
+ data: data.into(),
+ op_type: op_type as i32,
+ compression_codec: CompressionCodec::Zstd as i32,
+ }));
+}
+
+/// The plans of an analysis, which PySpark builds with its plan compression.
The plans of
+/// the other analyses, as the relations of persist, are not compressed.
+fn analyze_plans(analyze: &mut Analyze) -> Vec<&mut Option<Plan>> {
+ match analyze {
+ Analyze::Schema(request) => vec![&mut request.plan],
+ Analyze::Explain(request) => vec![&mut request.plan],
+ Analyze::TreeString(request) => vec![&mut request.plan],
+ Analyze::IsLocal(request) => vec![&mut request.plan],
+ Analyze::IsStreaming(request) => vec![&mut request.plan],
+ Analyze::InputFiles(request) => vec![&mut request.plan],
+ Analyze::SemanticHash(request) => vec![&mut request.plan],
+ Analyze::SameSemantics(request) => vec![&mut request.target_plan, &mut
request.other_plan],
+ Analyze::SparkVersion(_)
+ | Analyze::DdlParse(_)
+ | Analyze::Persist(_)
+ | Analyze::Unpersist(_)
+ | Analyze::GetStorageLevel(_)
+ | Analyze::JsonToDdl(_) => Vec::new(),
+ }
+}
+
/// A hook of the executions of a client, as PySpark's
`SparkSession.Hook.on_execute_plan`: it is
/// called with each `ExecutePlanRequest` before the client sends it, and
returns the request to
/// send, which keeps the operation ID of the original.
@@ -312,6 +388,8 @@ pub struct SparkConnectClient {
/// check of the IDs of its responses, and its close when the server
reports that the session
/// changed. See [`SparkConnectClient::set_session_tracking`].
session_tracking: bool,
+ /// The plan compression of the client, shared by its clones, looked up on
its first plan.
+ plan_compression: std::sync::Arc<std::sync::Mutex<PlanCompression>>,
}
/// The user context extensions of a client, as PySpark's `SparkConnectClient`
keeps them: those
@@ -433,6 +511,7 @@ impl SparkConnectClient {
closed: Default::default(),
server_session_id: Default::default(),
session_tracking: true,
+ plan_compression: Default::default(),
})
}
@@ -462,6 +541,7 @@ impl SparkConnectClient {
closed: Default::default(),
server_session_id: Default::default(),
session_tracking: self.session_tracking,
+ plan_compression: Default::default(),
}
}
@@ -562,14 +642,20 @@ impl SparkConnectClient {
}
/// A gRPC failure as a [`SparkError`], which closes the client when the
server reports that
- /// the session changed, as PySpark's `_handle_rpc_error` does.
+ /// the session changed, and disables its plan compression when the server
cannot parse a
+ /// plan, as PySpark's `_handle_rpc_error` does.
fn grpc_error(&self, status: tonic::Status) -> SparkError {
let error = SparkError::from_grpc_status(status);
- if self.session_tracking
- && error.get_condition().as_deref() ==
Some("INVALID_HANDLE.SESSION_CHANGED")
- {
+ let condition = error.get_condition();
+ if self.session_tracking && condition.as_deref() ==
Some("INVALID_HANDLE.SESSION_CHANGED") {
self.close();
}
+ if condition.as_deref() == Some("CONNECT_INVALID_PLAN.CANNOT_PARSE") {
+ *self
+ .plan_compression
+ .lock()
+ .unwrap_or_else(|e| e.into_inner()) =
PlanCompression::Disabled;
+ }
error
}
@@ -780,6 +866,46 @@ impl SparkConnectClient {
&self.rpc_deadlines
}
+ /// The plan compression of this client. The server's confs are read on
the first plan, with
+ /// one `Config` call, and kept for the client; a failed read disables the
compression for it,
+ /// as PySpark's `_get_plan_compression_threshold_and_algorithm` does.
+ async fn plan_compression(&self) -> PlanCompression {
+ let known = *self
+ .plan_compression
+ .lock()
+ .unwrap_or_else(|e| e.into_inner());
+ if known != PlanCompression::Unknown {
+ return known;
+ }
+ let looked_up = match self
+ .get_configs(&[
+ PLAN_COMPRESSION_THRESHOLD_CONF,
+ PLAN_COMPRESSION_ALGORITHM_CONF,
+ ])
+ .await
+ {
+ Ok(values) => match values.as_slice() {
+ [threshold, algorithm] => {
+ plan_compression_of(threshold.as_deref(),
algorithm.as_deref())
+ }
+ _ => PlanCompression::Disabled,
+ },
+ Err(_) => PlanCompression::Disabled,
+ };
+ *self
+ .plan_compression
+ .lock()
+ .unwrap_or_else(|e| e.into_inner()) = looked_up;
+ looked_up
+ }
+
+ /// Compress `plan` as the plan compression of this client asks.
+ async fn compress_plan(&self, plan: &mut Plan) {
+ if let PlanCompression::Zstd { threshold } =
self.plan_compression().await {
+ compress_over_threshold(plan, threshold);
+ }
+ }
+
/// Execute a plan and return a stream of responses.
///
/// Mirrors
`pyspark.sql.connect.client.core.SparkConnectClient.execute_plan`.
@@ -792,6 +918,9 @@ impl SparkConnectClient {
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);
+ if let Some(plan) = request.plan.as_mut() {
+ self.compress_plan(plan).await;
+ }
let request = self.hooked(request)?;
let mut req = Request::new(request);
self._attach_metadata(&mut req);
@@ -921,6 +1050,11 @@ impl SparkConnectClient {
self.ensure_open()?;
self.extend_user_context(&mut request.user_context);
self.fill_user_context(&mut request.user_context);
+ if let Some(analyze) = request.analyze.as_mut() {
+ for plan in analyze_plans(analyze).into_iter().flatten() {
+ self.compress_plan(plan).await;
+ }
+ }
let response = self
.with_retry(|| {
let deadline = self.rpc_deadlines.analyze_plan;
@@ -989,6 +1123,9 @@ impl SparkConnectClient {
// 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);
+ if let Some(plan) = request.plan.as_mut() {
+ self.compress_plan(plan).await;
+ }
let request = self.hooked(request)?;
let iter = ExecutePlanResponseReattachableIterator::new(request);
let start = iter.request().clone();
@@ -2848,3 +2985,137 @@ mod tests {
assert_eq!(other.observed_server_session_id(), None);
}
}
+
+#[cfg(test)]
+mod plan_compression_tests {
+ use super::*;
+ use spark_connect_proto::analyze_plan_request::{SameSemantics, Schema,
SparkVersion};
+ use spark_connect_proto::command::CommandType;
+ use spark_connect_proto::relation::RelType;
+ use spark_connect_proto::{Command, LocalRelation, Relation};
+
+ const PAYLOAD: usize = 64 * 1024;
+
+ fn relation_with(data: Vec<u8>) -> Relation {
+ Relation {
+ rel_type: Some(RelType::LocalRelation(LocalRelation {
+ data: Some(data.into()),
+ ..Default::default()
+ })),
+ ..Default::default()
+ }
+ }
+
+ fn root(relation: &Relation) -> Plan {
+ Plan {
+ op_type: Some(PlanOpType::Root(relation.clone())),
+ }
+ }
+
+ /// Bytes of a xorshift sequence, which zstd does not compress.
+ fn incompressible(len: usize) -> Vec<u8> {
+ let mut state = 0x2545_f491_4f6c_dd1du64;
+ (0..len)
+ .map(|_| {
+ state ^= state << 13;
+ state ^= state >> 7;
+ state ^= state << 17;
+ state as u8
+ })
+ .collect()
+ }
+
+ #[test]
+ fn plan_compression_is_zstd_above_the_threshold_of_the_confs() {
+ assert_eq!(
+ plan_compression_of(Some("10485760"), Some("ZSTD")),
+ PlanCompression::Zstd {
+ threshold: 10485760
+ }
+ );
+ assert_eq!(
+ plan_compression_of(Some("0"), Some("ZSTD")),
+ PlanCompression::Zstd { threshold: 0 }
+ );
+ for (threshold, algorithm) in [
+ (Some("-1"), Some("ZSTD")),
+ (None, Some("ZSTD")),
+ (Some(""), Some("ZSTD")),
+ (Some("ten"), Some("ZSTD")),
+ (Some("10"), Some("NONE")),
+ (Some("10"), Some("LZ4")),
+ (Some("10"), None),
+ ] {
+ assert_eq!(
+ plan_compression_of(threshold, algorithm),
+ PlanCompression::Disabled,
+ "threshold {threshold:?}, algorithm {algorithm:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn a_relation_over_the_threshold_is_sent_as_a_zstd_relation_operation() {
+ let relation = relation_with(vec![7; PAYLOAD]);
+ let encoded = relation.encode_to_vec();
+ let mut plan = root(&relation);
+ compress_over_threshold(&mut plan, encoded.len() - 1);
+ let Some(PlanOpType::CompressedOperation(operation)) = plan.op_type
else {
+ panic!("the plan over the threshold was not compressed");
+ };
+ assert_eq!(operation.op_type, CompressedOpType::Relation as i32);
+ assert_eq!(operation.compression_codec, CompressionCodec::Zstd as i32);
+ assert_eq!(zstd::decode_all(&operation.data[..]).unwrap(), encoded);
+ }
+
+ #[test]
+ fn a_command_over_the_threshold_is_sent_as_a_zstd_command_operation() {
+ let command = Command {
+ command_type: Some(CommandType::Extension(prost_types::Any {
+ type_url: "example.org/command".into(),
+ value: vec![7; PAYLOAD],
+ })),
+ };
+ let encoded = command.encode_to_vec();
+ let mut plan = Plan {
+ op_type: Some(PlanOpType::Command(command)),
+ };
+ compress_over_threshold(&mut plan, encoded.len() / 2);
+ let Some(PlanOpType::CompressedOperation(operation)) = plan.op_type
else {
+ panic!("the command over the threshold was not compressed");
+ };
+ assert_eq!(operation.op_type, CompressedOpType::Command as i32);
+ assert_eq!(zstd::decode_all(&operation.data[..]).unwrap(), encoded);
+ }
+
+ #[test]
+ fn
a_plan_is_sent_as_it_is_unless_it_is_over_the_threshold_and_compression_shrinks_it()
{
+ let relation = relation_with(vec![7; PAYLOAD]);
+ let size = relation.encode_to_vec().len();
+ let mut at_threshold = root(&relation);
+ compress_over_threshold(&mut at_threshold, size);
+ assert_eq!(at_threshold, root(&relation));
+
+ let random = relation_with(incompressible(PAYLOAD));
+ let mut not_smaller = root(&random);
+ compress_over_threshold(&mut not_smaller, 0);
+ assert_eq!(not_smaller, root(&random));
+ }
+
+ #[test]
+ fn the_plans_of_an_analysis_are_those_pyspark_compresses() {
+ let relation = relation_with(vec![7; 1]);
+ let mut schema = Analyze::Schema(Schema {
+ plan: Some(root(&relation)),
+ });
+ assert_eq!(analyze_plans(&mut schema).len(), 1);
+
+ let mut same_semantics = Analyze::SameSemantics(SameSemantics {
+ target_plan: Some(root(&relation)),
+ other_plan: Some(root(&relation)),
+ });
+ assert_eq!(analyze_plans(&mut same_semantics).len(), 2);
+
+ assert!(analyze_plans(&mut Analyze::SparkVersion(SparkVersion
{})).is_empty());
+ }
+}
diff --git a/python/tests/_mock_connect_server.py
b/python/tests/_mock_connect_server.py
index 4742b15b..f4cc8da2 100644
--- a/python/tests/_mock_connect_server.py
+++ b/python/tests/_mock_connect_server.py
@@ -27,6 +27,10 @@ from threading import Condition, Event
# The drop-in package does not ship generated service protobuf classes, so
these
# encoders provide just the messages needed by this test server.
+# The key that a client reads on its first plan, to compress the plans of the
session.
+PLAN_COMPRESSION_LOOKUP = b"spark.connect.session.planCompression.threshold"
+
+
def varint(value):
result = bytearray()
while value > 127:
@@ -292,6 +296,7 @@ def serve(connection):
self.confs = {}
self.read_confs = []
self.config_requests = []
+ self.plan_compression_lookups = 0
self.config_failure = None
self.block_config = False
self.rpc_events = []
@@ -424,6 +429,7 @@ def serve(connection):
}
read_confs = []
config_requests = []
+ plan_compression_lookups = 0
config_failure = None
block_config = False
rpc_events = []
@@ -653,14 +659,21 @@ def serve(connection):
def config(self, request, context):
# ConfigRequest.session_id=1, operation=3, Operation.get=2,
Get.keys=1;
# ConfigResponse.session_id=1, pairs=2, KeyValue.key=1, value=2.
- self.config_requests.append(request)
- self.rpc_events.append("config")
- if self.block_config and not self.response_gate.wait(5):
+ # The plan compression lookup of a client, which PySpark makes on
its first plan, is
+ # not recorded, blocked or failed, so that the tests of the other
requests count,
+ # block and fail only their own.
+ lookup = PLAN_COMPRESSION_LOOKUP in request
+ if lookup:
+ self.plan_compression_lookups += 1
+ if not lookup:
+ self.config_requests.append(request)
+ self.rpc_events.append("config")
+ if not lookup and self.block_config and not
self.response_gate.wait(5):
context.abort(
grpc.StatusCode.DEADLINE_EXCEEDED,
"Python thread could not run while configuration lookup
waited",
)
- if self.config_failure:
+ if not lookup and self.config_failure:
context.abort(grpc.StatusCode.INVALID_ARGUMENT,
self.config_failure)
request = parse_message(request)
operation = parse_message(request[3][0])
@@ -704,7 +717,8 @@ def serve(connection):
"only Get, GetWithDefault, Set and Unset are served",
)
keys = [key.decode() for key in
parse_message(operation[2][0]).get(1, [])]
- self.read_confs.extend(keys)
+ if not lookup:
+ self.read_confs.extend(keys)
confs = {**self.default_confs, **self.confs}
if any(key not in confs for key in keys):
context.abort(grpc.StatusCode.INTERNAL, "[SQL_CONF_NOT_FOUND]")
diff --git a/python/tests/integer_tuple_cases.py
b/python/tests/integer_tuple_cases.py
index aa4fce94..4936da82 100644
--- a/python/tests/integer_tuple_cases.py
+++ b/python/tests/integer_tuple_cases.py
@@ -90,8 +90,11 @@ class IntegerTupleTests(unittest.TestCase):
+ _bytes(14, b""))
def config(raw, context):
- self.config_calls += 1
request = _fields(raw)
+ if b"spark.connect.session.planCompression.threshold" in raw:
+ # The plan compression lookup, which is not counted: it has no
value here.
+ return _bytes(1, request[1][0]) + _bytes(4,
b"input-name-fixture")
+ self.config_calls += 1
operation = _fields(request[3][0])
if 2 in operation: # ConfigRequest.Get.keys(1).
keys = _fields(operation[2][0])[1]
diff --git a/python/tests/test_arrow_handoff.py
b/python/tests/test_arrow_handoff.py
index 56eca9c6..af89b6b6 100644
--- a/python/tests/test_arrow_handoff.py
+++ b/python/tests/test_arrow_handoff.py
@@ -88,6 +88,12 @@ def
test_missing_protoc_fails_in_ci_and_skips_locally(monkeypatch, tmp_path_fact
protocol.__wrapped__(tmp_path_factory)
+# The plan compression lookup that a client makes on its first plan. The fake
servers answer
+# it with no value, so plans are not compressed, and do not count it, so the
tests count only
+# their own Config requests.
+_PLAN_COMPRESSION_THRESHOLD =
b"spark.connect.session.planCompression.threshold"
+
+
@contextmanager
def _dataframe(batches, *, protocol, payloads=None, calls=None):
"""Serve Arrow results using the repository's protobuf message
definitions."""
@@ -130,6 +136,10 @@ def _dataframe(batches, *, protocol, payloads=None,
calls=None):
).SerializeToString()
def config(request, context):
+ if _PLAN_COMPRESSION_THRESHOLD in request:
+ return protocol("ConfigResponse",
+
session_id=protocol("ConfigRequest").FromString(request).session_id,
+
server_side_session_id=server_id).SerializeToString()
# The settings that toPandas reads first, and the defaults that row
collection reads.
if calls is not None:
calls["config"] = calls.get("config", 0) + 1
@@ -599,6 +609,8 @@ def _arrow_input_service(
def configure(raw, context):
request = protocol("ConfigRequest").FromString(raw)
+ if _PLAN_COMPRESSION_THRESHOLD in raw:
+ return protocol("ConfigResponse",
session_id=request.session_id).SerializeToString()
operation = request.operation.WhichOneof("op_type")
defaults = None
if operation == "get_with_default":
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index a27fed72..df934c0b 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -7,6 +7,7 @@ that require a live server live in test_dropin_e2e.py and are
gated on SPARK_REM
"""
import array
+import io
import contextlib
import datetime
import os
@@ -15170,7 +15171,10 @@ def _repr_serve(connection):
def config(self, request, context):
# ConfigRequest.session_id=1, operation=3, Operation.get=2,
Get.keys=1;
# ConfigResponse.session_id=1, pairs=2, KeyValue.key=1, value=2.
+ request_bytes = request
request = parse_message(request)
+ if b"spark.connect.session.planCompression.threshold" in
request_bytes:
+ return _repr_message(1, request[1][0])
keys = [key.decode() for key in
parse_message(parse_message(request[3][0])[2][0]).get(1,
[])]
self.config_keys = self.config_keys + [keys]
@@ -18203,3 +18207,126 @@ def
test_functions_send_their_optional_arguments_as_pyspark(column, expected):
from pyspark.sql import functions as F
assert repr(column(F)) == f"Column<'{expected}'>"
+
+
+# ---------------------------------------------------------------------------
plan compression
+
+PLAN_COMPRESSION_THRESHOLD = "spark.connect.session.planCompression.threshold"
+PLAN_COMPRESSION_ALGORITHM =
"spark.connect.session.planCompression.defaultAlgorithm"
+
+
+def _plan_confs(threshold):
+ return {PLAN_COMPRESSION_THRESHOLD: threshold, PLAN_COMPRESSION_ALGORITHM:
"ZSTD"}
+
+
+def _sent_plan(requests):
+ # ExecutePlanRequest.plan=3; Plan.root=1, or Plan.compressed_operation=3
whose data=1,
+ # op_type=2 (OP_TYPE_RELATION=1) and compression_codec=3
(COMPRESSION_CODEC_ZSTD=1).
+ return parse_message(parse_message(requests[-1])[3][0])
+
+
+def _collect_in_new_session(service, confs, make_df):
+ # The plan compression of a session is read once, so each threshold gets a
session of its own.
+ from pyspark.sql import SparkSession
+
+ service.confs = confs
+ spark = SparkSession.builder.remote(service.remote).create()
+ try:
+ make_df(spark).collect()
+ finally:
+ spark.stop()
+ return _sent_plan(service.execute_requests)
+
+
+def _long_literal_frame(spark):
+ from pyspark.sql import functions as F
+
+ return spark.range(1).select(F.length(F.lit("x" * 4096)))
+
+
+def
test_plans_over_the_server_threshold_are_sent_as_zstd_relations(mock_connect):
+ zstandard = pytest.importorskip("zstandard")
+
+ spark, service = mock_connect
+ service.confs = _plan_confs("1024")
+ _long_literal_frame(spark).collect()
+ plan = _sent_plan(service.execute_requests)
+ assert 1 not in plan
+ operation = parse_message(plan[3][0])
+ assert operation[2] == [1]
+ assert operation[3] == [1]
+ assert len(operation[1][0]) < 4096
+
+ # The same plan, sent uncompressed by a session whose threshold is above
its size.
+ root = _collect_in_new_session(
+ service,
+ _plan_confs(str(1 << 30)),
+ _long_literal_frame,
+ )[1][0]
+ # The plan IDs of two DataFrames differ, so the relations are compared by
their fields.
+ reader =
zstandard.ZstdDecompressor().stream_reader(io.BytesIO(operation[1][0]))
+ relation = reader.read()
+ assert b"x" * 4096 in relation and len(relation) == len(root)
+ assert parse_message(relation).keys() == parse_message(root).keys()
+
+
+def test_plans_at_the_server_threshold_are_sent_as_they_are(mock_connect):
+ spark, service = mock_connect
+ size = len(_collect_in_new_session(
+ service, _plan_confs(str(1 << 30)), _long_literal_frame)[1][0])
+ at_threshold = _collect_in_new_session(
+ service, _plan_confs(str(size)), _long_literal_frame)
+ assert 3 not in at_threshold and len(at_threshold[1][0]) == size
+ over_threshold = _collect_in_new_session(
+ service, _plan_confs(str(size - 1)), _long_literal_frame)
+ assert 1 not in over_threshold and 3 in over_threshold
+
+
+def test_plan_compression_is_read_once_per_session(mock_connect):
+ spark, service = mock_connect
+ service.confs = _plan_confs("1024")
+ frame = _long_literal_frame(spark)
+ frame.collect()
+ frame.collect()
+ assert service.plan_compression_lookups == 1
+
+
+def
test_plan_compression_is_disabled_for_a_session_whose_server_gives_no_threshold(mock_connect):
+ spark, service = mock_connect
+ plan = _collect_in_new_session(
+ service,
+ _plan_confs(None),
+ _long_literal_frame,
+ )
+ assert 3 not in plan and 1 in plan
+
+
+def
test_a_cannot_parse_error_disables_the_plan_compression_of_the_session(mock_connect):
+ from pyspark.errors.exceptions import connect as C
+
+ spark, service = mock_connect
+ service.confs = _plan_confs("1024")
+ frame = _long_literal_frame(spark)
+ classes = ["org.apache.spark.sql.connect.common.InvalidPlanInput",
"java.lang.Exception"]
+ service.execute_error = (
+ "[CONNECT_INVALID_PLAN.CANNOT_PARSE] The plan cannot be parsed.",
+ classes[0],
+ _error_info(classes, errorClass="CONNECT_INVALID_PLAN.CANNOT_PARSE"),
+ )
+ with pytest.raises(C.SparkConnectGrpcException):
+ frame.collect()
+ assert 3 in _sent_plan(service.execute_requests)
+
+ service.execute_error = None
+ frame.collect()
+ assert 3 not in _sent_plan(service.execute_requests)
+
+
+def
test_schemas_of_plans_over_the_server_threshold_are_sent_compressed(mock_connect):
+ spark, service = mock_connect
+ service.confs = _plan_confs("1024")
+ _long_literal_frame(spark).schema
+ # AnalyzePlanRequest.schema=4, Schema.plan=1, compressed_operation=3 as
above.
+ plan =
parse_message(parse_message(service.analyze_requests[-1])[4][0])[1][0]
+ assert 1 not in parse_message(plan)
+ assert parse_message(parse_message(plan)[3][0])[3] == [1]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]