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 4cdb7e5b [SPARK-61328][CONNECT][PYTHON] Raise RecursionError instead 
of crashing the process on a deep expression, in the Python client as PySpark 
does
4cdb7e5b is described below

commit 4cdb7e5b4de3d125af4b1b3a8ca964ed52f953ad
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 13:17:21 2026 +0900

    [SPARK-61328][CONNECT][PYTHON] Raise RecursionError instead of crashing the 
process on a deep expression, in the Python client as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61328](https://issues.apache.org/jira/browse/SPARK-61328): Raise 
`RecursionError` instead of crashing the process on a deep expression, in the 
Python client as PySpark does. This is a follow-up of SPARK-61260 (#451), which 
bounded the depth of a plan but not the depth of an expression.
    
    - `crates/spark-connect/src/expression.rs`:
      - `Expression::to_proto`, `Expression::render`, the `Debug` and 
`PartialEq` of `Expression`, and the drop by the last owner of a node each 
recurse once per level of the expression. They now run on a stack that grows on 
demand (`stacker::maybe_grow`), so an expression of any depth does not overflow 
the stack of the calling thread.
      - `MAX_EXPRESSION_DEPTH` (745) and `with_expression_depth_bound`: the 
levels of the expressions that a request serializes are counted. An expression 
deeper than the bound fails the request with a `RecursionError` 
(`SparkErrorKind::RecursionError`, which the Python client raises as the 
builtin), as PySpark's serializer raises it. Within the bound, an expression is 
serialized down to the bound only: its proto is dropped and encoded by 
recursing too, so it is never built deeper.
      - Out of a request, the public `Expression::to_proto` serializes every 
level, as before.
    - `crates/spark-connect/src/plan.rs`: `relation_with_ids`, which every 
request that sends a DataFrame's plan goes through (SPARK-61260), serializes 
within `with_expression_depth_bound`, on the calling thread or on its own sized 
thread.
    - `crates/spark-connect/Cargo.toml`: `stacker = "0.1"`, already in 
`Cargo.lock` at 0.1.24 through `polars-utils` and `recursive`. Its MSRV is 1.63.
    
    The bound: official PySpark 4.3.0 raises `RecursionError` for 
`select((col("id") + 1 + ... + 1).alias("x"))` from 744 additions (746 levels 
with the alias and the column) and sends 743 (745 levels), so 745 gives the 
same result for that expression.
    
    ### Why are the changes needed?
    
    `select((col("id") + 1 + ... + 1).alias("x")).collect()` against a local 
Spark 4.3.0 Connect server, by number of additions:
    
    | Additions | Official PySpark 4.3.0 | master | This PR |
    |---|---|---|---|
    | 300 | server error (`Max iterations (100) reached for batch Resolution`) 
| the same | the same |
    | 743 | server error (gRPC `INTERNAL`) | `[Unknown error] Application error 
processing RPC` | the same as master |
    | 744 | `RecursionError` | `[Unknown error] Application error processing 
RPC` | `RecursionError` |
    | 3,000 | `RecursionError` | `[Unknown error] Application error processing 
RPC` | `RecursionError` |
    | 30,000 | `RecursionError` | the process dies with SIGSEGV | 
`RecursionError` |
    | 100,000 | `RecursionError` | the process dies with SIGSEGV | 
`RecursionError` |
    
    With this change the process lives, and the session works afterwards, at 
every depth.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. A request whose plan has an expression deeper than 745 levels raises 
`RecursionError` in the Python client, and is an error of that kind in the Rust 
API, before any request is sent, instead of a server error or a crash. 
Expressions of any depth can be built, rendered, compared and dropped without 
overflowing the stack.
    
    One difference from PySpark remains: the `repr` of a column of more than 
about 1,000 levels is returned (a 30,000-level column renders 180,012 
characters in 0.2 s), where PySpark raises `RecursionError`.
    
    ### How was this patch tested?
    
    - `expression::tests::deep_expressions_do_not_overflow_a_small_stack` 
(offline, placed before `test_literal_integer`), on a thread with a stack of 
512 KiB: an expression at the bound is serialized with all its levels. One of 
100,000 levels is a `RecursionError` in a request; out of one it is serialized 
with all its levels; and it is rendered, compared, formatted and dropped. It 
overflowed the stack before this change.
    - 
`plan::deep_plan_tests::an_expression_past_the_bound_is_a_recursion_error_as_in_pyspark`
 (offline, placed before 
`dropping_a_deep_plan_does_not_overflow_a_small_stack`): a projection of an 
expression at the bound is serialized; one past it is a `RecursionError`, over 
plans of 1 and of 100 levels (serialized on the calling thread and on their own 
thread), on a small stack.
    - Both pass in release and in debug builds.
    - 
`test_an_expression_too_deep_to_send_raises_recursion_error_without_a_request` 
in `python/tests/test_dropin_offline.py` (mock server, placed before 
`test_window_and_lambda_reprs_as_pyspark`): `select` and `withColumn` of 744, 
30,000 and 100,000 additions raise `RecursionError` without a request, the 
`repr` of the deep columns is rendered, and 743 additions are sent.
    - The table above, for the drop-in and official PySpark 4.3.0 on the same 
server.
    - The lib tests of both crates (718 passed), the build of all tests, also 
with `wasm-udf`, the offline Python suites (2977 passed, 8 skipped), and the 
live drop-in and Arrow suites (249 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 #456 from HyukjinKwon/SPARK-61328-deep-expressions.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 Cargo.lock                             |   1 +
 crates/spark-connect/Cargo.toml        |   2 +
 crates/spark-connect/src/expression.rs | 219 ++++++++++++++++++++++++++++++++-
 crates/spark-connect/src/plan.rs       |  59 ++++++++-
 python/tests/test_dropin_offline.py    |  28 +++++
 5 files changed, 302 insertions(+), 7 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock
index 1a0fdbe3..22ef66dd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -68,6 +68,7 @@ dependencies = [
  "prost",
  "prost-types",
  "serde_json",
+ "stacker",
  "thiserror",
  "tokio",
  "uuid",
diff --git a/crates/spark-connect/Cargo.toml b/crates/spark-connect/Cargo.toml
index d73b2b75..927540cb 100644
--- a/crates/spark-connect/Cargo.toml
+++ b/crates/spark-connect/Cargo.toml
@@ -26,6 +26,8 @@ serde_json = "1.0"
 # Local time for the reprs of timestamp literals, as Python's 
`datetime.fromtimestamp`.
 chrono = { version = "0.4", default-features = false, features = ["clock"] }
 uuid.workspace = true
+# Grows the stack on demand while an expression of many levels is serialized 
or rendered.
+stacker = "0.1"
 
 # Optional: only pulled in by the `wasm-udf` feature.
 base64 = { version = "0.21", optional = true }
diff --git a/crates/spark-connect/src/expression.rs 
b/crates/spark-connect/src/expression.rs
index bfa58b83..34b09661 100644
--- a/crates/spark-connect/src/expression.rs
+++ b/crates/spark-connect/src/expression.rs
@@ -2,9 +2,11 @@
 //!
 //! Defines the Expression hierarchy and conversion functions to Spark Connect 
protobufs.
 
+use std::cell::Cell;
 use std::sync::atomic::{AtomicU32, Ordering};
 use std::sync::Arc;
 
+use spark_connect_core::error::{Result, SparkError};
 use spark_connect_proto as proto;
 
 use crate::plan::LogicalPlan;
@@ -19,6 +21,111 @@ 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`]).
+pub const MAX_EXPRESSION_DEPTH: usize = 745;
+
+/// The stack that serializing or rendering an expression keeps free before it 
goes down a level,
+/// and the size of a stack segment that it adds when less is left: a level 
recurses once, so an
+/// expression of any number of levels grows the stack instead of overflowing 
it. A frame of a
+/// debug build is many times larger than one of a release build.
+const EXPRESSION_RED_ZONE: usize = if cfg!(debug_assertions) {
+    1 << 20
+} else {
+    128 << 10
+};
+const EXPRESSION_STACK_SEGMENT: usize = if cfg!(debug_assertions) {
+    16 << 20
+} else {
+    4 << 20
+};
+
+thread_local! {
+    /// The level of the expression that this thread serializes now, and the 
deepest one since
+    /// the start of the innermost [`with_expression_depth_bound`].
+    static EXPRESSION_LEVEL: Cell<usize> = const { Cell::new(0) };
+    static DEEPEST_EXPRESSION_LEVEL: Cell<usize> = const { Cell::new(0) };
+    /// Whether this thread serializes in a [`with_expression_depth_bound`], 
which stops at the
+    /// bound.
+    static EXPRESSION_DEPTH_BOUNDED: Cell<bool> = const { Cell::new(false) };
+}
+
+/// One level of an expression that is being serialized, left when it is 
dropped (also on a
+/// panic, so that the level of the thread stays right).
+struct ExpressionLevel(usize);
+
+impl ExpressionLevel {
+    fn enter() -> Self {
+        let level = EXPRESSION_LEVEL.with(|current| {
+            let level = current.get() + 1;
+            current.set(level);
+            level
+        });
+        DEEPEST_EXPRESSION_LEVEL.with(|deepest| 
deepest.set(deepest.get().max(level)));
+        ExpressionLevel(level)
+    }
+}
+
+impl Drop for ExpressionLevel {
+    fn drop(&mut self) {
+        EXPRESSION_LEVEL.with(|current| current.set(current.get() - 1));
+    }
+}
+
+/// The [`with_expression_depth_bound`] of this thread, until it is dropped: 
the bound and the
+/// deepest level of the serialization that encloses it, if any, are restored.
+struct DepthBoundScope {
+    outer_bounded: bool,
+    outer_deepest: usize,
+}
+
+impl DepthBoundScope {
+    fn enter() -> Self {
+        DepthBoundScope {
+            outer_bounded: EXPRESSION_DEPTH_BOUNDED.with(|bounded| 
bounded.replace(true)),
+            outer_deepest: DEEPEST_EXPRESSION_LEVEL.with(|deepest| 
deepest.replace(0)),
+        }
+    }
+
+    /// The deepest level since the scope was entered.
+    fn deepest(&self) -> usize {
+        DEEPEST_EXPRESSION_LEVEL.with(Cell::get)
+    }
+}
+
+impl Drop for DepthBoundScope {
+    fn drop(&mut self) {
+        EXPRESSION_DEPTH_BOUNDED.with(|bounded| 
bounded.set(self.outer_bounded));
+        DEEPEST_EXPRESSION_LEVEL.with(|deepest| 
deepest.set(deepest.get().max(self.outer_deepest)));
+    }
+}
+
+/// 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 {
+    stacker::maybe_grow(EXPRESSION_RED_ZONE, EXPRESSION_STACK_SEGMENT, f)
+}
+
+/// Run `serialize`, which serializes expressions for a request, and fail as 
PySpark's serializer
+/// does if one of them is deeper than [`MAX_EXPRESSION_DEPTH`]: with a 
`RecursionError`, instead
+/// of a request that overflows the stack or that the server cannot parse. 
Within it, an
+/// expression is serialized down to the bound only: its proto is dropped and 
encoded by
+/// recursing too, so it must not be deeper.
+pub(crate) fn with_expression_depth_bound<T>(serialize: impl FnOnce() -> T) -> 
Result<T> {
+    let scope = DepthBoundScope::enter();
+    let value = serialize();
+    if scope.deepest() > MAX_EXPRESSION_DEPTH {
+        return Err(SparkError::recursion_msg(format!(
+            "maximum recursion depth exceeded while serializing an expression; 
an expression \
+             may be at most {MAX_EXPRESSION_DEPTH} levels deep"
+        )));
+    }
+    Ok(value)
+}
+
 /// An immutable, shared expression, mirroring PySpark's base Expression type.
 ///
 /// Cloning a handle shares its node rather than copying the expression 
subtree.
@@ -34,14 +141,30 @@ pub struct Expression {
 
 impl std::fmt::Debug for Expression {
     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-        std::fmt::Debug::fmt(self.node(), f)
+        with_stack_for_a_level(|| std::fmt::Debug::fmt(self.node(), f))
     }
 }
 
 impl PartialEq for Expression {
     fn eq(&self, other: &Self) -> bool {
         // Compare values even for the same allocation: NaN must remain 
unequal to itself.
-        self.node().eq(other.node())
+        with_stack_for_a_level(|| self.node().eq(other.node()))
+    }
+}
+
+/// The node that a dropped expression holds once its own node has gone, which 
has no levels
+/// below it.
+static DROPPED_NODE: std::sync::LazyLock<Arc<ExpressionNode>> =
+    std::sync::LazyLock::new(|| 
Arc::new(ExpressionNode::SQLExpression(String::new())));
+
+impl Drop for Expression {
+    /// The last owner of a node drops the levels below it, each in turn: give 
them the stack
+    /// that an expression of many levels needs, as for serializing it.
+    fn drop(&mut self) {
+        if Arc::strong_count(&self.node) == 1 {
+            let node = std::mem::replace(&mut self.node, 
Arc::clone(&DROPPED_NODE));
+            with_stack_for_a_level(move || drop(node));
+        }
     }
 }
 
@@ -346,6 +469,11 @@ impl Expression {
     /// decide column equality, so the rendering must be deterministic and 
mirror
     /// PySpark's format for the common operators.
     pub fn render(&self) -> String {
+        // A level renders the levels below it: grow the stack for an 
expression of many levels.
+        with_stack_for_a_level(|| self.render_node())
+    }
+
+    fn render_node(&self) -> String {
         match self.node() {
             ExpressionNode::Literal(lit) => lit.render(),
             ExpressionNode::ColumnReference(col_ref) => col_ref.name.clone(),
@@ -422,6 +550,20 @@ impl Expression {
     /// Converts the expression to a Spark Connect protobuf expression, with 
its origin, as
     /// PySpark's `Expression._create_proto_expression` sends it.
     pub fn to_proto(&self) -> proto::Expression {
+        // A level serializes the levels below it: grow the stack for an 
expression of many
+        // levels, and count them for `with_expression_depth_bound`.
+        with_stack_for_a_level(|| {
+            let level = ExpressionLevel::enter();
+            if level.0 > MAX_EXPRESSION_DEPTH && 
EXPRESSION_DEPTH_BOUNDED.with(Cell::get) {
+                // The request fails with a `RecursionError`: stop here, so 
that the proto of the
+                // expression is no deeper than the bound.
+                return proto::Expression::default();
+            }
+            self.to_proto_with_origin()
+        })
+    }
+
+    fn to_proto_with_origin(&self) -> proto::Expression {
         let mut expr = self.node_to_proto();
         if let Some(origin) = &self.origin {
             expr.common = Some(proto::ExpressionCommon {
@@ -1596,6 +1738,79 @@ mod tests {
         assert_ne!(add.render(), eq.render());
     }
 
+    /// `id + 1` chained `levels` times, as `col("id") + 1` in a loop of 
PySpark builds it.
+    fn chained_additions(levels: usize) -> Expression {
+        let mut expr = col("id");
+        for _ in 0..levels {
+            expr = Expression::function(
+                "+",
+                vec![expr, Expression::literal(LiteralExpression::Integer(1))],
+            );
+        }
+        expr
+    }
+
+    /// The levels of a serialized expression of `chained_additions`.
+    fn serialized_levels(expr: &proto::Expression) -> usize {
+        let mut levels = 1;
+        let mut expr = expr;
+        while let 
Some(proto::expression::ExprType::UnresolvedFunction(function)) = 
&expr.expr_type
+        {
+            expr = &function.arguments[0];
+            levels += 1;
+        }
+        levels
+    }
+
+    /// An expression of any number of levels is serialized, rendered, 
compared, formatted and
+    /// dropped on a small stack, which grows on demand; one deeper than 
`MAX_EXPRESSION_DEPTH`
+    /// is a `RecursionError`, as PySpark's serializer raises it.
+    #[test]
+    fn deep_expressions_do_not_overflow_a_small_stack() {
+        std::thread::Builder::new()
+            .stack_size(512 << 10)
+            .spawn(|| {
+                let at_bound = chained_additions(MAX_EXPRESSION_DEPTH - 1);
+                let proto =
+                    with_expression_depth_bound(|| 
at_bound.to_proto()).expect("at the bound");
+                assert_eq!(serialized_levels(&proto), MAX_EXPRESSION_DEPTH);
+
+                let deep = chained_additions(100_000);
+                let error = with_expression_depth_bound(|| 
deep.to_proto()).expect_err("deep");
+                assert_eq!(
+                    error.kind,
+                    spark_connect_core::error::SparkErrorKind::RecursionError
+                );
+                assert!(
+                    error.message().contains("maximum recursion depth"),
+                    "{error}"
+                );
+                // Out of a request, every level is serialized.
+                let full = deep.to_proto();
+                assert_eq!(serialized_levels(&full), 100_001);
+                // The caller drops it: a proto this deep needs the stack of a 
big thread.
+                std::thread::Builder::new()
+                    .stack_size(256 << 20)
+                    .spawn(move || std::mem::drop(full))
+                    .unwrap()
+                    .join()
+                    .unwrap();
+                let rendered = chained_additions(10_000).render();
+                assert!(rendered.starts_with("+(+(+(") && 
rendered.contains("+(id, 1), 1)"));
+                assert!(rendered.ends_with(", 1), 1), 1)"));
+                assert_eq!(rendered.len(), "id".len() + 10_000 * "+(, 
1)".len());
+                assert!(deep == deep.clone());
+                
assert!(format!("{deep:?}").starts_with("UnresolvedFunction("));
+                std::mem::drop(deep);
+
+                // The deepest level is counted again for each serialization.
+                assert!(with_expression_depth_bound(|| 
at_bound.to_proto()).is_ok());
+            })
+            .unwrap()
+            .join()
+            .unwrap();
+    }
+
     #[test]
     fn test_literal_integer() {
         let lit = LiteralExpression::int(42);
diff --git a/crates/spark-connect/src/plan.rs b/crates/spark-connect/src/plan.rs
index cac08e4a..5a95ab29 100644
--- a/crates/spark-connect/src/plan.rs
+++ b/crates/spark-connect/src/plan.rs
@@ -798,8 +798,9 @@ const STACK_PER_PLAN_LEVEL: usize = if 
cfg!(debug_assertions) {
 };
 
 /// 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`] 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`], 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.
 pub(crate) fn relation_with_ids(node: &Arc<LogicalPlan>, ids: &PlanIds) -> 
Result<proto::Relation> {
     let depth = node.depth();
     if depth > MAX_PLAN_DEPTH {
@@ -808,17 +809,20 @@ 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 Ok(relation_of(node, Some(ids)));
+        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, || relation_of(node, Some(ids)))
+            .spawn_scoped(scope, serialize)
             .map_err(|e| SparkError::connect_msg(format!("cannot serialize the 
plan: {e}")))?;
         match serializing.join() {
-            Ok(relation) => Ok(relation),
+            Ok(relation) => relation,
             Err(panic) => std::panic::resume_unwind(panic),
         }
     })
@@ -3266,6 +3270,51 @@ mod deep_plan_tests {
         }
     }
 
+    /// A projection of `id + 1` chained `levels` times, over a plan of 
`plan_levels` levels.
+    fn projection_of_additions(plan_levels: usize, levels: usize) -> 
Arc<LogicalPlan> {
+        let mut expr = Expression::column("id");
+        for _ in 0..levels {
+            expr = Expression::function(
+                "+",
+                vec![
+                    expr,
+                    
Expression::literal(crate::expression::LiteralExpression::Integer(1)),
+                ],
+            );
+        }
+        Arc::new(LogicalPlan::Project {
+            input: chain(plan_levels),
+            columns: vec![crate::column::Column::new(expr)],
+        })
+    }
+
+    /// An expression deeper than `MAX_EXPRESSION_DEPTH` is a 
`RecursionError`, as PySpark's
+    /// serializer raises it, whether the plan is serialized on the calling 
thread or on one of
+    /// its own, and an expression at the bound is serialized; neither 
overflows a small stack.
+    #[test]
+    fn an_expression_past_the_bound_is_a_recursion_error_as_in_pyspark() {
+        use crate::expression::MAX_EXPRESSION_DEPTH;
+        for plan_levels in [1, 100] {
+            let at_bound = projection_of_additions(plan_levels, 
MAX_EXPRESSION_DEPTH - 1);
+            on_a_small_stack(|| relation_with_ids(&at_bound, 
&PlanIds::new()).unwrap());
+            for levels in [MAX_EXPRESSION_DEPTH, 100_000] {
+                let plan = projection_of_additions(plan_levels, levels);
+                let error =
+                    on_a_small_stack(|| relation_with_ids(&plan, 
&PlanIds::new()).unwrap_err());
+                assert_eq!(
+                    error.kind,
+                    SparkErrorKind::RecursionError,
+                    "{levels}: {error}"
+                );
+                assert!(
+                    error.message().contains("an expression may be at most"),
+                    "{error}"
+                );
+                on_a_small_stack(move || std::mem::drop(plan));
+            }
+        }
+    }
+
     #[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_offline.py 
b/python/tests/test_dropin_offline.py
index f7678857..d7467988 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -14488,6 +14488,34 @@ def test_column_reprs_as_pyspark(column, expected):
     assert repr(column(F)) == f"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.
+    from pyspark.sql import functions as F
+
+    spark, service = mock_connect
+
+    def chained(additions):
+        c = F.col("id")
+        for _ in range(additions):
+            c = c + 1
+        return c.alias("x")
+
+    for additions in [744, 30_000, 100_000]:
+        deep = chained(additions)
+        for action in [spark.range(1).select(deep).collect, 
spark.range(1).withColumn("y", deep).count]:
+            with pytest.raises(RecursionError, match="an expression may be at 
most 745 levels"):
+                action()
+        if additions <= 30_000:
+            # Rendered on a stack that grows (PySpark raises RecursionError 
from ~1,000 levels).
+            assert repr(deep).startswith("Column<'+(+(")
+        del deep
+    assert service.execute_requests == []
+    spark.range(1).select(chained(743)).collect()
+    assert len(service.execute_requests) == 1
+
+
 def test_window_and_lambda_reprs_as_pyspark():
     import re
 


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

Reply via email to