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 2f83537f [SPARK-61400][CONNECT] Clone the request of a deep plan on a
grown stack, so that a deep plan or expression does not crash a thread with a
small stack, in Spark Connect Rust
2f83537f is described below
commit 2f83537fae857e54eda8872b95e5620b6a151cca
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 06:17:54 2026 +0900
[SPARK-61400][CONNECT] Clone the request of a deep plan on a grown stack,
so that a deep plan or expression does not crash a thread with a small stack,
in Spark Connect Rust
### What changes were proposed in this pull request?
[SPARK-61400](https://issues.apache.org/jira/browse/SPARK-61400): a
follow-up of #451 (SPARK-61260), #456 (SPARK-61328) and #458 (SPARK-61332),
from a review of them.
- The analyze and reattachable execute paths clone the request on the
calling thread, once per attempt (`crates/spark-connect-core/src/client.rs`).
The clone now runs on a stack grown for its levels, with a new
`clone_on_grown_stack` helper (stacker, 4 MiB in release builds and 16 MiB in
debug builds). It is used at `analyze_plan`'s per-attempt clone,
`execute_plan_reattachable`'s per-attempt clone (taken from `iter.request()`,
so the extra `start` copy is gone) and `open_execute_plan [...]
- The comments that gave PySpark's `RecursionError` point as a fixed number
(`MAX_PLAN_DEPTH` in `plan.rs`, `MAX_EXPRESSION_DEPTH` in `expression.rs`,
`MAX_LIST_DEPTH` in pyspark-rs `functions.rs`, and the matching test comments)
now say what the bound protects in this client and that PySpark's point depends
on its protobuf backend. With pyspark-client 4.3.0, a chain of filters raises
from about 245 levels with the pure-Python protobuf and about 992 levels with
upb. The bounds are unchanged.
The drop, `encode` and `encoded_len` of a request at the bound stay on the
calling thread: measured in a release build, a 746-level relation proto takes
them on a 64 KiB stack. Only the derived `Clone` recursed deeply.
### Why are the changes needed?
prost's derived `Clone` recurses once per level, about 2 KiB of stack per
level in a release build. The stack guard of #451, #456 and #458 covers the
serialization, `Expression::to_proto`, render and drop, but not the clone. So a
Python thread with a small stack crashed the process with SIGBUS (lldb:
`Relation::clone`/`Box<Relation>::clone`) on a plan that the bound lets
through, although #451 says "Plans up to 256 levels are sent as before, also
from threads with small stacks":
```python
import threading
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.remote("sc://localhost:15002").getOrCreate()
def work():
df = spark.range(10)
for x in range(255):
df = df.withColumn(f"col{x}", F.lit(x))
df.schema
threading.stack_size(512 * 1024)
t = threading.Thread(target=work)
t.start()
t.join()
# before: the process dies with SIGBUS; after: the schema is returned
```
An expression of 200 additions crashed the same way, in
`Expression::clone`. The existing small-stack tests never reached the clone.
### Does this PR introduce _any_ user-facing change?
A deep plan or expression sent from a thread with a small stack no longer
crashes the process. Plans and expressions are sent as before; only comments
change otherwise.
### How was this patch tested?
- Rust: `deep_request_stack_tests` in
`crates/spark-connect/src/dataframe.rs`, a 746-level plan (`schema` and
`collect`) and a 740-addition expression (`schema`) on a 512 KiB thread against
an unreachable endpoint without retries. Both abort with "thread has overflowed
its stack" without the change, and pass with it.
- Python:
`test_a_plan_of_256_levels_is_sent_from_a_thread_with_a_small_stack` and
`test_an_expression_of_200_additions_is_sent_from_a_thread_with_a_small_stack`
in `python/tests/test_dropin_offline.py`, which run the small-stack thread in a
subprocess against the mock server. Both die with SIGBUS without the change,
and pass with it.
- `cargo test -p apache-spark-connect -p apache-spark-connect-core
--release --lib` and the core integration tests, the `--no-run` builds, `cargo
fmt --check`, `scripts/audit_no_stubs.sh`, the full offline drop-in suite, and
the drop-in, Arrow and Rust e2e suites against a Spark 4.3.0 server (apart from
`from_ddl_interval_colon_and_spellings_agree_with_the_server_parser`, which
fails on master as well, as that server does not enable
`spark.sql.timestampNanosTypes.enabled`).
### 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 #494 from HyukjinKwon/SPARK-61400-deep-request-clone-stack.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
Cargo.lock | 1 +
crates/pyspark-rs/src/functions.rs | 9 ++--
crates/spark-connect-core/Cargo.toml | 2 +
crates/spark-connect-core/src/client.rs | 25 +++++++++--
crates/spark-connect/src/dataframe.rs | 78 +++++++++++++++++++++++++++++++++
crates/spark-connect/src/expression.rs | 12 ++---
crates/spark-connect/src/plan.rs | 16 ++++---
python/tests/test_dropin_e2e.py | 7 +--
python/tests/test_dropin_offline.py | 77 ++++++++++++++++++++++++++++++--
9 files changed, 201 insertions(+), 26 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index a79073d3..772b1ffc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -95,6 +95,7 @@ dependencies = [
"serde",
"serde_json",
"sha2",
+ "stacker",
"tempfile",
"thiserror",
"tokio",
diff --git a/crates/pyspark-rs/src/functions.rs
b/crates/pyspark-rs/src/functions.rs
index 82293333..95efccf7 100644
--- a/crates/pyspark-rs/src/functions.rs
+++ b/crates/pyspark-rs/src/functions.rs
@@ -360,10 +360,11 @@ pub(crate) fn to_value_column(obj: &Bound<'_, PyAny>) ->
PyResult<Column> {
to_column(obj)
}
-/// How deep the lists of a Column method may nest. PySpark's
`LiteralExpression` recurses in
-/// Python for each level, so under Python's default recursion limit it raises
`RecursionError`
-/// for a list nested about 990 levels deep (a little less below a deeper
caller). A deeper list
-/// is a `RecursionError` here too, rather than a native stack overflow.
+/// How deep the lists of a Column method may nest. It protects this client: a
deeper list is a
+/// `RecursionError` here, rather than a native stack overflow. PySpark's
`LiteralExpression`
+/// recurses in Python for each level, so where its `RecursionError` starts
depends on the Python
+/// recursion limit and on the protobuf backend, and this bound is not a copy
of its point (a
+/// little less below a deeper caller).
const MAX_LIST_DEPTH: usize = 988;
/// The stack that a level of nested lists keeps free before it goes down a
level, and the size of
diff --git a/crates/spark-connect-core/Cargo.toml
b/crates/spark-connect-core/Cargo.toml
index eee78bad..151ddc04 100644
--- a/crates/spark-connect-core/Cargo.toml
+++ b/crates/spark-connect-core/Cargo.toml
@@ -33,6 +33,8 @@ sha2 = "0.10"
# Transport errors that tonic keeps as a status's source, for
`RetryPolicy::can_retry`.
h2 = "0.4"
hyper = "1"
+# Grows the stack for the clones and drops of the requests of deep plans.
+stacker = "0.1"
[target.'cfg(all(target_arch = "aarch64", not(target_os =
"windows")))'.dependencies]
# sha2 0.10 requires this feature for ARM hardware acceleration; sha2-asm
excludes Windows.
diff --git a/crates/spark-connect-core/src/client.rs
b/crates/spark-connect-core/src/client.rs
index af08ea07..94040761 100644
--- a/crates/spark-connect-core/src/client.rs
+++ b/crates/spark-connect-core/src/client.rs
@@ -282,6 +282,22 @@ fn plan_compression_of(threshold: Option<&str>, algorithm:
Option<&str>) -> Plan
}
}
+/// The stack that a clone of a request takes for the levels of its plan:
prost's derived `Clone`
+/// recurses once per level, with about 2 KiB of stack per level in a release
build (more in a
+/// debug one), while encoding and dropping a plan take a fraction of that. A
plan of PySpark's
+/// serializer, at most 746 levels, must not overflow a thread of a small
stack, such as a Python
+/// thread of 512 KiB, that calls the client.
+const REQUEST_STACK: usize = if cfg!(debug_assertions) {
+ 16 << 20
+} else {
+ 4 << 20
+};
+
+/// Clone `value`, a request, on a stack that holds its levels (see
[`REQUEST_STACK`]).
+fn clone_on_grown_stack<T: Clone>(value: &T) -> T {
+ stacker::maybe_grow(REQUEST_STACK, REQUEST_STACK, || value.clone())
+}
+
/// 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) {
@@ -1290,7 +1306,7 @@ impl SparkConnectClient {
let response = self
.with_retry(|| {
let deadline = self.rpc_deadlines.analyze_plan;
- let mut request = request.clone();
+ let mut request = clone_on_grown_stack(&request);
self.observe_on(&mut
request.client_observed_server_side_session_id);
let mut req = with_deadline(Request::new(request), deadline);
self._attach_metadata(&mut req);
@@ -1389,14 +1405,14 @@ impl SparkConnectClient {
std::sync::Arc::clone(&self.inflight_operations),
iter.operation_id().to_string(),
);
- let start = iter.request().clone();
let deadline = self.rpc_deadlines.reattachable_execute_plan;
let mut stream_deadline = None;
let stream = {
// The first RPC is a wait of the caller for the execution.
let _waiting = inflight.waiting();
self.with_retry(|| {
- let mut req = with_deadline(Request::new(start.clone()),
deadline);
+ let request = clone_on_grown_stack(iter.request());
+ let mut req = with_deadline(Request::new(request), deadline);
self._attach_metadata(&mut req);
stream_deadline = deadline.map(|d| tokio::time::Instant::now()
+ d);
let mut stub = self.stub.clone();
@@ -2651,7 +2667,8 @@ impl ReattachableResponseStream {
&mut self,
) -> std::result::Result<Streaming<ExecutePlanResponse>, tonic::Status> {
let deadline = self.client.rpc_deadlines.reattachable_execute_plan;
- let mut req = with_deadline(Request::new(self.iter.request().clone()),
deadline);
+ let request = clone_on_grown_stack(self.iter.request());
+ let mut req = with_deadline(Request::new(request), deadline);
self.client._attach_metadata(&mut req);
self.stream_deadline = deadline.map(|d| tokio::time::Instant::now() +
d);
let response =
diff --git a/crates/spark-connect/src/dataframe.rs
b/crates/spark-connect/src/dataframe.rs
index c58e7e29..562823fe 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -6853,3 +6853,81 @@ mod subquery_tests {
);
}
}
+
+/// The requests of deep plans and expressions, sent from a thread with a
small stack. The clone of
+/// a request recurses once per level, as its serialization does, so the
client grows the stack for
+/// it. The client of a port that nothing listens to fails each call after its
request is built and
+/// cloned, so that a call returns an error without a server.
+#[cfg(test)]
+mod deep_request_stack_tests {
+ use super::*;
+ use crate::column::col;
+ use crate::expression::MAX_EXPRESSION_DEPTH;
+ use crate::plan::MAX_PLAN_DEPTH;
+ use crate::session::SparkSession;
+ use spark_connect_core::retries::RetryPolicy;
+ use spark_connect_core::{ChannelBuilder, SparkConnectClient};
+
+ fn unreachable_session() -> SparkSession {
+ let builder = ChannelBuilder::parse("sc://127.0.0.1:1").expect("valid
URL");
+ let mut client =
+ block_on(SparkConnectClient::connect(&builder)).expect("failed to
build client");
+ client.set_retry_policy(RetryPolicy::no_retries());
+ SparkSession::new(client)
+ }
+
+ /// Run `f` on a thread of 512 KiB, the smallest stack that a Python
thread may have, in a
+ /// release build, as the drop-in runs. The frames of a debug build, and
more so of a
+ /// coverage build, are several times larger, and the encode and drop of a
request at the
+ /// bound, which stay on the calling thread, take more than 512 KiB there,
so its thread has
+ /// the 8 MiB of a default thread of Linux.
+ fn on_a_small_stack<T: Send>(f: impl FnOnce() -> T + Send) -> T {
+ let stack = if cfg!(debug_assertions) {
+ 8 << 20
+ } else {
+ 512 << 10
+ };
+ std::thread::scope(|scope| {
+ std::thread::Builder::new()
+ .stack_size(stack)
+ .spawn_scoped(scope, f)
+ .unwrap()
+ .join()
+ .unwrap()
+ })
+ }
+
+ #[test]
+ fn a_plan_at_the_bound_is_sent_from_a_small_stack_without_overflowing_it()
{
+ let spark = unreachable_session();
+ let mut df = spark.range(1).unwrap();
+ for i in 1..MAX_PLAN_DEPTH {
+ df = df.with_column(&format!("c{i}"), col("id"));
+ }
+ assert_eq!(df.plan().depth(), MAX_PLAN_DEPTH);
+ let (schema, collect) = on_a_small_stack(move || (df.schema(),
df.collect()));
+ for error in [schema.unwrap_err(), collect.unwrap_err()] {
+ assert_ne!(
+ error.kind,
+ SparkErrorKind::RecursionError,
+ "a plan at the bound is sent: {error}"
+ );
+ }
+ }
+
+ #[test]
+ fn a_deep_expression_is_sent_from_a_small_stack_without_overflowing_it() {
+ let spark = unreachable_session();
+ let mut expr = col("id");
+ for _ in 0..MAX_EXPRESSION_DEPTH - 5 {
+ expr = expr.add(col("id"));
+ }
+ let df = spark.range(1).unwrap().select([expr.alias("x")]);
+ let schema = on_a_small_stack(move || df.schema()).unwrap_err();
+ assert_ne!(
+ schema.kind,
+ SparkErrorKind::RecursionError,
+ "an expression within the bound is sent: {schema}"
+ );
+ }
+}
diff --git a/crates/spark-connect/src/expression.rs
b/crates/spark-connect/src/expression.rs
index ed129136..f2504392 100644
--- a/crates/spark-connect/src/expression.rs
+++ b/crates/spark-connect/src/expression.rs
@@ -21,11 +21,13 @@ pub fn next_lambda_var_index() -> u32 {
LAMBDA_VAR_COUNTER.fetch_add(1, Ordering::SeqCst)
}
-/// The most levels of an expression that a plan of a request may carry.
PySpark builds the proto
-/// of an expression by recursing in Python, so under Python's default
recursion limit its
-/// serializer raises `RecursionError` for `select((col("id") + 1 + ... +
1).alias("x"))` from
-/// 744 additions, an expression of 746 levels with its alias and column, and
serializes 745; a
-/// deeper expression is a `RecursionError` here too (see
[`with_expression_depth_bound`]).
+/// The most levels of an expression that a plan of a request may carry. It
protects this client,
+/// as [`crate::plan::MAX_PLAN_DEPTH`] does for plans: a deeper expression is
a `RecursionError`
+/// here, before any request is built (see [`with_expression_depth_bound`]).
PySpark's own point is
+/// not this number, and depends on its protobuf backend: it builds the proto
of an expression by
+/// recursing in Python, so with the pure-Python backend its serializer raises
`RecursionError` from
+/// about 244 additions, as in `select((col("id") + 1 + ... + 1).alias("x"))`,
and with upb it
+/// raises a `DecodeError` from 48 additions in some paths (measured with
pyspark-client 4.3.0).
pub const MAX_EXPRESSION_DEPTH: usize = 745;
/// The stack that serializing or rendering an expression keeps free before it
goes down a level,
diff --git a/crates/spark-connect/src/plan.rs b/crates/spark-connect/src/plan.rs
index df0e4680..6478d9e4 100644
--- a/crates/spark-connect/src/plan.rs
+++ b/crates/spark-connect/src/plan.rs
@@ -805,13 +805,15 @@ pub fn resolve_request(request: &mut
proto::ExecutePlanRequest) -> Result<()> {
}
}
-/// How many levels deep a plan may be to be sent, with the plans of its
subqueries. PySpark
-/// builds the proto of a plan by recursing in Python, so under Python's
default recursion limit
-/// its serializer raises `RecursionError` from about 747 levels (from 746 for
a chain of filters,
-/// 747 of `withColumn`s or `select`s, and 748 of limits); a deeper plan fails
in the same way
-/// here, before any request is sent. The server itself rejects a plan of
about 510 levels or more
-/// (its marshaller nests at most 1024 messages), with an error that gives no
reason, so the plans
-/// between the two fail there, as they do for PySpark.
+/// How many levels deep a plan may be to be sent, with the plans of its
subqueries. It protects
+/// this client: the serialization of a plan, the clone of its request and the
encoding of the
+/// request recurse once per level, so a deeper plan is refused here with a
`RecursionError`,
+/// before any request is built, and the levels that are sent fit the stack
that the client grows
+/// for them. PySpark's own point is not this number, and depends on its
protobuf backend: its
+/// serializer recurses in Python, so it raises `RecursionError` from about
245 levels with the
+/// pure-Python backend, and from about 992 with upb (measured with
pyspark-client 4.3.0). The
+/// server itself rejects a plan of about 510 levels or more (its marshaller
nests at most 1024
+/// messages), with an error that gives no reason, so the plans between the
two fail there.
pub const MAX_PLAN_DEPTH: usize = 746;
/// The stack that the clone of a [`LogicalPlan::Raw`] relation takes for each
of its levels:
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index e585ac35..12fbdfc6 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -1329,9 +1329,10 @@ except RecursionError as error:
def test_plans_of_a_few_hundred_levels_are_sent_as_pyspark(session):
- # As PySpark, which serializes plans up to about 746 levels, and the
server runs them up to
- # about 510: Apache's test_recursion_handling_for_plan_logging builds 400
withColumns, and a
- # subquery of 300 levels under 33 more runs too. Both were a
RecursionError, or a crash.
+ # Plans of a few hundred levels are sent, which the client grows the stack
for, while the
+ # server runs them up to about 510: Apache's
test_recursion_handling_for_plan_logging builds
+ # 400 withColumns, and a subquery of 300 levels under 33 more runs too.
Both were a
+ # RecursionError, or a crash.
df = session.range(10)
for x in range(400):
df = df.withColumn(f"col{x}", F.lit(x))
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 433a9e04..0ddd4e49 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -10670,6 +10670,76 @@ def
test_a_plan_too_deep_to_send_raises_recursion_error_without_a_request(mock_c
assert service.analyze_requests == []
+def
test_a_plan_of_256_levels_is_sent_from_a_thread_with_a_small_stack(mock_connect):
+ # Each clone of a request recurses once per level of its plan, on the
thread that sends it:
+ # on a Python thread of 512 KiB, a plan of 256 levels overflowed the stack
(SIGBUS) in the
+ # clone. The thread runs in a subprocess, since the crash would end this
one.
+ import subprocess
+ import sys
+
+ _, service = mock_connect
+ script = """
+import threading
+from pyspark.sql import SparkSession, functions as F
+spark = SparkSession.builder.remote(REMOTE_URL).getOrCreate()
+
+def work():
+ df = spark.range(10)
+ for x in range(255):
+ df = df.withColumn(f"col{x}", F.lit(x))
+ df.schema
+ print("analyzed", flush=True)
+ df.collect()
+ print("collected", flush=True)
+
+threading.stack_size(512 * 1024)
+thread = threading.Thread(target=work)
+thread.start()
+thread.join()
+""".replace("REMOTE_URL", repr(service.remote))
+ result = subprocess.run(
+ [sys.executable, "-c", script], env=dict(os.environ, TZ="UTC"),
+ capture_output=True, text=True, timeout=300)
+ assert result.returncode == 0, result.stderr
+ assert "analyzed" in result.stdout, result.stdout
+ assert "collected" in result.stdout, result.stdout
+ assert len(service.analyze_requests) == 1
+ assert len(service.execute_requests) == 1
+
+
+def
test_an_expression_of_200_additions_is_sent_from_a_thread_with_a_small_stack(mock_connect):
+ # As the plan above, for an expression: its clone recurses once per level,
on a Python
+ # thread of 512 KiB, which overflowed the stack (SIGBUS). The thread runs
in a subprocess.
+ import subprocess
+ import sys
+
+ _, service = mock_connect
+ script = """
+import threading
+from pyspark.sql import SparkSession, functions as F
+spark = SparkSession.builder.remote(REMOTE_URL).getOrCreate()
+
+def work():
+ c = F.col("id")
+ for _ in range(200):
+ c = c + 1
+ df = spark.range(1).select(c.alias("x"))
+ df.schema
+ print("analyzed", flush=True)
+
+threading.stack_size(512 * 1024)
+thread = threading.Thread(target=work)
+thread.start()
+thread.join()
+""".replace("REMOTE_URL", repr(service.remote))
+ result = subprocess.run(
+ [sys.executable, "-c", script], env=dict(os.environ, TZ="UTC"),
+ capture_output=True, text=True, timeout=300)
+ assert result.returncode == 0, result.stderr
+ assert "analyzed" in result.stdout, result.stdout
+ assert len(service.analyze_requests) == 1
+
+
def
test_create_dataframe_raises_recursion_error_for_a_value_that_contains_itself():
class Node:
def __init__(self):
@@ -16092,9 +16162,10 @@ def test_column_reprs_as_pyspark(column, expected):
def
test_an_expression_too_deep_to_send_raises_recursion_error_without_a_request(mock_connect):
- # As PySpark, whose client raises RecursionError while it builds the proto
of an expression
- # from 744 additions under an alias, before any request, rather than
overflowing the native
- # stack (which killed the process from about 30,000 levels); 743 are sent.
+ # Past the bound of expressions, the client raises RecursionError while it
builds the proto
+ # of an expression of 744 additions under an alias, before any request,
rather than
+ # overflowing the native stack (which killed the process from about 30,000
levels); 743 are
+ # sent. PySpark's own point depends on its protobuf backend (see
MAX_EXPRESSION_DEPTH).
from pyspark.sql import functions as F
spark, service = mock_connect
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]