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 04127c4b [SPARK-61332][CONNECT][PYTHON] Send plans of up to 746 levels 
as PySpark does, and count the plans of subqueries for the depth bound without 
overflowing the stack
04127c4b is described below

commit 04127c4b3826dde306c7229befbb05a101b12350
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 16:50:33 2026 +0900

    [SPARK-61332][CONNECT][PYTHON] Send plans of up to 746 levels as PySpark 
does, and count the plans of subqueries for the depth bound without overflowing 
the stack
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61332](https://issues.apache.org/jira/browse/SPARK-61332): Send 
plans of up to 746 levels as PySpark does, and count the plans of subqueries 
for the depth bound without overflowing the stack. This is a follow-up of 
SPARK-61260 (#451), with two fixes in `crates/spark-connect/src/plan.rs`:
    
    - `MAX_PLAN_DEPTH` is 746, the depth from which official PySpark 4.3.0's 
serializer raises `RecursionError`, instead of 256. Its doc comment gives the 
measured depths.
    - Plans are serialized on the calling thread, on a stack that grows on 
demand. Each level of `relation_with_references` goes through the stack helper 
of SPARK-61328 (#456), which `expression.rs` now shares. The thread sized for 
the outer plan (`INLINE_PLAN_DEPTH`, `STACK_PER_PLAN_LEVEL`) is gone.
    - The levels of the plans are counted as they are serialized, those of the 
plans of subqueries included, under the plan that has them, as they are sent in 
its `WithRelations`. `relation_with_ids` fails with a `RecursionError` when the 
count is past the bound, and stops serializing at the bound, so the proto of 
the request, which is encoded and dropped by recursing too, is never deeper. 
The check of `LogicalPlan::depth` before the serialization stays, for the 
levels of the plan itself.
    
    ### Why are the changes needed?
    
    Two regressions of SPARK-61260.
    
    - It bounded a plan at 256 levels, on the premise that PySpark raises 
`RecursionError` from about 245 levels. It does not. Bisecting `_plan.to_proto` 
with official PySpark 4.3.0 against a local Spark 4.3.0 server, under the 
default recursion limit:
    
      | Chain | Serialized | `RecursionError` from |
      |---|---|---|
      | `filter` | 745 levels | 746 |
      | `withColumn` | 746 | 747 |
      | `select` | 746 | 747 |
      | `limit` | 747 | 748 |
    
      The server runs plans of up to about 510 levels. So the Rust client and 
the Python drop-in rejected plans of 257 to about 510 levels that PySpark, the 
previous master and the server all run, such as the 400 `withColumn`s of 
Apache's own `test_recursion_handling_for_plan_logging`.
    - The thread that SPARK-61260 serialized a deep plan on was sized for the 
levels of the outer plan only, but the plans of its subqueries (EXISTS, scalar, 
IN, table arguments) were serialized on it too. An outer plan of about 34 
levels with an EXISTS over a plan of 256 levels (Rust) or 300 (drop-in) 
overflowed that thread and aborted the process. In debug builds a 5-level plan 
over a 30-level subquery was enough. The previous master ran these plans.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. Plans of up to 746 levels, with the plans of their subqueries, are 
sent, as PySpark sends them. Deeper ones raise `RecursionError` in the Python 
client, and are an error of that kind in the Rust API, as before. A subquery 
over a deep plan no longer crashes the process.
    
    ### How was this patch tested?
    
    - 
`plan::deep_plan_tests::a_subquery_counts_for_the_bound_under_the_levels_above_it`
 (offline, placed before 
`dropping_a_deep_plan_does_not_overflow_a_small_stack`): limits over a filter 
with an EXISTS subquery, with the subquery's levels within the bound and one 
past it, under 0 and 33 levels. The plan within is serialized and the one past 
is a `RecursionError`, both on a thread with a stack of 512 KiB. A subquery of 
100,000 levels is a `RecursionError` and is dropped there too.
    - 
`plan::deep_plan_tests::a_plan_at_the_bound_is_encoded_on_a_thread_of_the_runtime`
 (same place): a plan at the bound is encoded and dropped on a thread with a 
stack of 2 MiB, that of the runtime's threads, where the transport encodes a 
request.
    - The existing deep-plan and deep-expression tests pass. All of them pass 
in release and in debug builds.
    - 
`test_a_subquery_of_a_deep_plan_is_sent_or_raises_recursion_error_as_pyspark` 
in `python/tests/test_dropin_offline.py` (mock server, placed before 
`test_a_plan_too_deep_to_send_raises_recursion_error_without_a_request`): a 
subquery of 300 levels under 33 is sent, and one of 800 raises `RecursionError` 
without a request.
    - `test_plans_of_a_few_hundred_levels_are_sent_as_pyspark` in 
`python/tests/test_dropin_e2e.py` (live, placed before 
`test_a_deep_plan_raises_recursion_error_as_pyspark`): 400 `withColumn`s give 
401 fields and count 10, and the filter of a 300-level subquery under 33 levels 
counts 10.
    - The lib tests of both crates (720 passed), the build of all tests, also 
with `wasm-udf`, the offline Python suites (2981 passed, 8 skipped) with the 
rebuilt extension, and the live drop-in and Arrow suites (255 passed) and live 
cases (15 passed) against a local Spark 4.3.0 server. Clippy reports no 
diagnostics in the changed lines.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #458 from HyukjinKwon/SPARK-61332-plan-depth.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/spark-connect/src/expression.rs |   6 +-
 crates/spark-connect/src/plan.rs       | 193 ++++++++++++++++++++++++++-------
 python/tests/test_dropin_e2e.py        |  18 +++
 python/tests/test_dropin_offline.py    |  18 +++
 4 files changed, 191 insertions(+), 44 deletions(-)

diff --git a/crates/spark-connect/src/expression.rs 
b/crates/spark-connect/src/expression.rs
index 34b09661..884ae215 100644
--- a/crates/spark-connect/src/expression.rs
+++ b/crates/spark-connect/src/expression.rs
@@ -103,9 +103,9 @@ impl Drop for DepthBoundScope {
     }
 }
 
-/// Run `f`, which goes down a level of an expression, with at least 
[`EXPRESSION_RED_ZONE`] of
-/// stack left.
-fn with_stack_for_a_level<T>(f: impl FnOnce() -> T) -> T {
+/// Run `f`, which goes down a level of an expression or of a plan, with at 
least
+/// [`EXPRESSION_RED_ZONE`] of stack left.
+pub(crate) fn with_stack_for_a_level<T>(f: impl FnOnce() -> T) -> T {
     stacker::maybe_grow(EXPRESSION_RED_ZONE, EXPRESSION_STACK_SEGMENT, f)
 }
 
diff --git a/crates/spark-connect/src/plan.rs b/crates/spark-connect/src/plan.rs
index 5a95ab29..8338e744 100644
--- a/crates/spark-connect/src/plan.rs
+++ b/crates/spark-connect/src/plan.rs
@@ -775,33 +775,82 @@ pub fn resolve_request(request: &mut 
proto::ExecutePlanRequest) -> Result<()> {
     }
 }
 
-/// How many levels deep a plan may be to be sent. PySpark builds the proto of 
a plan by
-/// recursing in Python, so under Python's default recursion limit of 1000 it 
raises
-/// `RecursionError` for a plan of about 245 levels or more, before any 
request is sent. A plan
-/// deeper than this bound fails in the same way. The server itself rejects a 
plan of about 510
-/// levels or more, with an error that gives no reason.
-pub const MAX_PLAN_DEPTH: usize = 256;
-
-/// Plans up to this deep are serialized on the calling thread. A level takes 
about 6 KiB of
-/// native stack in a release build, and about 96 KiB in a debug build, whose 
frames are much
-/// larger, so these fit any thread; a deeper plan is serialized on a thread 
with a stack of its
-/// own, sized for it, as the calling thread may have as little as 512 KiB.
-const INLINE_PLAN_DEPTH: usize = if cfg!(debug_assertions) { 4 } else { 32 };
-
-/// Native stack for each level of a plan serialized on a thread of its own: 
more than twice what
-/// a level takes, in a release build and in a debug build. The stack is 
reserved, so only the
-/// pages that the serialization uses take memory.
-const STACK_PER_PLAN_LEVEL: usize = if cfg!(debug_assertions) {
-    256 << 10
-} else {
-    16 << 10
-};
+/// 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.
+pub const MAX_PLAN_DEPTH: usize = 746;
+
+thread_local! {
+    /// The level of the plan that this thread serializes now, the plans of 
subqueries
+    /// included, and the deepest one since the start of the innermost 
`with_plan_depth_bound`.
+    static PLAN_LEVEL: std::cell::Cell<usize> = const { 
std::cell::Cell::new(0) };
+    static DEEPEST_PLAN_LEVEL: std::cell::Cell<usize> = const { 
std::cell::Cell::new(0) };
+    /// Whether this thread serializes in a `with_plan_depth_bound`, which 
stops at the bound.
+    static PLAN_DEPTH_BOUNDED: std::cell::Cell<bool> = const { 
std::cell::Cell::new(false) };
+}
+
+/// One level of a plan that is being serialized, left when it is dropped 
(also on a panic).
+struct PlanLevel(usize);
+
+impl PlanLevel {
+    fn enter() -> Self {
+        let level = PLAN_LEVEL.with(|current| {
+            let level = current.get() + 1;
+            current.set(level);
+            level
+        });
+        DEEPEST_PLAN_LEVEL.with(|deepest| 
deepest.set(deepest.get().max(level)));
+        PlanLevel(level)
+    }
+}
+
+impl Drop for PlanLevel {
+    fn drop(&mut self) {
+        PLAN_LEVEL.with(|current| current.set(current.get() - 1));
+    }
+}
+
+/// Run `serialize`, which serializes plans for a request, and fail as 
PySpark's serializer does
+/// if one of them, with the plans of its subqueries, is deeper than 
[`MAX_PLAN_DEPTH`]. Within
+/// it, a plan is serialized down to the bound only: its proto is dropped and 
encoded by
+/// recursing too, so it must not be deeper.
+fn with_plan_depth_bound<T>(serialize: impl FnOnce() -> T) -> Result<T> {
+    struct Scope {
+        outer_bounded: bool,
+        outer_deepest: usize,
+    }
+    impl Drop for Scope {
+        fn drop(&mut self) {
+            PLAN_DEPTH_BOUNDED.with(|bounded| bounded.set(self.outer_bounded));
+            DEEPEST_PLAN_LEVEL.with(|deepest| 
deepest.set(deepest.get().max(self.outer_deepest)));
+        }
+    }
+    let _scope = Scope {
+        outer_bounded: PLAN_DEPTH_BOUNDED.with(|bounded| 
bounded.replace(true)),
+        outer_deepest: DEEPEST_PLAN_LEVEL.with(|deepest| deepest.replace(0)),
+    };
+    let value = serialize();
+    if DEEPEST_PLAN_LEVEL.with(std::cell::Cell::get) > MAX_PLAN_DEPTH {
+        return Err(SparkError::recursion_msg(format!(
+            "maximum recursion depth exceeded while serializing a plan and the 
plans of its \
+             subqueries; a plan may be at most {MAX_PLAN_DEPTH} levels deep"
+        )));
+    }
+    Ok(value)
+}
 
 /// Serialize a shared plan node for a request: the node and every node below 
it carry
-/// their stable plan IDs. A plan deeper than [`MAX_PLAN_DEPTH`], or with an 
expression deeper
-/// than [`crate::expression::MAX_EXPRESSION_DEPTH`], is a `RecursionError`, 
as in PySpark,
-/// instead of a request that overflows the stack of the thread.
+/// their stable plan IDs. A plan deeper than [`MAX_PLAN_DEPTH`], with the 
plans of its
+/// subqueries, or with an expression deeper than 
[`crate::expression::MAX_EXPRESSION_DEPTH`], is
+/// a `RecursionError`, as in PySpark. The plan is serialized on the calling 
thread, whose stack
+/// grows on demand for its levels.
 pub(crate) fn relation_with_ids(node: &Arc<LogicalPlan>, ids: &PlanIds) -> 
Result<proto::Relation> {
+    // The levels of the plan itself are known before it is serialized; those 
of the plans of
+    // its subqueries are counted as they are serialized.
     let depth = node.depth();
     if depth > MAX_PLAN_DEPTH {
         return Err(SparkError::recursion_msg(format!(
@@ -809,23 +858,9 @@ pub(crate) fn relation_with_ids(node: &Arc<LogicalPlan>, 
ids: &PlanIds) -> Resul
              a plan may be at most {MAX_PLAN_DEPTH} levels deep"
         )));
     }
-    // The levels of the expressions are counted on the thread that serializes 
them.
-    let serialize =
-        || crate::expression::with_expression_depth_bound(|| relation_of(node, 
Some(ids)));
-    if depth <= INLINE_PLAN_DEPTH {
-        return serialize();
-    }
-    std::thread::scope(|scope| {
-        let serializing = std::thread::Builder::new()
-            .name("spark-connect-plan".to_string())
-            .stack_size((1 << 20) + depth * STACK_PER_PLAN_LEVEL)
-            .spawn_scoped(scope, serialize)
-            .map_err(|e| SparkError::connect_msg(format!("cannot serialize the 
plan: {e}")))?;
-        match serializing.join() {
-            Ok(relation) => relation,
-            Err(panic) => std::panic::resume_unwind(panic),
-        }
-    })
+    with_plan_depth_bound(|| {
+        crate::expression::with_expression_depth_bound(|| relation_of(node, 
Some(ids)))
+    })?
 }
 
 /// Serialize a child node, with its stable plan ID when `ids` is given.
@@ -890,6 +925,24 @@ fn relation_with_references(
     node: &LogicalPlan,
     shared: Option<&Arc<LogicalPlan>>,
     ids: Option<&PlanIds>,
+) -> proto::Relation {
+    // A level serializes the levels below it and the plans of its subqueries: 
grow the stack for
+    // a plan of many levels, and count them for `with_plan_depth_bound`.
+    crate::expression::with_stack_for_a_level(|| {
+        let level = PlanLevel::enter();
+        if level.0 > MAX_PLAN_DEPTH && 
PLAN_DEPTH_BOUNDED.with(std::cell::Cell::get) {
+            // The request fails with a `RecursionError`: stop here, so that 
the proto of the
+            // plan is no deeper than the bound.
+            return proto::Relation::default();
+        }
+        relation_with_references_of_a_level(node, shared, ids)
+    })
+}
+
+fn relation_with_references_of_a_level(
+    node: &LogicalPlan,
+    shared: Option<&Arc<LogicalPlan>>,
+    ids: Option<&PlanIds>,
 ) -> proto::Relation {
     let (mut relation, references) = relation_and_references(node, ids);
     let plan_ids = ids.zip(shared);
@@ -3315,6 +3368,64 @@ mod deep_plan_tests {
         }
     }
 
+    /// `limits` limits over a filter whose condition is the EXISTS subquery 
of a plan of
+    /// `levels` levels.
+    fn limits_over_a_filter_of_a_subquery(limits: usize, levels: usize) -> 
Arc<LogicalPlan> {
+        let subquery = crate::expression::SubqueryExpression::new(
+            chain(levels),
+            1,
+            crate::expression::SubqueryType::Exists,
+        );
+        let mut plan = Arc::new(LogicalPlan::Filter {
+            input: Arc::new(range(0, 10, 1)),
+            condition: 
crate::column::Column::new(Expression::new(ExpressionNode::Subquery(
+                Box::new(subquery),
+            ))),
+        });
+        for _ in 0..limits {
+            plan = Arc::new(limit(plan, 1));
+        }
+        plan
+    }
+
+    /// The plan of a subquery is sent under the plan that has it, so its 
levels count for the
+    /// bound under the levels above it, and neither overflows a small stack.
+    #[test]
+    fn a_subquery_counts_for_the_bound_under_the_levels_above_it() {
+        for limits in [0, 33] {
+            // The filter is a level under the limits, and the subquery one 
under the filter.
+            let within = limits_over_a_filter_of_a_subquery(limits, 
MAX_PLAN_DEPTH - limits - 1);
+            on_a_small_stack(|| relation_with_ids(&within, 
&PlanIds::new()).unwrap());
+            let past = limits_over_a_filter_of_a_subquery(limits, 
MAX_PLAN_DEPTH - limits);
+            let error = on_a_small_stack(|| relation_with_ids(&past, 
&PlanIds::new()).unwrap_err());
+            assert_eq!(error.kind, SparkErrorKind::RecursionError, "{error}");
+            assert!(
+                error.message().contains("the plans of its subqueries"),
+                "{error}"
+            );
+        }
+        let deep = limits_over_a_filter_of_a_subquery(33, 100_000);
+        let error = on_a_small_stack(|| relation_with_ids(&deep, 
&PlanIds::new()).unwrap_err());
+        assert_eq!(error.kind, SparkErrorKind::RecursionError, "{error}");
+        on_a_small_stack(move || std::mem::drop(deep));
+    }
+
+    /// The proto of a plan at the bound is encoded and dropped by recursing, 
as the transport
+    /// encodes a request on a thread of the runtime, whose stack is 2 MiB.
+    #[test]
+    fn a_plan_at_the_bound_is_encoded_on_a_thread_of_the_runtime() {
+        use prost::Message;
+
+        let relation = relation_with_ids(&chain(MAX_PLAN_DEPTH), 
&PlanIds::new()).unwrap();
+        let encoded = std::thread::Builder::new()
+            .stack_size(2 << 20)
+            .spawn(move || relation.encode_to_vec().len())
+            .unwrap()
+            .join()
+            .unwrap();
+        assert!(encoded > MAX_PLAN_DEPTH);
+    }
+
     #[test]
     fn dropping_a_deep_plan_does_not_overflow_a_small_stack() {
         on_a_small_stack(|| std::mem::drop(chain(1_000_000)));
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 67ff05f9..70036731 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -1312,6 +1312,24 @@ except RecursionError as error:
     assert "raised RecursionError" in result.stdout, (result.stdout, 
result.stderr)
 
 
+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.
+    df = session.range(10)
+    for x in range(400):
+        df = df.withColumn(f"col{x}", F.lit(x))
+    assert len(df.schema.fields) == 401
+    assert df.count() == 10
+    sub = session.range(1)
+    for _ in range(300):
+        sub = sub.limit(100)
+    outer = session.range(10)
+    for _ in range(32):
+        outer = outer.limit(100)
+    assert outer.filter(sub.exists()).count() == 10
+
+
 def test_a_deep_plan_raises_recursion_error_as_pyspark():
     # As official PySpark 4.3.0, which raises RecursionError for each of these 
depths while it
     # builds the plan, before any request. The server rejected 1,000 and 1,500 
levels without a
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index bc3f6363..014669bf 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -9398,6 +9398,24 @@ def 
test_create_dataframe_converts_numpy_scalars_as_pyarrow(mock_connect):
             _local_create_dataframe([(value,)], schema)
 
 
+def 
test_a_subquery_of_a_deep_plan_is_sent_or_raises_recursion_error_as_pyspark(mock_connect):
+    # As PySpark, which sends a subquery under the plan that has it, so that 
its levels add to
+    # those above it: one within the bound is sent (it overflowed the stack of 
the serializing
+    # thread before), and a deeper one raises RecursionError without a request.
+    spark, service = mock_connect
+
+    def limited(df, levels):
+        for _ in range(levels):
+            df = df.limit(100)
+        return df
+
+    limited(spark.range(10).filter(limited(spark.range(1), 300).exists()), 
33).collect()
+    assert len(service.execute_requests) == 1
+    with pytest.raises(RecursionError, match="the plans of its subqueries"):
+        spark.range(10).filter(limited(spark.range(1), 800).exists()).collect()
+    assert len(service.execute_requests) == 1
+
+
 def 
test_a_plan_too_deep_to_send_raises_recursion_error_without_a_request(mock_connect):
     # As PySpark, whose client raises RecursionError while it builds the proto 
of a plan a few
     # hundred levels deep, before any request, rather than overflowing the 
native stack.


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

Reply via email to