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

commit 2c768214e8831567d3e1082b3cfc06cc5f114b6d
Author: Timothy Meehan <[email protected]>
AuthorDate: Tue Nov 10 10:45:13 2026 +0900

    [SPARK-61260][CONNECT][PYTHON] Raise RecursionError instead of crashing the 
process on a deep plan, in the Python client as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61260](https://issues.apache.org/jira/browse/SPARK-61260): Raise 
`RecursionError` instead of crashing the process on a deep plan, in the Python 
client as PySpark does.
    
    - A plan deeper than `MAX_PLAN_DEPTH` (256 levels) fails with a 
`RecursionError` (`SparkErrorKind::RecursionError`, which the Python client 
raises as the builtin) before any request is built (`relation_with_ids`, 
`crates/spark-connect/src/plan.rs`). Every request that sends a DataFrame's 
plan goes through it: actions, analysis, writes, streaming starts, merges, ML 
transforms and fits, pipelines, and the placeholders that `pyspark.ml` and 
session hooks send. The depth (`LogicalPlan::de [...]
    - A plan deeper than 32 levels is serialized on a scoped thread whose stack 
is sized for its depth, so it does not overflow the stack of a calling thread 
with as little as 512 KiB. A level takes about 5 KiB of native stack.
    - `LogicalPlan` drops the plans below it that nothing else holds without 
recursing, so dropping a plan of any depth, sent or not, does not overflow the 
stack. The plans that another plan still holds are kept as they are.
    - `DataFrame::to_relation` and `Transformer::build_ml_relation` of the Rust 
API now return a `Result`, as serializing can fail.
    
    The bound: PySpark builds the proto of a plan by recursing in Python, so 
under Python's default recursion limit of 1000 it raises `RecursionError` from 
245 to 247 levels, depending on the operation (measured with `filter`, 
`select`, `limit`, `withColumn` and `alias` chains). The server rejects a plan 
of about 510 levels or more with only `[Unknown error] Application error 
processing RPC`. 256 gives `RecursionError` for every plan PySpark raises it 
for, give or take ten levels, and kee [...]
    
    ### Why are the changes needed?
    
    Serializing a plan recursed once per level with no bound. Against an OSS 
Spark 4.3.0 Connect server, with `spark.range(10)` under chained `filter`s and 
`count()`:
    
    ```python
    df = spark.range(10)
    for _ in range(2000):
        df = df.filter(F.col("id") >= 0)
    df.count()
    ```
    
    - PySpark 4.3.0 raises `RecursionError` from 245 levels, and the process 
lives.
    - master: 510 to 1,500 levels were rejected by the server with `[Unknown 
error] Application error processing RPC`, and from 2,000 levels the process 
died with SIGSEGV. On a thread with a stack of 1 MiB, the process died from 200 
levels.
    - master: dropping a plan of 100,000 levels that was never sent killed the 
process on a thread with a stack of 1 MiB. PySpark drops it.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes.
    - A plan deeper than 256 levels raises `RecursionError` in the Python 
client, and is an error of that kind in the Rust API, instead of a crash or an 
error of the server. Plans up to 256 levels are sent as before, also from 
threads with small stacks.
    - Dropping a deep plan no longer crashes the process.
    - Rust API: `DataFrame::to_relation` returns `Result<Relation>`, and 
`Transformer::build_ml_relation` returns `Result<MlRelation>`.
    
    ### How was this patch tested?
    
    - Rust unit tests (new, `plan::deep_plan_tests` in 
`crates/spark-connect/src/plan.rs`): the depth of chains and of plans with 
references; a plan whose levels each refer twice to the one below (2^64 paths) 
has its depth found at once; a plan of exactly 256 levels is serialized on a 
thread with a 512 KiB stack; plans of 257, 2,000 and 100,000 levels are 
`RecursionError`s; a plan of 1,000,000 levels drops on a 512 KiB stack; 
dropping a plan keeps the inputs that another plan holds. Witho [...]
    - Rust unit test (new, `dataframe::plan_construction_tests`): `count`, 
`collect`, `schema` and `explain_string` of 10,000 chained filters are 
`RecursionError`s, offline, without a server.
    - Python offline test (new, 
`test_a_plan_too_deep_to_send_raises_recursion_error_without_a_request` in 
`python/tests/test_dropin_offline.py`, with the mock server): `count`, 
`collect`, `schema` and `explain` of 10,000 chained filters raise 
`RecursionError`, and no execute or analyze request is sent.
    - Python live test (new, 
`test_a_deep_plan_raises_recursion_error_as_pyspark` in 
`python/tests/test_dropin_e2e.py`): the depths of the issue, 1,000 to 10,000 
levels, raise `RecursionError` in a process of its own, which then runs 
`spark.range(3).count()`.
    - The issue's repro against a local Spark 4.3.0 server: from 255 to 10,000 
levels the drop-in raises `RecursionError` and the process lives, as PySpark 
4.3.0 does from 245; on a thread with a 1 MiB stack, plans up to 254 levels are 
sent (the server's error, as PySpark gets at those depths) and deeper ones 
raise `RecursionError`; plans of 10,000, 100,000 and 1,000,000 levels drop on 
the main thread and on a 1 MiB thread.
    - The lib tests of the crate (535 passed), all the Rust tests of both 
crates against a local Spark 4.3.0 server (1009 passed), the build of all 
tests, also with `wasm-udf` and with `datafusion,polars`, the offline Python 
suites (2928 passed, 8 skipped), and the live drop-in, Arrow and ML suites (237 
passed, 1 skipped) against a local Spark 4.3.0 server. The official Connect 
suites through `scripts/run_official_tests.py`, in drop-in mode and through the 
transport, against a local Spark [...]
    
    ### 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 #451 from tdcmeehan/SPARK-61260-deep-plan-recursion-error.
    
    Lead-authored-by: Timothy Meehan <[email protected]>
    Co-authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/dataframe.rs                 |   7 +-
 crates/spark-connect/src/arrow_input.rs            |  17 +-
 crates/spark-connect/src/dataframe.rs              | 104 ++++---
 crates/spark-connect/src/merge.rs                  |   2 +-
 crates/spark-connect/src/ml.rs                     |  84 ++++--
 crates/spark-connect/src/pipelines.rs              |   2 +-
 crates/spark-connect/src/plan.rs                   | 325 ++++++++++++++++++++-
 crates/spark-connect/src/readwriter.rs             |   5 +-
 crates/spark-connect/src/session.rs                |   2 +-
 crates/spark-connect/src/streaming.rs              |   2 +-
 crates/spark-connect/tests/arrow_map_input.rs      |   4 +-
 crates/spark-connect/tests/e2e_coverage.rs         |   8 +-
 crates/spark-connect/tests/e2e_dataframe.rs        |   4 +-
 crates/spark-connect/tests/e2e_kmeans.rs           |   2 +-
 .../spark-connect/tests/e2e_linear_regression.rs   |   2 +-
 crates/spark-connect/tests/e2e_linear_svc.rs       |   2 +-
 crates/spark-connect/tests/execute_plan_hook.rs    |   2 +-
 crates/spark-connect/tests/raw_relation.rs         |  41 ++-
 python/tests/test_dropin_e2e.py                    |  36 +++
 python/tests/test_dropin_offline.py                |  16 +
 20 files changed, 549 insertions(+), 118 deletions(-)

diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index 18797457..f6017ab3 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -656,9 +656,10 @@ impl PyDataFrame {
     }
 
     /// The bytes of the relation of this DataFrame as it is sent, for the 
plan of `_plan`.
-    fn _relation_bytes<'py>(&self, py: Python<'py>) -> Bound<'py, 
pyo3::types::PyBytes> {
+    fn _relation_bytes<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, 
pyo3::types::PyBytes>> {
         use prost::Message;
-        pyo3::types::PyBytes::new(py, 
&self.dataframe.to_relation().encode_to_vec())
+        let relation = self.dataframe.to_relation().to_pyerr()?;
+        Ok(pyo3::types::PyBytes::new(py, &relation.encode_to_vec()))
     }
 
     /// The bytes of the placeholder of the relation of this DataFrame, which 
the plan of `_plan`
@@ -678,7 +679,7 @@ impl PyDataFrame {
         let this = slf.borrow();
         py.import("pyspark.sql.connect.dataframe")?
             .getattr("_reduce_dataframe")?
-            .call1((this.spark_session(py)?, this._relation_bytes(py)))
+            .call1((this.spark_session(py)?, this._relation_bytes(py)?))
     }
 
     /// The DataFrame of `relation`, the bytes of a relation of `session`, as 
a pickled DataFrame
diff --git a/crates/spark-connect/src/arrow_input.rs 
b/crates/spark-connect/src/arrow_input.rs
index 31751353..d44b87d0 100644
--- a/crates/spark-connect/src/arrow_input.rs
+++ b/crates/spark-connect/src/arrow_input.rs
@@ -580,13 +580,14 @@ mod tests {
         assert_eq!(before.values().to_data(), after.values().to_data());
         assert_eq!(before.offsets(), after.offsets());
 
+        let relation = inline_relation(std::slice::from_ref(&batch), 
None).unwrap();
         let LogicalPlan::LocalRelation {
             data: Some(data), ..
-        } = inline_relation(std::slice::from_ref(&batch), None).unwrap()
+        } = &relation
         else {
             panic!("expected inline data");
         };
-        let mut reader = StreamReader::try_new(Cursor::new(data), 
None).unwrap();
+        let mut reader = StreamReader::try_new(Cursor::new(data.clone()), 
None).unwrap();
         assert_canonical_map(reader.schema().field(0).data_type());
         assert_eq!(reader.next().unwrap().unwrap(), expected);
         assert!(reader.next().is_none());
@@ -887,13 +888,14 @@ mod tests {
         assert_eq!(fields[0].metadata().get("schema_tag").unwrap(), 
"preserved");
         let after = after.as_any().downcast_ref::<StructArray>().unwrap();
         assert_map_values_unchanged(&maps, after.column(0));
+        let relation = inline_relation(std::slice::from_ref(&batch), 
None).unwrap();
         let LogicalPlan::LocalRelation {
             data: Some(data), ..
-        } = inline_relation(std::slice::from_ref(&batch), None).unwrap()
+        } = &relation
         else {
             panic!("expected inline relation");
         };
-        let mut reader = StreamReader::try_new(Cursor::new(data), 
None).unwrap();
+        let mut reader = StreamReader::try_new(Cursor::new(data.clone()), 
None).unwrap();
         let decoded = reader.next().unwrap().unwrap();
         decoded.column(0).to_data().validate_full().unwrap();
         assert_eq!(decoded.schema(), normalized[0].schema());
@@ -909,7 +911,7 @@ mod tests {
             .create_dataframe_from_arrow(vec![map_batch(0)], None)
             .unwrap();
         let Some(spark_connect_proto::relation::RelType::LocalRelation(local)) 
=
-            dataframe.to_relation().rel_type
+            dataframe.to_relation().unwrap().rel_type
         else {
             panic!("expected zero-row inline relation");
         };
@@ -952,13 +954,14 @@ mod tests {
         .unwrap();
         let prepared = 
normalize_map_names(std::slice::from_ref(&batch)).unwrap();
         assert!(matches!(prepared, Cow::Borrowed(_)));
+        let relation = inline_relation(std::slice::from_ref(&batch), 
None).unwrap();
         let LogicalPlan::LocalRelation {
             data: Some(data), ..
-        } = inline_relation(std::slice::from_ref(&batch), None).unwrap()
+        } = &relation
         else {
             panic!("expected inline relation");
         };
-        let mut reader = StreamReader::try_new(Cursor::new(data), 
None).unwrap();
+        let mut reader = StreamReader::try_new(Cursor::new(data.clone()), 
None).unwrap();
         assert_canonical_map(reader.schema().field(0).data_type());
         let decoded = reader.next().unwrap().unwrap();
         assert_canonical_map(decoded.schema().field(0).data_type());
diff --git a/crates/spark-connect/src/dataframe.rs 
b/crates/spark-connect/src/dataframe.rs
index 57311a97..121efaba 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -1170,7 +1170,7 @@ impl DataFrame {
     /// The relation of this DataFrame as it is sent, with the plan IDs of its 
session, for a
     /// plan built outside the core over it, such as of `pyspark.ml`. Not a 
stable API.
     #[doc(hidden)]
-    pub fn to_relation(&self) -> proto::Relation {
+    pub fn to_relation(&self) -> Result<proto::Relation> {
         build_input_relation(&self.plan, &self.session)
     }
 
@@ -1276,13 +1276,13 @@ impl DataFrame {
 
     /// This DataFrame's relation for a request. Its plan nodes keep the same 
plan IDs each
     /// time, as in PySpark, so the server can reuse the plans it already 
resolved.
-    pub(crate) fn relation(&self) -> proto::Relation {
+    pub(crate) fn relation(&self) -> Result<proto::Relation> {
         crate::plan::relation_with_ids(&self.plan, self.session.plan_ids())
     }
 
     /// Build an ExecutePlanRequest from the logical plan.
     fn build_execute_request(&self) -> Result<proto::ExecutePlanRequest> {
-        let relation = self.relation();
+        let relation = self.relation()?;
 
         let mut request = proto::ExecutePlanRequest::default();
         request.session_id = self.session.client().session_id().to_string();
@@ -1298,7 +1298,7 @@ impl DataFrame {
 
     /// Build an AnalyzePlanRequest from the logical plan.
     fn build_analyze_request(&self) -> Result<proto::AnalyzePlanRequest> {
-        let relation = self.relation();
+        let relation = self.relation()?;
 
         let mut plan = proto::Plan::default();
         plan.op_type = Some(proto::plan::OpType::Root(relation));
@@ -1392,7 +1392,7 @@ impl DataFrame {
     /// Mirrors `pyspark.sql.DataFrame.persist(storageLevel)`.
     pub fn persist(&self, storage_level: proto::StorageLevel) -> 
Result<DataFrame> {
         let persist = proto::analyze_plan_request::Persist {
-            relation: Some(self.relation()),
+            relation: Some(self.relation()?),
             storage_level: Some(storage_level),
         };
         let request = 
self.analyze_request(proto::analyze_plan_request::Analyze::Persist(persist));
@@ -1403,7 +1403,7 @@ impl DataFrame {
     /// Remove this DataFrame from cache. Mirrors 
`DataFrame.unpersist(blocking)`.
     pub fn unpersist(&self, blocking: bool) -> Result<DataFrame> {
         let unpersist = proto::analyze_plan_request::Unpersist {
-            relation: Some(self.relation()),
+            relation: Some(self.relation()?),
             blocking: Some(blocking),
         };
         let request =
@@ -1449,7 +1449,7 @@ impl DataFrame {
         storage_level: Option<proto::StorageLevel>,
     ) -> Result<DataFrame> {
         let mut cmd = proto::CheckpointCommand::default();
-        cmd.relation = Some(self.relation());
+        cmd.relation = Some(self.relation()?);
         cmd.local = local;
         cmd.eager = eager;
         cmd.storage_level = storage_level;
@@ -1505,7 +1505,7 @@ impl DataFrame {
     /// Build + execute a real `CreateDataFrameViewCommand` (was previously a
     /// silent no-op that passed the query relation through and never created 
a view).
     fn create_view(&self, name: &str, replace: bool, global: bool) -> 
Result<()> {
-        let input = self.relation();
+        let input = self.relation()?;
         let mut cmd = proto::CreateDataFrameViewCommand::default();
         cmd.input = Some(input);
         cmd.name = name.to_string();
@@ -1556,7 +1556,7 @@ impl DataFrame {
             }
         };
         let plan = proto::Plan {
-            op_type: Some(proto::plan::OpType::Root(self.relation())),
+            op_type: Some(proto::plan::OpType::Root(self.relation()?)),
         };
         let request = proto::AnalyzePlanRequest {
             session_id: self.session.client().session_id().to_string(),
@@ -1666,7 +1666,7 @@ impl DataFrame {
 
     /// Get the input files for this DataFrame. Mirrors 
`pyspark.sql.DataFrame.inputFiles`.
     pub fn input_files(&self) -> Result<Vec<String>> {
-        let relation = self.relation();
+        let relation = self.relation()?;
         let mut plan = proto::Plan::default();
         plan.op_type = Some(proto::plan::OpType::Root(relation));
         let mut inp = proto::analyze_plan_request::InputFiles::default();
@@ -2084,7 +2084,7 @@ impl DataFrame {
     /// Get the storage level of this DataFrame. Mirrors 
`DataFrame.storageLevel`.
     pub fn storage_level(&self) -> Result<proto::StorageLevel> {
         let get = proto::analyze_plan_request::GetStorageLevel {
-            relation: Some(self.relation()),
+            relation: Some(self.relation()?),
         };
         let request =
             
self.analyze_request(proto::analyze_plan_request::Analyze::GetStorageLevel(get));
@@ -2120,7 +2120,7 @@ impl DataFrame {
     /// Compute the server-side semantic hash of this DataFrame's logical plan,
     /// mirroring `DataFrame.semanticHash()` (an AnalyzePlan request).
     pub fn semantic_hash(&self) -> Result<i32> {
-        let relation = self.relation();
+        let relation = self.relation()?;
         let mut plan = proto::Plan::default();
         plan.op_type = Some(proto::plan::OpType::Root(relation));
         let mut request = proto::AnalyzePlanRequest::default();
@@ -2141,8 +2141,8 @@ impl DataFrame {
     /// Whether two DataFrames have the same semantics, mirroring
     /// `DataFrame.sameSemantics(other)` (a server-side AnalyzePlan 
comparison).
     pub fn same_semantics(&self, other: &DataFrame) -> Result<bool> {
-        let self_rel = self.relation();
-        let other_rel = other.relation();
+        let self_rel = self.relation()?;
+        let other_rel = other.relation()?;
         let mut target_plan = proto::Plan::default();
         target_plan.op_type = Some(proto::plan::OpType::Root(self_rel));
         let mut other_plan = proto::Plan::default();
@@ -2304,7 +2304,7 @@ impl DataFrame {
             analyze: Some(proto::analyze_plan_request::Analyze::IsStreaming(
                 proto::analyze_plan_request::IsStreaming {
                     plan: Some(proto::Plan {
-                        op_type: 
Some(proto::plan::OpType::Root(self.relation())),
+                        op_type: 
Some(proto::plan::OpType::Root(self.relation()?)),
                     }),
                 },
             )),
@@ -2482,7 +2482,7 @@ impl DataFrame {
 pub(crate) fn build_input_relation(
     plan: &Arc<LogicalPlan>,
     session: &SparkSession,
-) -> proto::Relation {
+) -> Result<proto::Relation> {
     crate::plan::relation_with_ids(plan, session.plan_ids())
 }
 
@@ -4523,6 +4523,29 @@ mod plan_construction_tests {
             .expect("failed to build session")
     }
 
+    #[test]
+    fn 
actions_of_a_plan_past_the_depth_bound_are_recursion_errors_without_a_request() 
{
+        // Offline: the plan is refused before any request, so no server is 
needed.
+        let spark = session();
+        let mut df = spark.range(10).unwrap();
+        for _ in 0..10_000 {
+            df = 
df.filter(crate::functions::col("id").gt(crate::column::lit(0)));
+        }
+        let errors = [
+            df.count().unwrap_err(),
+            df.collect().unwrap_err(),
+            df.schema().unwrap_err(),
+            df.explain_string("simple").unwrap_err(),
+        ];
+        for error in errors {
+            assert_eq!(
+                error.kind,
+                spark_connect_core::error::SparkErrorKind::RecursionError,
+                "{error}"
+            );
+        }
+    }
+
     #[test]
     fn is_local_only_for_a_local_relation_itself() {
         let spark = session();
@@ -4569,7 +4592,7 @@ mod plan_construction_tests {
             ..Default::default()
         }));
         assert!(!query.is_local());
-        let relation = build_input_relation(&query.plan, &spark);
+        let relation = build_input_relation(&query.plan, &spark).unwrap();
         match relation.rel_type {
             Some(RelType::Sql(sql)) => assert_eq!(sql.query, "SELECT 1"),
             other => panic!("expected the returned SQL relation, got 
{other:?}"),
@@ -4714,8 +4737,8 @@ mod plan_construction_tests {
 
         // As in PySpark, a shared node has one plan ID wherever it occurs, 
and serializing
         // the same plan again gives the same relation.
-        let first = build_input_relation(&joined.plan, &spark);
-        let second = build_input_relation(&joined.plan, &spark);
+        let first = build_input_relation(&joined.plan, &spark).unwrap();
+        let second = build_input_relation(&joined.plan, &spark).unwrap();
         assert_eq!(first, second);
         let ids = plan_ids_of(&first);
         assert_eq!(ids.len(), 5);
@@ -4881,18 +4904,21 @@ mod plan_construction_tests {
 
         let spark = session();
         let base = spark.range(3).unwrap().select(vec![col("id")]);
-        let base_relation = base.relation();
+        let base_relation = base.relation().unwrap();
         let derived = base.filter(col("id").gt(lit(1)));
-        let derived_relation = derived.relation();
+        let derived_relation = derived.relation().unwrap();
         let Some(proto::relation::RelType::Filter(filter)) = 
&derived_relation.rel_type else {
             panic!("expected filter");
         };
         assert_eq!(filter.input.as_deref(), Some(&base_relation));
-        assert_eq!(derived.relation(), derived_relation);
+        assert_eq!(derived.relation().unwrap(), derived_relation);
         // Separately built plans, even equal ones, are distinct nodes with 
distinct IDs.
         let other = spark.range(3).unwrap().select(vec![col("id")]);
         assert_eq!(other.plan.to_proto(), base.plan.to_proto());
-        let (mine, theirs) = (plan_ids_of(&base_relation), 
plan_ids_of(&other.relation()));
+        let (mine, theirs) = (
+            plan_ids_of(&base_relation),
+            plan_ids_of(&other.relation().unwrap()),
+        );
         assert!(mine.iter().all(|id| !theirs.contains(id)));
     }
 
@@ -4901,18 +4927,18 @@ mod plan_construction_tests {
         // A session of its own, so that other tests' plans do not change its 
entries.
         let spark = session().new_session();
         let kept = spark.range(1).unwrap();
-        let kept_ids = plan_ids_of(&kept.relation());
+        let kept_ids = plan_ids_of(&kept.relation().unwrap());
         let mut seen: std::collections::HashSet<i64> = 
kept_ids.iter().copied().collect();
         // Each plan is dropped at once, so pruning frees its allocation for a 
later plan to
         // reuse. A new node must still never get the ID of a dropped one.
         for end in 0..5000 {
-            for id in plan_ids_of(&spark.range(end).unwrap().relation()) {
+            for id in 
plan_ids_of(&spark.range(end).unwrap().relation().unwrap()) {
                 assert!(seen.insert(id), "plan ID {id} was assigned twice");
             }
             // With one live node, pruning keeps the map at most MIN_PRUNE_AT 
entries.
             assert!(spark.plan_ids().len() <= 1024, "{}", 
spark.plan_ids().len());
         }
-        assert_eq!(plan_ids_of(&kept.relation()), kept_ids);
+        assert_eq!(plan_ids_of(&kept.relation().unwrap()), kept_ids);
     }
 
     #[test]
@@ -4924,7 +4950,7 @@ mod plan_construction_tests {
         let mut seen = std::collections::HashSet::new();
         for end in 0..10 {
             for plans in [&one, &two] {
-                for id in plan_ids_of(&plans.range(end).unwrap().relation()) {
+                for id in 
plan_ids_of(&plans.range(end).unwrap().relation().unwrap()) {
                     assert!(seen.insert(id), "plan ID {id} was assigned 
twice");
                 }
             }
@@ -5051,7 +5077,7 @@ mod plan_construction_tests {
         let splits = df.random_split(vec![1.0, 0.0, 3.0], Some(42)).unwrap();
         assert_eq!(splits.len(), 3);
         for (split, (lower, upper)) in splits.iter().zip([(0.0, 0.25), (0.25, 
0.25), (0.25, 1.0)]) {
-            let Some(RelType::Sample(sample)) = split.relation().rel_type else 
{
+            let Some(RelType::Sample(sample)) = 
split.relation().unwrap().rel_type else {
                 panic!("expected a serialized Sample relation");
             };
             assert_eq!(sample.lower_bound, lower);
@@ -5196,7 +5222,7 @@ mod plan_construction_tests {
         let df2 = spark.range(5).unwrap();
         let e = || col("id").expression().clone();
         let ser = |d: &DataFrame| {
-            build_input_relation(&d.plan, &spark);
+            build_input_relation(&d.plan, &spark).unwrap();
         };
 
         ser(&df.select(vec![col("id")]));
@@ -5262,7 +5288,7 @@ mod plan_construction_tests {
         use crate::streaming::Trigger;
         let spark = session();
         let ser = |d: &DataFrame| {
-            build_input_relation(&d.plan, &spark);
+            build_input_relation(&d.plan, &spark).unwrap();
         };
         ser(&spark
             .read_stream()
@@ -5367,7 +5393,7 @@ mod plan_construction_tests {
 
         let spark = session();
         let ser = |d: &DataFrame| {
-            build_input_relation(&d.plan, &spark);
+            build_input_relation(&d.plan, &spark).unwrap();
         };
         let df = spark.range(5).unwrap();
         let df2 = spark.range(5).unwrap();
@@ -5421,7 +5447,7 @@ mod plan_construction_tests {
                 PythonUDFPayload::new(DataType::Integer, 205, vec![1], 
"3.11".to_string()),
             )
         };
-        let sent = |mapped: DataFrame| match mapped.relation().rel_type {
+        let sent = |mapped: DataFrame| match 
mapped.relation().unwrap().rel_type {
             Some(RelType::MapPartitions(map)) => (map.profile_id, 
map.is_barrier),
             other => panic!("expected MapPartitions, got {other:?}"),
         };
@@ -6014,7 +6040,7 @@ mod plan_id_column_tests {
                 JoinType::Inner,
             )
             .select(vec![left.col("id"), right.star(), 
left.col_regex("`i.*`")]);
-        let relation = joined.relation();
+        let relation = joined.relation().unwrap();
         let Some(RelType::Project(project)) = &relation.rel_type else {
             panic!("expected Project: {relation:?}");
         };
@@ -6100,7 +6126,7 @@ mod subquery_tests {
             .unwrap()
             .select(vec![col("id"), inner.scalar().alias("m")]);
 
-        let relation = df.relation();
+        let relation = df.relation().unwrap();
         let (root, references) = with_relations(&relation);
         assert_eq!(plan_id(&relation), Some(spark.plan_ids().id_of(&df.plan)));
         assert!(plan_id(root).is_some() && plan_id(root) != 
plan_id(&relation));
@@ -6118,9 +6144,9 @@ mod subquery_tests {
         );
         assert_eq!(references.len(), 1);
         assert_eq!(plan_id(&references[0]), Some(scalar.plan_id));
-        assert_eq!(references[0], inner.relation());
+        assert_eq!(references[0], inner.relation().unwrap());
         // The plan IDs are stable, as PySpark's.
-        assert_eq!(df.relation(), relation);
+        assert_eq!(df.relation().unwrap(), relation);
         // Without plan IDs, the relation is sent the same way.
         let Some(RelType::WithRelations(with)) = df.plan.to_proto().rel_type 
else {
             panic!("expected WithRelations");
@@ -6128,7 +6154,7 @@ mod subquery_tests {
         assert_eq!(with.references.len(), 1);
         // A plan without subqueries is sent as it is.
         assert!(matches!(
-            inner.relation().rel_type,
+            inner.relation().unwrap().rel_type,
             Some(RelType::Project(_))
         ));
     }
@@ -6146,7 +6172,7 @@ mod subquery_tests {
             .filter(col("id").isin_subquery(&filtered))
             .filter(t2.exists());
 
-        let relation = df.relation();
+        let relation = df.relation().unwrap();
         let (root, references) = with_relations(&relation);
         let Some(RelType::Filter(outer)) = &root.rel_type else {
             panic!("expected Filter: {root:?}");
@@ -6176,7 +6202,7 @@ mod subquery_tests {
         assert!(matches!(filtered_root.rel_type, Some(RelType::Filter(_))));
         assert_eq!(
             filtered_references,
-            std::slice::from_ref(&smallest.relation())
+            std::slice::from_ref(&smallest.relation().unwrap())
         );
     }
 
diff --git a/crates/spark-connect/src/merge.rs 
b/crates/spark-connect/src/merge.rs
index e7ad8918..dc9a10b6 100644
--- a/crates/spark-connect/src/merge.rs
+++ b/crates/spark-connect/src/merge.rs
@@ -126,7 +126,7 @@ impl MergeIntoWriter {
     pub fn merge(mut self) -> Result<()> {
         let cmd = proto::MergeIntoTableCommand {
             target_table_name: std::mem::take(&mut self.target_table),
-            source_table_plan: Some(build_input_relation(&self.source_plan, 
&self.session)),
+            source_table_plan: Some(build_input_relation(&self.source_plan, 
&self.session)?),
             merge_condition: Some(self.condition.to_proto()),
             match_actions: std::mem::take(&mut self.matched_actions),
             not_matched_actions: std::mem::take(&mut self.not_matched_actions),
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index d7d05ffa..cb38c927 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -310,17 +310,20 @@ pub trait Transformer: Send + Sync {
     }
 
     /// Build the MlRelation for this transformation.
-    fn build_ml_relation(&self, input: &DataFrame) -> proto::MlRelation {
+    fn build_ml_relation(
+        &self,
+        input: &DataFrame,
+    ) -> spark_connect_core::error::Result<proto::MlRelation> {
         let mut transform = proto::ml_relation::Transform::default();
         transform.operator = 
Some(proto::ml_relation::transform::Operator::Transformer(
             self.operator().to_proto(),
         ));
-        transform.input = Some(Box::new(input.relation()));
+        transform.input = Some(Box::new(input.relation()?));
         transform.params = Some(self.params().to_proto());
 
         let mut ml_relation = proto::MlRelation::default();
         ml_relation.ml_type = 
Some(proto::ml_relation::MlType::Transform(Box::new(transform)));
-        ml_relation
+        Ok(ml_relation)
     }
 }
 
@@ -357,7 +360,7 @@ fn evaluate_via_command(
     params: &Params,
     df: &DataFrame,
 ) -> spark_connect_core::error::Result<f64> {
-    let dataset = df.relation();
+    let dataset = df.relation()?;
     let evaluate = proto::ml_command::Evaluate {
         evaluator: Some(operator.to_proto()),
         params: Some(params.to_proto()),
@@ -511,7 +514,10 @@ impl Transformer for StandardScalerModel {
         &mut self.params
     }
 
-    fn build_ml_relation(&self, input: &DataFrame) -> proto::MlRelation {
+    fn build_ml_relation(
+        &self,
+        input: &DataFrame,
+    ) -> spark_connect_core::error::Result<proto::MlRelation> {
         self.cached.build_ml_relation(input, &self.params)
     }
 
@@ -595,7 +601,7 @@ impl Transformer for VectorAssembler {
     }
 
     fn transform_impl(&mut self, df: &DataFrame) -> 
spark_connect_core::error::Result<DataFrame> {
-        let ml_relation = self.build_ml_relation(df);
+        let ml_relation = self.build_ml_relation(df)?;
         let mut relation = proto::Relation::default();
         relation.common = Some(proto::RelationCommon::default());
         relation.rel_type = 
Some(proto::relation::RelType::MlRelation(Box::new(ml_relation)));
@@ -724,7 +730,10 @@ impl Transformer for StringIndexerModel {
         &mut self.params
     }
 
-    fn build_ml_relation(&self, input: &DataFrame) -> proto::MlRelation {
+    fn build_ml_relation(
+        &self,
+        input: &DataFrame,
+    ) -> spark_connect_core::error::Result<proto::MlRelation> {
         self.cached.build_ml_relation(input, &self.params)
     }
 
@@ -855,7 +864,10 @@ impl Transformer for MaxAbsScalerModel {
         &mut self.params
     }
 
-    fn build_ml_relation(&self, input: &DataFrame) -> proto::MlRelation {
+    fn build_ml_relation(
+        &self,
+        input: &DataFrame,
+    ) -> spark_connect_core::error::Result<proto::MlRelation> {
         self.cached.build_ml_relation(input, &self.params)
     }
 
@@ -880,7 +892,7 @@ fn fit_via_command(
         command: Some(proto::ml_command::Command::Fit(proto::ml_command::Fit {
             estimator: Some(operator.to_proto()),
             params: Some(params.to_proto()),
-            dataset: Some(df.relation()),
+            dataset: Some(df.relation()?),
         })),
     };
     let responses = crate::dataframe::execute_command_collect(
@@ -953,19 +965,23 @@ impl CachedModel {
         }
     }
 
-    fn build_ml_relation(&self, df: &DataFrame, params: &Params) -> 
proto::MlRelation {
-        proto::MlRelation {
+    fn build_ml_relation(
+        &self,
+        df: &DataFrame,
+        params: &Params,
+    ) -> spark_connect_core::error::Result<proto::MlRelation> {
+        Ok(proto::MlRelation {
             ml_type: Some(proto::ml_relation::MlType::Transform(Box::new(
                 proto::ml_relation::Transform {
                     operator: 
Some(proto::ml_relation::transform::Operator::ObjRef(
                         self.0.model_ref.clone(),
                     )),
-                    input: Some(Box::new(df.relation())),
+                    input: Some(Box::new(df.relation()?)),
                     params: Some(params.to_proto()),
                 },
             ))),
             ..Default::default()
-        }
+        })
     }
 
     fn transform(
@@ -980,7 +996,7 @@ impl CachedModel {
         }
         let relation = proto::Relation {
             rel_type: Some(proto::relation::RelType::MlRelation(Box::new(
-                self.build_ml_relation(df, params),
+                self.build_ml_relation(df, params)?,
             ))),
             ..Default::default()
         };
@@ -1145,7 +1161,10 @@ impl Transformer for LogisticRegressionModel {
         &mut self.params
     }
 
-    fn build_ml_relation(&self, input: &DataFrame) -> proto::MlRelation {
+    fn build_ml_relation(
+        &self,
+        input: &DataFrame,
+    ) -> spark_connect_core::error::Result<proto::MlRelation> {
         self.cached.build_ml_relation(input, &self.params)
     }
 
@@ -1328,7 +1347,10 @@ impl Transformer for LinearSVCModel {
         &mut self.params
     }
 
-    fn build_ml_relation(&self, input: &DataFrame) -> proto::MlRelation {
+    fn build_ml_relation(
+        &self,
+        input: &DataFrame,
+    ) -> spark_connect_core::error::Result<proto::MlRelation> {
         self.cached.build_ml_relation(input, &self.params)
     }
 
@@ -1522,7 +1544,10 @@ impl Transformer for LinearRegressionModel {
         &mut self.params
     }
 
-    fn build_ml_relation(&self, input: &DataFrame) -> proto::MlRelation {
+    fn build_ml_relation(
+        &self,
+        input: &DataFrame,
+    ) -> spark_connect_core::error::Result<proto::MlRelation> {
         self.cached.build_ml_relation(input, &self.params)
     }
 
@@ -1703,7 +1728,10 @@ impl Transformer for KMeansModel {
         &mut self.params
     }
 
-    fn build_ml_relation(&self, input: &DataFrame) -> proto::MlRelation {
+    fn build_ml_relation(
+        &self,
+        input: &DataFrame,
+    ) -> spark_connect_core::error::Result<proto::MlRelation> {
         self.cached.build_ml_relation(input, &self.params)
     }
 
@@ -1960,7 +1988,7 @@ impl Transformer for PipelineModel {
     }
 
     fn transform_impl(&mut self, df: &DataFrame) -> 
spark_connect_core::error::Result<DataFrame> {
-        let ml_relation = self.build_ml_relation(df);
+        let ml_relation = self.build_ml_relation(df)?;
         let mut relation = proto::Relation::default();
         relation.common = Some(proto::RelationCommon::default());
         relation.rel_type = 
Some(proto::relation::RelType::MlRelation(Box::new(ml_relation)));
@@ -2151,7 +2179,7 @@ impl Transformer for CrossValidatorModel {
         &mut self.params
     }
     fn transform_impl(&mut self, df: &DataFrame) -> 
spark_connect_core::error::Result<DataFrame> {
-        let ml_relation = self.build_ml_relation(df);
+        let ml_relation = self.build_ml_relation(df)?;
         let mut relation = proto::Relation::default();
         relation.common = Some(proto::RelationCommon::default());
         relation.rel_type = 
Some(proto::relation::RelType::MlRelation(Box::new(ml_relation)));
@@ -2687,7 +2715,7 @@ mod tests {
         assert_eq!(model.operator.op_type, OperatorType::Model);
         let data = session.range(3).unwrap();
         let transformed = model.transform(&data).unwrap();
-        let relation = transformed.relation();
+        let relation = transformed.relation().unwrap();
         let Some(proto::relation::RelType::MlRelation(ml)) = relation.rel_type 
else {
             panic!("expected an ML relation");
         };
@@ -2707,7 +2735,7 @@ mod tests {
             .unwrap()
             .params
             .contains_key("predictionCol"));
-        assert_eq!(*transform.input.unwrap(), data.relation());
+        assert_eq!(*transform.input.unwrap(), data.relation().unwrap());
         let _ = model.clone_box();
     }
 
@@ -2802,7 +2830,7 @@ mod tests {
         assert_eq!(model.operator().op_type, OperatorType::Model);
         let df = session.range(2).unwrap();
         let proto::ml_relation::MlType::Transform(transform) =
-            model.build_ml_relation(&df).ml_type.unwrap()
+            model.build_ml_relation(&df).unwrap().ml_type.unwrap()
         else {
             panic!("expected transform");
         };
@@ -2814,7 +2842,7 @@ mod tests {
                 },
             ))
         );
-        assert_eq!(*transform.input.unwrap(), df.relation());
+        assert_eq!(*transform.input.unwrap(), df.relation().unwrap());
         assert!(model
             .transform(&session.new_session().range(2).unwrap())
             .is_err());
@@ -2873,7 +2901,7 @@ mod tests {
         assert_eq!(model.operator().op_type, OperatorType::Model);
         let df = session.range(2).unwrap();
         let proto::ml_relation::MlType::Transform(t) =
-            model.build_ml_relation(&df).ml_type.unwrap()
+            model.build_ml_relation(&df).unwrap().ml_type.unwrap()
         else {
             panic!("transform")
         };
@@ -2885,7 +2913,7 @@ mod tests {
                 }
             ))
         );
-        assert_eq!(*t.input.unwrap(), df.relation());
+        assert_eq!(*t.input.unwrap(), df.relation().unwrap());
         assert!(t.params.unwrap().params.contains_key("predictionCol"));
         assert!(model
             .transform(&session.new_session().range(2).unwrap())
@@ -2943,7 +2971,7 @@ mod tests {
         assert_eq!(fallback.operator().uid, estimator.operator().uid);
         let df = session.range(2).unwrap();
         let proto::ml_relation::MlType::Transform(t) =
-            model.build_ml_relation(&df).ml_type.unwrap()
+            model.build_ml_relation(&df).unwrap().ml_type.unwrap()
         else {
             panic!("transform")
         };
@@ -2955,7 +2983,7 @@ mod tests {
                 }
             ))
         );
-        assert_eq!(*t.input.unwrap(), df.relation());
+        assert_eq!(*t.input.unwrap(), df.relation().unwrap());
         assert_eq!(t.params.unwrap(), estimator.params().to_proto());
         assert!(model
             .transform(&session.new_session().range(2).unwrap())
diff --git a/crates/spark-connect/src/pipelines.rs 
b/crates/spark-connect/src/pipelines.rs
index 3aad22bf..ae272c34 100644
--- a/crates/spark-connect/src/pipelines.rs
+++ b/crates/spark-connect/src/pipelines.rs
@@ -148,7 +148,7 @@ pub fn define_flow(
     sql_conf: HashMap<String, String>,
     source_code_location: Option<proto::SourceCodeLocation>,
 ) -> Result<()> {
-    let relation = relation_df.relation();
+    let relation = relation_df.relation()?;
     let details =
         
define_flow::Details::RelationFlowDetails(define_flow::WriteRelationFlowDetails 
{
             relation: Some(relation),
diff --git a/crates/spark-connect/src/plan.rs b/crates/spark-connect/src/plan.rs
index 098b5bdb..cac08e4a 100644
--- a/crates/spark-connect/src/plan.rs
+++ b/crates/spark-connect/src/plan.rs
@@ -700,7 +700,7 @@ pub(crate) fn resolve_relation(relation: &mut 
proto::Relation) -> Result<()> {
             let (node, ids) = placeholder_target(marker).ok_or_else(|| {
                 SparkError::value_msg("a placeholder of a DataFrame that no 
longer exists")
             })?;
-            *relation = relation_with_ids(&node, &ids);
+            *relation = relation_with_ids(&node, &ids)?;
             return Ok(());
         }
     }
@@ -775,10 +775,53 @@ 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
+};
+
 /// Serialize a shared plan node for a request: the node and every node below 
it carry
-/// their stable plan IDs.
-pub(crate) fn relation_with_ids(node: &Arc<LogicalPlan>, ids: &PlanIds) -> 
proto::Relation {
-    relation_of(node, Some(ids))
+/// 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.
+pub(crate) fn relation_with_ids(node: &Arc<LogicalPlan>, ids: &PlanIds) -> 
Result<proto::Relation> {
+    let depth = node.depth();
+    if depth > MAX_PLAN_DEPTH {
+        return Err(SparkError::recursion_msg(format!(
+            "maximum recursion depth exceeded while serializing a plan of 
{depth} levels; \
+             a plan may be at most {MAX_PLAN_DEPTH} levels deep"
+        )));
+    }
+    if depth <= INLINE_PLAN_DEPTH {
+        return Ok(relation_of(node, Some(ids)));
+    }
+    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)))
+            .map_err(|e| SparkError::connect_msg(format!("cannot serialize the 
plan: {e}")))?;
+        match serializing.join() {
+            Ok(relation) => Ok(relation),
+            Err(panic) => std::panic::resume_unwind(panic),
+        }
+    })
 }
 
 /// Serialize a child node, with its stable plan ID when `ids` is given.
@@ -873,7 +916,165 @@ fn relation_with_references(
     }
 }
 
+/// The plans that `$plan` reads, as references of the same mutability as 
`$plan`.
+macro_rules! inputs_of {
+    ($plan:expr) => {{
+        let mut inputs = Vec::new();
+        match $plan {
+            LogicalPlan::Project { input, .. }
+            | LogicalPlan::Filter { input, .. }
+            | LogicalPlan::Aggregate { input, .. }
+            | LogicalPlan::Limit { input, .. }
+            | LogicalPlan::Offset { input, .. }
+            | LogicalPlan::Tail { input, .. }
+            | LogicalPlan::ShowString { input, .. }
+            | LogicalPlan::HtmlString { input, .. }
+            | LogicalPlan::Deduplicate { input, .. }
+            | LogicalPlan::Sort { input, .. }
+            | LogicalPlan::Sample { input, .. }
+            | LogicalPlan::Repartition { input, .. }
+            | LogicalPlan::RepartitionByExpression { input, .. }
+            | LogicalPlan::WithColumns { input, .. }
+            | LogicalPlan::WithColumnMetadata { input, .. }
+            | LogicalPlan::WithColumnsRenamed { input, .. }
+            | LogicalPlan::Drop { input, .. }
+            | LogicalPlan::ToDF { input, .. }
+            | LogicalPlan::ToSchema { input, .. }
+            | LogicalPlan::Hint { input, .. }
+            | LogicalPlan::Parse { input, .. }
+            | LogicalPlan::Unpivot { input, .. }
+            | LogicalPlan::NAFill { input, .. }
+            | LogicalPlan::NAFillColumns { input, .. }
+            | LogicalPlan::NADrop { input, .. }
+            | LogicalPlan::NAReplace { input, .. }
+            | LogicalPlan::Describe { input, .. }
+            | LogicalPlan::Summary { input, .. }
+            | LogicalPlan::ColRegex { input, .. }
+            | LogicalPlan::SubqueryAlias { input, .. }
+            | LogicalPlan::WithWatermark { input, .. }
+            | LogicalPlan::RepartitionByRange { input, .. }
+            | LogicalPlan::StatCrosstab { input, .. }
+            | LogicalPlan::StatFreqItems { input, .. }
+            | LogicalPlan::StatApproxQuantile { input, .. }
+            | LogicalPlan::StatCorr { input, .. }
+            | LogicalPlan::StatCov { input, .. }
+            | LogicalPlan::StatSampleBy { input, .. }
+            | LogicalPlan::Observe { input, .. }
+            | LogicalPlan::MlTransform { input, .. }
+            | LogicalPlan::Transpose { input, .. }
+            | LogicalPlan::MapPartitions { input, .. }
+            | LogicalPlan::ApplyInPandasWithState { input, .. } => 
inputs.push(input),
+            LogicalPlan::Join { left, right, .. }
+            | LogicalPlan::LateralJoin { left, right, .. }
+            | LogicalPlan::SetOperation { left, right, .. }
+            | LogicalPlan::Zip { left, right, .. }
+            | LogicalPlan::AsOfJoin { left, right, .. }
+            | LogicalPlan::NearestByJoin { left, right, .. } => {
+                inputs.push(left);
+                inputs.push(right);
+            }
+            LogicalPlan::CoGroupMap { input, other, .. } => {
+                inputs.push(input);
+                inputs.push(other);
+            }
+            LogicalPlan::GroupMap {
+                input,
+                initial_input,
+                ..
+            } => {
+                inputs.push(input);
+                inputs.extend(initial_input);
+            }
+            LogicalPlan::WithRelations { root, references } => {
+                inputs.push(root);
+                inputs.extend(references);
+            }
+            LogicalPlan::Range { .. }
+            | LogicalPlan::Sql { .. }
+            | LogicalPlan::Raw { .. }
+            | LogicalPlan::LocalRelation { .. }
+            | LogicalPlan::ChunkedCachedLocalRelation { .. }
+            | LogicalPlan::CachedRemoteRelation { .. }
+            | LogicalPlan::CachedRelation { .. }
+            | LogicalPlan::Read { .. }
+            | LogicalPlan::RelationChanges { .. }
+            | LogicalPlan::UnresolvedTableValuedFunction { .. }
+            | LogicalPlan::Catalog { .. }
+            | LogicalPlan::CommonInlineUdtf { .. } => {}
+        }
+        inputs
+    }};
+}
+
+/// A leaf that a dropped node leaves in place of each of its inputs, so that 
the inputs are
+/// dropped one at a time rather than each inside the drop of the node above 
it.
+static DROPPED_INPUT: LazyLock<Arc<LogicalPlan>> = LazyLock::new(|| {
+    Arc::new(LogicalPlan::Range {
+        start: 0,
+        end: 0,
+        step: 1,
+        num_partitions: None,
+    })
+});
+
+impl Drop for LogicalPlan {
+    /// Drop the plans below this one that nothing else holds, without 
recursing: a plan of
+    /// many levels would otherwise overflow the stack of the thread that 
drops it.
+    fn drop(&mut self) {
+        let mut pending: Vec<Arc<LogicalPlan>> = Vec::new();
+        let take_inputs = |plan: &mut LogicalPlan, pending: &mut 
Vec<Arc<LogicalPlan>>| {
+            for input in inputs_of!(plan) {
+                if !Arc::ptr_eq(input, &DROPPED_INPUT) {
+                    pending.push(std::mem::replace(input, 
Arc::clone(&DROPPED_INPUT)));
+                }
+            }
+        };
+        take_inputs(self, &mut pending);
+        while let Some(input) = pending.pop() {
+            if let Some(mut plan) = Arc::into_inner(input) {
+                take_inputs(&mut plan, &mut pending);
+            }
+        }
+    }
+}
+
 impl LogicalPlan {
+    /// The plans that this one reads directly.
+    fn inputs(&self) -> Vec<&Arc<LogicalPlan>> {
+        inputs_of!(self)
+    }
+
+    /// The number of levels of this plan: one for a leaf, and one more than 
its deepest input
+    /// otherwise. Computed without recursing, and once for each node that 
several plans share.
+    pub fn depth(&self) -> usize {
+        let mut depths: HashMap<*const LogicalPlan, usize> = HashMap::new();
+        let mut pending: Vec<(&LogicalPlan, bool)> = vec![(self, false)];
+        while let Some((plan, inputs_done)) = pending.pop() {
+            let key: *const LogicalPlan = plan;
+            if depths.contains_key(&key) {
+                continue;
+            }
+            let inputs = plan.inputs();
+            if inputs_done {
+                let deepest = inputs
+                    .iter()
+                    .map(|input| depths[&Arc::as_ptr(input)])
+                    .max()
+                    .unwrap_or(0);
+                depths.insert(key, deepest + 1);
+            } else {
+                pending.push((plan, true));
+                pending.extend(
+                    inputs
+                        .into_iter()
+                        .filter(|input| 
!depths.contains_key(&Arc::as_ptr(input)))
+                        .map(|input| (input.as_ref(), false)),
+                );
+            }
+        }
+        depths[&(self as *const LogicalPlan)]
+    }
+
     /// Convert this logical plan to a `spark.connect.Relation` protobuf, 
without plan IDs.
     pub fn to_proto(&self) -> proto::Relation {
         relation_with_references(self, None, None)
@@ -2628,7 +2829,7 @@ mod with_relations_tests {
             root: Arc::new(sql("SELECT * FROM v")),
             references: vec![Arc::new(subquery_alias(df.clone(), "v"))],
         });
-        let relation = relation_with_ids(&plan, &ids);
+        let relation = relation_with_ids(&plan, &ids).unwrap();
         let Some(proto::relation::RelType::WithRelations(with)) = 
&relation.rel_type else {
             panic!("expected WithRelations: {relation:?}");
         };
@@ -2743,7 +2944,7 @@ mod placeholder_tests {
                     limit: 3,
                 });
             }
-            let relation = relation_with_ids(&node, &ids);
+            let relation = relation_with_ids(&node, &ids).unwrap();
             let shallow = placeholder(&node, &ids);
             assert!(shallow.encoded_len() < 128, "{}", shallow.encoded_len());
             let mut resolved = transform_of(shallow.clone());
@@ -2773,7 +2974,7 @@ mod placeholder_tests {
     fn 
placeholders_resolve_in_every_position_that_the_ml_plans_build_over_their_inputs()
 {
         let ids = Arc::new(PlanIds::new());
         let node = Arc::new(range(0, 3, 1));
-        let relation = relation_with_ids(&node, &ids);
+        let relation = relation_with_ids(&node, &ids).unwrap();
         let shallow = placeholder(&node, &ids);
         let fetch = || proto::Fetch {
             obj_ref: None,
@@ -2869,7 +3070,7 @@ mod placeholder_tests {
     fn the_ml_commands_resolve_their_datasets_and_fetched_arguments() {
         let ids = Arc::new(PlanIds::new());
         let node = Arc::new(range(0, 3, 1));
-        let relation = relation_with_ids(&node, &ids);
+        let relation = relation_with_ids(&node, &ids).unwrap();
         let shallow = placeholder(&node, &ids);
         let command = |ml_command: proto::ml_command::Command| proto::Command {
             command_type: 
Some(proto::command::CommandType::MlCommand(proto::MlCommand {
@@ -2941,7 +3142,7 @@ mod placeholder_tests {
     fn relations_without_placeholders_are_left_as_they_are() {
         let ids = Arc::new(PlanIds::new());
         let node = Arc::new(range(0, 3, 1));
-        let mut relation = relation_with_ids(&node, &ids);
+        let mut relation = relation_with_ids(&node, &ids).unwrap();
         let before = relation.clone();
         resolve_relation(&mut relation).unwrap();
         assert_eq!(relation, before);
@@ -2976,3 +3177,109 @@ mod placeholder_tests {
         assert!(error.to_string().contains("no marker"), "{error}");
     }
 }
+
+#[cfg(test)]
+mod deep_plan_tests {
+    use super::*;
+    use spark_connect_core::error::SparkErrorKind;
+
+    /// A plan of `levels` levels: a range under limits.
+    fn chain(levels: usize) -> Arc<LogicalPlan> {
+        let mut plan = Arc::new(range(0, 10, 1));
+        for _ in 1..levels {
+            plan = Arc::new(limit(plan, 1));
+        }
+        plan
+    }
+
+    /// Run `f` on a thread with a stack of 512 KiB, the smallest that the 
client supports.
+    fn on_a_small_stack<T: Send>(f: impl FnOnce() -> T + Send) -> T {
+        std::thread::scope(|scope| {
+            std::thread::Builder::new()
+                .stack_size(512 << 10)
+                .spawn_scoped(scope, f)
+                .unwrap()
+                .join()
+                .unwrap()
+        })
+    }
+
+    /// How many relations are nested in `relation`, following the inputs of 
limits.
+    fn nested_limits(relation: &proto::Relation) -> usize {
+        let mut levels = 1;
+        let mut relation = relation;
+        while let Some(proto::relation::RelType::Limit(limit)) = 
&relation.rel_type {
+            relation = limit.input.as_deref().expect("input");
+            levels += 1;
+        }
+        levels
+    }
+
+    #[test]
+    fn depth_counts_the_levels_of_the_deepest_input() {
+        assert_eq!(chain(1).depth(), 1);
+        assert_eq!(chain(5).depth(), 5);
+        let with = LogicalPlan::WithRelations {
+            root: chain(3),
+            references: vec![chain(2), chain(7)],
+        };
+        assert_eq!(with.depth(), 8);
+    }
+
+    #[test]
+    fn depth_visits_an_input_that_plans_share_once() {
+        // Each level refers to the one below twice: 2^64 paths, but 65 nodes.
+        let mut plan = Arc::new(range(0, 10, 1));
+        for _ in 0..64 {
+            plan = Arc::new(LogicalPlan::WithRelations {
+                root: Arc::clone(&plan),
+                references: vec![plan],
+            });
+        }
+        assert_eq!(plan.depth(), 65);
+    }
+
+    #[test]
+    fn a_plan_at_the_bound_is_serialized_on_a_thread_with_a_small_stack() {
+        let plan = chain(MAX_PLAN_DEPTH);
+        let ids = PlanIds::new();
+        let relation = on_a_small_stack(|| relation_with_ids(&plan, 
&ids).unwrap());
+        assert_eq!(nested_limits(&relation), MAX_PLAN_DEPTH);
+    }
+
+    #[test]
+    fn a_plan_past_the_bound_is_a_recursion_error_as_in_pyspark() {
+        for levels in [MAX_PLAN_DEPTH + 1, 2_000, 100_000] {
+            let plan = chain(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(&format!("a plan of {levels} levels")),
+                "{error}"
+            );
+        }
+    }
+
+    #[test]
+    fn dropping_a_deep_plan_does_not_overflow_a_small_stack() {
+        on_a_small_stack(|| std::mem::drop(chain(1_000_000)));
+    }
+
+    #[test]
+    fn dropping_a_plan_keeps_the_inputs_that_another_plan_holds() {
+        let shared = chain(10);
+        let other = Arc::new(limit(Arc::clone(&shared), 1));
+        std::mem::drop(chain(3));
+        std::mem::drop(Arc::new(limit(Arc::clone(&shared), 1)));
+        assert_eq!(shared.depth(), 10);
+        assert_eq!(other.depth(), 11);
+        let relation = relation_with_ids(&other, &PlanIds::new()).unwrap();
+        assert_eq!(nested_limits(&relation), 11);
+    }
+}
diff --git a/crates/spark-connect/src/readwriter.rs 
b/crates/spark-connect/src/readwriter.rs
index 5680f360..1e6a8bdd 100644
--- a/crates/spark-connect/src/readwriter.rs
+++ b/crates/spark-connect/src/readwriter.rs
@@ -421,7 +421,7 @@ impl DataFrameWriter {
             ));
         }
         let mut op = proto::WriteOperation::default();
-        op.input = Some(build_input_relation(&self.input_plan, &self.session));
+        op.input = Some(build_input_relation(&self.input_plan, 
&self.session)?);
         op.source = self.format.clone();
         op.mode = self.mode.to_proto();
         op.sort_column_names = self.sort_cols.clone();
@@ -609,7 +609,7 @@ impl DataFrameWriterV2 {
         overwrite_condition: Option<proto::Expression>,
     ) -> Result<proto::WriteOperationV2> {
         let mut op = proto::WriteOperationV2::default();
-        op.input = Some(build_input_relation(&self.input_plan, &self.session));
+        op.input = Some(build_input_relation(&self.input_plan, 
&self.session)?);
         op.table_name = self.table_name.clone();
         op.provider = self.provider.clone();
         op.partitioning_columns = self.partition_cols.iter().map(|c| 
c.to_proto()).collect();
@@ -1000,6 +1000,7 @@ mod tests {
             .parse(format, &strings)
             .unwrap()
             .relation()
+            .unwrap()
             .rel_type
         {
             Some(RelType::Parse(parse)) => parse,
diff --git a/crates/spark-connect/src/session.rs 
b/crates/spark-connect/src/session.rs
index b450b133..3f5083f3 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -542,7 +542,7 @@ impl SparkSession {
         // returns a relation of its result; for a query it returns the 
query's relation, which
         // then runs at an action.
         let command = proto::SqlCommand {
-            input: Some(crate::dataframe::build_input_relation(&plan, self)),
+            input: Some(crate::dataframe::build_input_relation(&plan, self)?),
             ..Default::default()
         };
         let responses = crate::dataframe::execute_command_collect(
diff --git a/crates/spark-connect/src/streaming.rs 
b/crates/spark-connect/src/streaming.rs
index 2128a315..ff7a2c7c 100644
--- a/crates/spark-connect/src/streaming.rs
+++ b/crates/spark-connect/src/streaming.rs
@@ -431,7 +431,7 @@ impl DataStreamWriter {
         write_op.input = Some(crate::plan::relation_with_ids(
             &self.plan,
             self.session.plan_ids(),
-        ));
+        )?);
 
         if let Some(fmt) = &self.format {
             write_op.format = fmt.clone();
diff --git a/crates/spark-connect/tests/arrow_map_input.rs 
b/crates/spark-connect/tests/arrow_map_input.rs
index a077c9a5..53af687d 100644
--- a/crates/spark-connect/tests/arrow_map_input.rs
+++ b/crates/spark-connect/tests/arrow_map_input.rs
@@ -131,7 +131,7 @@ fn default_arrow_maps_round_trip_inline_and_chunked() {
             .0
             .create_dataframe_from_arrow(vec![input.slice(0, 2), 
input.slice(2, 2)], None)
             .unwrap();
-        let relation = dataframe.to_relation();
+        let relation = dataframe.to_relation().unwrap();
         match (chunked, relation.rel_type) {
             (true, Some(RelType::ChunkedCachedLocalRelation(local))) => {
                 assert!(
@@ -173,7 +173,7 @@ fn 
zero_row_arrow_maps_keep_a_canonical_header_and_analyze_on_spark() {
         .0
         .create_dataframe_from_arrow(vec![input().slice(0, 0)], None)
         .unwrap();
-    let Some(RelType::LocalRelation(local)) = dataframe.to_relation().rel_type 
else {
+    let Some(RelType::LocalRelation(local)) = 
dataframe.to_relation().unwrap().rel_type else {
         panic!("zero rows must use an inline relation");
     };
     let reader = StreamReader::try_new(Cursor::new(local.data.unwrap()), 
None).unwrap();
diff --git a/crates/spark-connect/tests/e2e_coverage.rs 
b/crates/spark-connect/tests/e2e_coverage.rs
index 88a518d8..b5a8665d 100644
--- a/crates/spark-connect/tests/e2e_coverage.rs
+++ b/crates/spark-connect/tests/e2e_coverage.rs
@@ -1606,8 +1606,12 @@ fn 
logistic_regression_fits_and_predicts_with_cached_models() {
     let mut first = estimator.fit(&training).expect("train first model");
     let flipped = training.with_column("target", lit(1) - col("target"));
     let mut second = estimator.fit(&flipped).expect("train opposite labels");
-    let first_operator = first.build_ml_relation(&held_out).ml_type.unwrap();
-    let second_operator = second.build_ml_relation(&held_out).ml_type.unwrap();
+    let first_operator = 
first.build_ml_relation(&held_out).unwrap().ml_type.unwrap();
+    let second_operator = second
+        .build_ml_relation(&held_out)
+        .unwrap()
+        .ml_type
+        .unwrap();
     let model_ref = |kind: spark_connect_proto::ml_relation::MlType| {
         let spark_connect_proto::ml_relation::MlType::Transform(t) = kind else 
{
             panic!("expected transform");
diff --git a/crates/spark-connect/tests/e2e_dataframe.rs 
b/crates/spark-connect/tests/e2e_dataframe.rs
index f69e0251..7abaedc2 100644
--- a/crates/spark-connect/tests/e2e_dataframe.rs
+++ b/crates/spark-connect/tests/e2e_dataframe.rs
@@ -600,7 +600,7 @@ fn 
a_dropped_checkpoint_releases_its_relation_on_the_server() {
     let s = session();
     // checkpoint() needs a checkpoint directory, which the test server does 
not set.
     let checkpoint = s.range(5).unwrap().local_checkpoint().unwrap();
-    let relation = checkpoint.to_relation();
+    let relation = checkpoint.to_relation().unwrap();
     assert_eq!(checkpoint.count().unwrap(), 5);
     drop(checkpoint);
     wait_until_relation_is_released(&s, &relation);
@@ -615,7 +615,7 @@ fn 
a_checkpoint_stays_while_a_dataframe_derived_from_it_is_alive() {
     }
     let s = session();
     let checkpoint = s.range(5).unwrap().local_checkpoint().unwrap();
-    let relation = checkpoint.to_relation();
+    let relation = checkpoint.to_relation().unwrap();
     let derived = checkpoint.filter(col("id").gt(lit(1)));
     drop(checkpoint);
     assert_eq!(derived.count().unwrap(), 3);
diff --git a/crates/spark-connect/tests/e2e_kmeans.rs 
b/crates/spark-connect/tests/e2e_kmeans.rs
index 569051c4..684d11d2 100644
--- a/crates/spark-connect/tests/e2e_kmeans.rs
+++ b/crates/spark-connect/tests/e2e_kmeans.rs
@@ -94,7 +94,7 @@ fn 
kmeans_learns_distinct_models_and_keeps_lazy_predictions_alive() {
     let mut second = estimator.fit(&shifted).unwrap();
     let object_id = |model: &dyn spark_connect::ml::Model| {
         let spark_connect_proto::ml_relation::MlType::Transform(t) =
-            model.build_ml_relation(&held_out).ml_type.unwrap()
+            model.build_ml_relation(&held_out).unwrap().ml_type.unwrap()
         else {
             panic!("transform")
         };
diff --git a/crates/spark-connect/tests/e2e_linear_regression.rs 
b/crates/spark-connect/tests/e2e_linear_regression.rs
index 175e1c0e..d0b55a8a 100644
--- a/crates/spark-connect/tests/e2e_linear_regression.rs
+++ b/crates/spark-connect/tests/e2e_linear_regression.rs
@@ -84,7 +84,7 @@ fn 
linear_regression_fits_different_lines_and_keeps_lazy_predictions_alive() {
         .unwrap();
     let object_id = |model: &dyn spark_connect::ml::Model| {
         let spark_connect_proto::ml_relation::MlType::Transform(t) =
-            model.build_ml_relation(&held_out).ml_type.unwrap()
+            model.build_ml_relation(&held_out).unwrap().ml_type.unwrap()
         else {
             panic!("transform")
         };
diff --git a/crates/spark-connect/tests/e2e_linear_svc.rs 
b/crates/spark-connect/tests/e2e_linear_svc.rs
index 1a1cbc76..1b4f8e61 100644
--- a/crates/spark-connect/tests/e2e_linear_svc.rs
+++ b/crates/spark-connect/tests/e2e_linear_svc.rs
@@ -76,7 +76,7 @@ fn 
linear_svc_fits_separate_models_and_predicts_on_unseen_data() {
         .unwrap();
     let object_id = |model: &dyn spark_connect::ml::Model| {
         let spark_connect_proto::ml_relation::MlType::Transform(t) =
-            model.build_ml_relation(&held_out).ml_type.unwrap()
+            model.build_ml_relation(&held_out).unwrap().ml_type.unwrap()
         else {
             panic!("transform")
         };
diff --git a/crates/spark-connect/tests/execute_plan_hook.rs 
b/crates/spark-connect/tests/execute_plan_hook.rs
index f186fe52..3748d231 100644
--- a/crates/spark-connect/tests/execute_plan_hook.rs
+++ b/crates/spark-connect/tests/execute_plan_hook.rs
@@ -84,7 +84,7 @@ fn 
the_request_of_a_hook_is_sent_with_the_operation_id_of_the_original() {
     let Some(session) = live() else {
         return;
     };
-    let replacement = session.range(5).unwrap().to_relation();
+    let replacement = session.range(5).unwrap().to_relation().unwrap();
     let operation_ids: Arc<Mutex<Vec<Option<String>>>> = Arc::default();
     let seen = Arc::clone(&operation_ids);
     let hook: ExecutePlanHook = Arc::new(move |mut request| {
diff --git a/crates/spark-connect/tests/raw_relation.rs 
b/crates/spark-connect/tests/raw_relation.rs
index c472dff8..ebdb8d7a 100644
--- a/crates/spark-connect/tests/raw_relation.rs
+++ b/crates/spark-connect/tests/raw_relation.rs
@@ -72,7 +72,7 @@ fn sql_relation(query: &str) -> proto::Relation {
 #[test]
 fn raw_relations_are_sent_as_they_are_with_a_plan_id_of_the_session() {
     let df = DataFrame::from_relation(offline(), sql_relation("SELECT 1 AS 
a"), None).unwrap();
-    let relation = df.to_relation();
+    let relation = df.to_relation().unwrap();
     let Some(proto::relation::RelType::Sql(sql)) = &relation.rel_type else {
         panic!("expected the SQL relation, got {relation:?}");
     };
@@ -80,16 +80,17 @@ fn 
raw_relations_are_sent_as_they_are_with_a_plan_id_of_the_session() {
     let plan_id = relation.common.as_ref().and_then(|common| common.plan_id);
     assert!(plan_id.is_some());
     // The plan ID is that of the node, as the session gives it, the same each 
time.
-    assert_eq!(df.to_relation(), relation);
-    assert_eq!(df.clone().to_relation(), relation);
+    assert_eq!(df.to_relation().unwrap(), relation);
+    assert_eq!(df.clone().to_relation().unwrap(), relation);
 }
 
 #[test]
 fn transformations_of_raw_relations_take_them_as_input() {
     let df = DataFrame::from_relation(offline(), sql_relation("SELECT 1 AS 
a"), None).unwrap();
-    let relation = df.to_relation();
+    let relation = df.to_relation().unwrap();
     let filtered = df.filter(col("a").gt(lit(0)));
-    let Some(proto::relation::RelType::Filter(filter)) = 
filtered.to_relation().rel_type else {
+    let Some(proto::relation::RelType::Filter(filter)) = 
filtered.to_relation().unwrap().rel_type
+    else {
         panic!("expected a filter");
     };
     assert_eq!(filter.input.as_deref(), Some(&relation));
@@ -104,7 +105,7 @@ fn 
raw_relations_keep_their_owners_alive_while_a_dataframe_uses_them() {
     let derived = df.select([col("a")]);
     drop(df);
     assert!(alive.upgrade().is_some());
-    assert!(format!("{:?}", derived.to_relation()).contains("SELECT 1 AS a"));
+    assert!(format!("{:?}", derived.to_relation().unwrap()).contains("SELECT 1 
AS a"));
     drop(derived);
     assert!(alive.upgrade().is_none());
 }
@@ -116,19 +117,20 @@ fn 
sent_relations_keep_the_plan_ids_of_the_dataframes_they_were_of() {
     // was of refer to it.
     let session = offline();
     let df = session.range(3).unwrap().select([col("id").alias("x")]);
-    let relation = df.to_relation();
+    let relation = df.to_relation().unwrap();
     let plan_id = relation.common.as_ref().and_then(|common| common.plan_id);
     let copy = DataFrame::from_sent_relation(session.clone(), 
relation.clone());
-    assert_eq!(copy.to_relation(), relation);
-    assert_eq!(copy.clone().to_relation(), relation);
+    assert_eq!(copy.to_relation().unwrap(), relation);
+    assert_eq!(copy.clone().to_relation().unwrap(), relation);
     let filtered = copy.filter(df.col("x").gt(lit(0)));
-    let Some(proto::relation::RelType::Filter(filter)) = 
filtered.to_relation().rel_type else {
+    let Some(proto::relation::RelType::Filter(filter)) = 
filtered.to_relation().unwrap().rel_type
+    else {
         panic!("expected a filter");
     };
     assert_eq!(filter.input.as_deref(), Some(&relation));
     assert!(format!("{:?}", filter.condition).contains(&format!("plan_id: 
{:?}", plan_id)));
     // The other plans of the session take other plan IDs.
-    let other = session.range(1).unwrap().to_relation();
+    let other = session.range(1).unwrap().to_relation().unwrap();
     assert_ne!(other.common.and_then(|common| common.plan_id), plan_id);
 }
 
@@ -159,21 +161,28 @@ fn 
placeholders_of_a_dataframe_are_replaced_by_its_relation() {
             None,
         )
         .unwrap();
-        let Some(proto::relation::RelType::WithRelations(with)) = 
input.to_relation().rel_type
+        let Some(proto::relation::RelType::WithRelations(with)) =
+            input.to_relation().unwrap().rel_type
         else {
             panic!("expected WithRelations");
         };
-        assert_eq!(with.root.as_deref(), Some(&df.to_relation()));
-        assert_eq!(with.references, vec![df.to_relation()]);
+        assert_eq!(with.root.as_deref(), Some(&df.to_relation().unwrap()));
+        assert_eq!(with.references, vec![df.to_relation().unwrap()]);
         // The same placeholder gives the same relation.
         assert_eq!(df.placeholder_relation(), placeholder);
         // The DataFrame of the placeholder is a node of its own, whose 
relation is that of `df`.
         let single = DataFrame::from_relation(session.clone(), 
placeholder.clone(), None).unwrap();
-        assert_eq!(single.to_relation().rel_type, df.to_relation().rel_type);
+        assert_eq!(
+            single.to_relation().unwrap().rel_type,
+            df.to_relation().unwrap().rel_type
+        );
         // A placeholder of a DataFrame of another session is the relation of 
that DataFrame too.
         let other = offline();
         let copy = DataFrame::from_relation(other, placeholder, None).unwrap();
-        assert_eq!(copy.to_relation().rel_type, df.to_relation().rel_type);
+        assert_eq!(
+            copy.to_relation().unwrap().rel_type,
+            df.to_relation().unwrap().rel_type
+        );
     });
 }
 
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index b882bdad..15e3e27b 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -1303,6 +1303,42 @@ except RecursionError as error:
     assert "raised RecursionError" in result.stdout, (result.stdout, 
result.stderr)
 
 
+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
+    # reason, and from 2,000 the process crashed (SIGSEGV), so this runs in a 
process of its own.
+    # The session works afterwards.
+    import subprocess
+    import sys
+
+    remote = os.environ.get("SPARK_REMOTE")
+    if not remote:
+        pytest.skip("SPARK_REMOTE is required for live-server tests")
+    result = subprocess.run([sys.executable, "-c", """
+from pyspark.sql import SparkSession, functions as F
+spark = SparkSession.builder.remote(%r).getOrCreate()
+for levels in [1000, 1500, 2000, 3000, 5000, 10000]:
+    df = spark.range(10)
+    for _ in range(levels):
+        df = df.filter(F.col("id") >= 0)
+    try:
+        df.count()
+    except RecursionError:
+        print(levels, "RecursionError")
+print(spark.range(3).count())
+""" % remote], capture_output=True, text=True, timeout=300)
+    assert result.returncode == 0, result.stderr
+    assert result.stdout.splitlines() == [
+        "1000 RecursionError",
+        "1500 RecursionError",
+        "2000 RecursionError",
+        "3000 RecursionError",
+        "5000 RecursionError",
+        "10000 RecursionError",
+        "3",
+    ], result.stdout
+
+
 def test_progress_handler_runs_a_query_of_its_own_as_pyspark(session):
     # As PySpark's: a handler runs while the execution runs, and a query of 
the handler runs
     # too, the progress of the execution having no effect on it.
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index df934c0b..3b71ad58 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -9227,6 +9227,22 @@ def 
test_create_dataframe_converts_numpy_scalars_as_pyarrow():
             _local_create_dataframe([(value,)], schema)
 
 
+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.
+    from pyspark.sql import functions as F
+
+    spark, service = mock_connect
+    df = spark.range(10)
+    for _ in range(10_000):
+        df = df.filter(F.col("id") >= 0)
+    for action in [df.count, df.collect, lambda: df.schema, df.explain]:
+        with pytest.raises(RecursionError, match="a plan of 1000[12] levels"):
+            action()
+    assert service.execute_requests == []
+    assert service.analyze_requests == []
+
+
 def 
test_create_dataframe_raises_recursion_error_for_a_value_that_contains_itself():
     class Node:
         def __init__(self):


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

Reply via email to