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 38118a6b [SPARK-61520][CONNECT][PYTHON] Unpickle deep Columns and 
DataFrames, and call session hooks on deep plans, in the Python client as 
PySpark does
38118a6b is described below

commit 38118a6ba725eb5be8da493a545e6a0e6ad63884
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 20:44:40 2026 +0900

    [SPARK-61520][CONNECT][PYTHON] Unpickle deep Columns and DataFrames, and 
call session hooks on deep plans, in the Python client as PySpark does
    
    ### What changes were proposed in this pull request?
    
    A pickled Column or DataFrame of the Python client, and the request that a 
session hook (`hook_factories`) sees, now work past 100 nested protobuf 
messages. They now go as deep as PySpark's own serializer does, instead of 
stopping at protobuf's decode limit:
    
    - The drop-in's Rust crate (`crates/pyspark-rs` only) enables prost's 
`no-recursion-limit` feature. Its fixed limit of 100 nested messages cannot be 
raised per call. The protobufs of a pickled Column or DataFrame, and of a 
hook's request, are encoded, decoded and dropped on a grown stack, so a deep 
one does not overflow a small thread (512 KiB). Python code (the hooks, the 
parse) keeps running on the caller's own stack. The client's bounds still 
apply: a pickle carries the levels of i [...]
    - Python protobuf (upb and the pure-Python backend) also stops `FromString` 
at 100 levels. `pyspark.sql.connect._column_reduce.parse_deep` parses a message 
of any depth. It tries `FromString` first, then fills the message field by 
field from a work list, so the parser never nests past its limit, and it gives 
the same message. It is used for the request the hooks see, and in the worker 
branches of `column_of` and of the DataFrame creator, which cloudpickle pickles 
by value to the serve [...]
    - `docs/compatibility.md` notes that the drop-in now also decodes server 
responses deeper than 100 nested messages, which PySpark's client rejects 
("Exception deserializing response!", for example the schema of a struct nested 
34 levels).
    
    ### Why are the changes needed?
    
    PySpark pickles its Python expression and plan objects, and hands the hooks 
its Python request without parsing it. In the drop-in, all three went through a 
protobuf decode, which stops at 100 nested messages:
    
    ```python
    c = F.col("id")
    for _ in range(50):
        c = c + 1
    pickle.loads(pickle.dumps(c))
    # before: ValueError: failed to decode Protobuf message ... (also on the 
server's Python worker)
    # after: the Column, which sends the same expression; PySpark 4.3.0 
round-trips its Column too
    
    df = spark.range(10)
    for i in range(60):
        df = df.withColumn(f"c{i}", F.lit(i))
    cloudpickle.loads(cloudpickle.dumps(df))   # before: the same decode error; 
after: the DataFrame
    
    SparkSession(connection=..., hook_factories=[f])   # then a 60-level plan 
.count()
    # before: DecodeError "Error parsing message: too many levels of nesting"; 
after (and PySpark): 10
    ```
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. Deep Columns, DataFrames and hook requests work up to the depth where 
PySpark stops; there it raises `RecursionError` while serializing, at about 200 
to 250 levels with protobuf's pure-Python backend. With protobuf's default 
backend, upb, PySpark's own plan builder copies an expression added to a 
repeated field (a `select`, a `withColumn`) through upb's parser, so official 
PySpark raises `DecodeError` for a plan with an expression of 49 or more nested 
additions, on a client and o [...]
    
    ### How was this patch tested?
    
    - New offline tests in `python/tests/test_dropin_offline.py`, run with the 
mock server under both protobuf backends (pure-Python and upb). They cover the 
Column and DataFrame round trips at 60, 100 and 300 levels (also CASE WHEN, 
sort order and window expressions over a deep column), which send the same 
expression or relation; hooks at 60, 150 and 300 levels, which see the full 
plan, and a hook that replaces a deep plan; `parse_deep` on shallow and deep 
messages, with maps, repeated m [...]
    - A new e2e test in `python/tests/test_dropin_e2e.py`, in which a 
`foreachBatch` closure captures a 100-addition Column that the server's Python 
worker (official PySpark) unpickles and gives back whole (its size against the 
pickled bytes, which holds on either backend; selecting it there raises upb's 
`DecodeError` in official PySpark too). Run against a server whose workers use 
upb, as CI's do.
    - Rust unit tests for the expression levels, the DataFrame levels bound and 
the small-stack send, also in a debug build.
    - The full offline suites (`test_dropin_offline.py`, `test_ml_offline.py` 
and `test_arrow_handoff.py`) under both backends (3213 passed each), the Rust 
library tests, the Rust e2e `raw_relation` and `e2e_dataframe` suites, the 
`--no-run` builds (with and without `wasm-udf`), `cargo fmt --check`, 
`scripts/audit_no_stubs.sh` and the ruff gates.
    
    ### 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 #561 from HyukjinKwon/SPARK-61520-deep-pickle-and-hooks.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/Cargo.toml                 |   5 +-
 crates/pyspark-rs/src/column.rs              |  36 ++--
 crates/pyspark-rs/src/dataframe.rs           |  35 ++--
 crates/pyspark-rs/src/lib.rs                 |  21 +++
 crates/pyspark-rs/src/session.rs             |  28 +--
 crates/spark-connect/src/column.rs           |  21 +++
 crates/spark-connect/src/dataframe.rs        |  93 +++++++++-
 crates/spark-connect/src/expression.rs       | 104 ++++++++++-
 crates/spark-connect/src/plan.rs             |  14 +-
 docs/compatibility.md                        |   8 +
 python/pyspark/sql/connect/_column_reduce.py | 119 +++++++++++-
 python/pyspark/sql/connect/column.py         |   3 +-
 python/pyspark/sql/connect/dataframe.py      |  23 ++-
 python/tests/test_dropin_e2e.py              |  43 +++++
 python/tests/test_dropin_offline.py          | 261 +++++++++++++++++++++++++++
 15 files changed, 744 insertions(+), 70 deletions(-)

diff --git a/crates/pyspark-rs/Cargo.toml b/crates/pyspark-rs/Cargo.toml
index 041d0f4b..bf84891d 100644
--- a/crates/pyspark-rs/Cargo.toml
+++ b/crates/pyspark-rs/Cargo.toml
@@ -26,7 +26,10 @@ spark-connect-proto = { package = 
"apache-spark-connect-proto", path = "../spark
 pyo3.workspace = true
 arrow = { workspace = true, features = ["pyarrow"] }
 tokio.workspace = true
-prost.workspace = true
+# The drop-in decodes the protobufs that a pickled Column or DataFrame, and a 
session hook's
+# request, carry, which PySpark's protobuf decodes at any depth: lift prost's 
limit of 100
+# nested messages for this crate (the decode stacks are grown, see 
`on_grown_stack`).
+prost = { workspace = true, features = ["no-recursion-limit"] }
 prost-types.workspace = true
 tonic.workspace = true
 serde_json = "1.0"
diff --git a/crates/pyspark-rs/src/column.rs b/crates/pyspark-rs/src/column.rs
index 520a1c43..ff9fc3b1 100644
--- a/crates/pyspark-rs/src/column.rs
+++ b/crates/pyspark-rs/src/column.rs
@@ -736,9 +736,8 @@ impl PyColumn {
     /// the unpickled Column is a sort order of `orderBy`, `Window.orderBy` 
and the others.
     /// A Column too deep to be sent is the `RecursionError` that PySpark's 
pickler raises for it.
     fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
-        use prost::Message;
-        let expression = self.column.try_to_proto().to_pyerr()?;
-        let expression = pyo3::types::PyBytes::new(py, 
&expression.encode_to_vec());
+        let (expression, levels) = 
self.column.try_to_proto_with_levels().to_pyerr()?;
+        let expression = pyo3::types::PyBytes::new(py, 
&crate::encode_on_grown_stack(expression));
         let column = |expr: &spark_connect::expression::Expression| -> 
PyResult<Py<PyColumn>> {
             Py::new(py, PyColumn::new(Column::new(expr.clone())))
         };
@@ -778,19 +777,22 @@ impl PyColumn {
                 branches,
                 else_value,
                 sort,
+                levels,
             ))
     }
 
     /// The Column of `expression`, the bytes of a `spark.connect.Expression`, 
and of its
-    /// `rendered` rendering, as a pickled Column unpickles: it sends the 
expression as it is.
-    /// The CASE WHEN of `branches` and `else_value`, the Columns of its 
parts, is built as it was.
+    /// `rendered` rendering, of its `levels`, as a pickled Column unpickles: 
it sends the
+    /// expression as it is. The CASE WHEN of `branches` and `else_value`, the 
Columns of its
+    /// parts, is built as it was.
     #[staticmethod]
-    #[pyo3(signature = (expression, rendered, branches=None, else_value=None))]
+    #[pyo3(signature = (expression, rendered, branches=None, else_value=None, 
levels=1))]
     fn _of_expression(
         expression: &[u8],
         rendered: String,
         branches: Option<Vec<(PyRef<'_, PyColumn>, PyRef<'_, PyColumn>)>>,
         else_value: Option<PyRef<'_, PyColumn>>,
+        levels: usize,
     ) -> PyResult<PyColumn> {
         if let Some(branches) = branches {
             let branches = branches
@@ -813,18 +815,16 @@ impl PyColumn {
             )));
         }
         use prost::Message;
-        let expression = spark_connect_proto::Expression::decode(expression)
-            .map_err(|error| 
pyo3::exceptions::PyValueError::new_err(error.to_string()))?;
-        Ok(PyColumn::new(Column::new(
-            spark_connect::expression::Expression::new(
-                spark_connect::expression::ExpressionNode::Sent(Box::new(
-                    spark_connect::expression::SentExpression {
-                        expression,
-                        rendered,
-                    },
-                )),
-            ),
-        )))
+        // Decoded, and then built or dropped, on a stack that holds its 
levels.
+        // The errors become Python exceptions on the caller's stack, which 
runs no Python code
+        // on the grown one.
+        let column = crate::on_grown_stack(|| {
+            spark_connect_proto::Expression::decode(expression)
+                .map(|expression| Column::sent(expression, rendered, levels))
+        })
+        .map_err(|error| 
pyo3::exceptions::PyValueError::new_err(error.to_string()))?
+        .to_pyerr()?;
+        Ok(PyColumn::new(column))
     }
 
     /// As PySpark's Column, which has no `__str__` of its own for 
`_with_origin` to wrap: no
diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index 1aeccda0..741e4021 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -656,9 +656,11 @@ 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>) -> PyResult<Bound<'py, 
pyo3::types::PyBytes>> {
-        use prost::Message;
         let relation = self.dataframe.to_relation().to_pyerr()?;
-        Ok(pyo3::types::PyBytes::new(py, &relation.encode_to_vec()))
+        Ok(pyo3::types::PyBytes::new(
+            py,
+            &crate::encode_on_grown_stack(relation),
+        ))
     }
 
     /// The bytes of the placeholder of the relation of this DataFrame, which 
the plan of `_plan`
@@ -678,23 +680,34 @@ 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)?,
+                this.dataframe.plan_levels(),
+            ))
     }
 
-    /// The DataFrame of `relation`, the bytes of a relation of `session`, as 
a pickled DataFrame
-    /// unpickles.
+    /// The DataFrame of `relation`, the bytes of a relation of `levels` 
levels of `session`, as a
+    /// pickled DataFrame unpickles.
     #[staticmethod]
+    #[pyo3(signature = (session, relation, levels=1))]
     fn _of_relation(
         session: &Bound<'_, crate::session::PySparkSession>,
         relation: &[u8],
+        levels: usize,
     ) -> PyResult<PyDataFrame> {
+        let session = session.borrow().session.clone();
         use prost::Message;
-        let relation = spark_connect_proto::Relation::decode(relation)
-            .map_err(|error| 
pyo3::exceptions::PyValueError::new_err(error.to_string()))?;
-        Ok(PyDataFrame::new(DataFrame::from_sent_relation(
-            session.borrow().session.clone(),
-            relation,
-        )))
+        // Decoded, and then built or dropped, on a stack that holds its 
levels.
+        // The errors become Python exceptions on the caller's stack, which 
runs no Python code
+        // on the grown one.
+        let dataframe = crate::on_grown_stack(|| {
+            spark_connect_proto::Relation::decode(relation)
+                .map(|relation| DataFrame::from_sent_relation_levels(session, 
relation, levels))
+        })
+        .map_err(|error| 
pyo3::exceptions::PyValueError::new_err(error.to_string()))?
+        .to_pyerr()?;
+        Ok(PyDataFrame::new(dataframe))
     }
 
     /// The plan of this DataFrame, as PySpark Connect's `DataFrame._plan`, 
whose
diff --git a/crates/pyspark-rs/src/lib.rs b/crates/pyspark-rs/src/lib.rs
index 3c2a27e8..4565f265 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -79,6 +79,27 @@ use types::{
 };
 use window::{PyFrameBound, PyWindow, PyWindowSpec};
 
+/// The stack that the encode, the decode and the drop of a protobuf of a 
pickled Column,
+/// DataFrame or hook request take on the thread that unpickles or sends it. 
Prost recurses once
+/// per level of a message, with frames of about 1 KiB in a release build and 
more in a debug
+/// one, and a deep message has at most `MAX_PLAN_DEPTH` levels (the client 
refuses more), so this
+/// holds them with room to spare, on a thread of 512 KiB as well.
+const PROTO_STACK: usize = if cfg!(debug_assertions) {
+    16 << 20
+} else {
+    4 << 20
+};
+
+/// Run `f`, which encodes, decodes or drops a deep protobuf, on a stack that 
holds its levels.
+pub(crate) fn on_grown_stack<T>(f: impl FnOnce() -> T) -> T {
+    stacker::maybe_grow(PROTO_STACK, PROTO_STACK, f)
+}
+
+/// The bytes of `message`, encoded and dropped on a stack that holds its 
levels.
+pub(crate) fn encode_on_grown_stack<M: prost::Message + Send>(message: M) -> 
Vec<u8> {
+    on_grown_stack(move || message.encode_to_vec())
+}
+
 #[pymodule(gil_used = false)]
 fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
     m.add_class::<PySparkSession>()?;
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index d61990f7..eb13281c 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -516,7 +516,11 @@ thread_local! {
 
 /// The request that `hooks` return of `request`, as PySpark's client calls 
its session hooks:
 /// each `on_execute_plan` with the request of the one before, as a 
`pb2.ExecutePlanRequest`
-/// of the generated `pyspark.sql.connect.proto`, of the operation ID of 
`request`.
+/// of the generated `pyspark.sql.connect.proto`, of the operation ID of 
`request`. The hooks get
+/// the request as `parse_deep` parses it, which takes a request of any 
nesting, where
+/// `FromString` stops at protobuf's limit of 100 nested messages. Its 
messages are encoded,
+/// decoded and dropped on a grown stack, as the caller's thread may be a 
small one, while the
+/// Python code (the parse and the hooks) runs on the stack of the caller's 
thread.
 fn call_execute_plan_hooks(
     py: Python<'_>,
     hooks: &[Py<PyAny>],
@@ -524,13 +528,15 @@ fn call_execute_plan_hooks(
 ) -> PyResult<spark_connect_proto::ExecutePlanRequest> {
     use prost::Message;
     let operation_id = request.operation_id.clone();
+    let bytes = pyo3::types::PyBytes::new(py, 
&crate::encode_on_grown_stack(request));
     let mut message = py
-        .import("pyspark.sql.connect.proto")?
-        .getattr("ExecutePlanRequest")?
-        .call_method1(
-            "FromString",
-            (pyo3::types::PyBytes::new(py, &request.encode_to_vec()),),
-        )?;
+        .import("pyspark.sql.connect._column_reduce")?
+        .getattr("parse_deep")?
+        .call1((
+            py.import("pyspark.sql.connect.proto")?
+                .getattr("ExecutePlanRequest")?,
+            bytes,
+        ))?;
     for hook in hooks {
         message = hook.bind(py).call_method1("on_execute_plan", (message,))?;
         if let Some(operation_id) = &operation_id {
@@ -538,10 +544,10 @@ fn call_execute_plan_hooks(
         }
     }
     let bytes = message.call_method0("SerializeToString")?;
-    let mut request = spark_connect_proto::ExecutePlanRequest::decode(
-        bytes.cast::<pyo3::types::PyBytes>()?.as_bytes(),
-    )
-    .map_err(|error| 
pyo3::exceptions::PyValueError::new_err(error.to_string()))?;
+    let bytes = bytes.cast::<pyo3::types::PyBytes>()?.as_bytes();
+    let mut request =
+        crate::on_grown_stack(|| 
spark_connect_proto::ExecutePlanRequest::decode(bytes))
+            .map_err(|error| 
pyo3::exceptions::PyValueError::new_err(error.to_string()))?;
     // A hook may put in the plan of a DataFrame, which the Python plan sends 
as a placeholder.
     spark_connect::plan::resolve_request(&mut request)
         .map_err(|error| 
pyo3::exceptions::PyValueError::new_err(error.to_string()))?;
diff --git a/crates/spark-connect/src/column.rs 
b/crates/spark-connect/src/column.rs
index 00b86efd..94f647a0 100644
--- a/crates/spark-connect/src/column.rs
+++ b/crates/spark-connect/src/column.rs
@@ -400,6 +400,27 @@ impl Column {
         self.expr.try_to_proto()
     }
 
+    /// As [`Column::try_to_proto`], and the levels of the expression, which a 
pickled Column keeps
+    /// for [`Column::sent`]. Not a stable API.
+    #[doc(hidden)]
+    pub fn try_to_proto_with_levels(
+        &self,
+    ) -> spark_connect_core::error::Result<(proto::Expression, usize)> {
+        self.expr.try_to_proto_with_levels()
+    }
+
+    /// The Column of the `spark.connect.Expression` `expression`, as it was 
sent, with its
+    /// `rendered` rendering and its `levels` (see 
[`Column::try_to_proto_with_levels`]), as a
+    /// pickled Column unpickles. Not a stable API.
+    #[doc(hidden)]
+    pub fn sent(
+        expression: proto::Expression,
+        rendered: String,
+        levels: usize,
+    ) -> spark_connect_core::error::Result<Column> {
+        Ok(Column::new(Expression::sent(expression, rendered, levels)?))
+    }
+
     /// Mirrors `pyspark.sql.column.Column.over` - window function application.
     pub fn over(self, window_spec: WindowSpec) -> Column {
         // Convert window frame spec if present
diff --git a/crates/spark-connect/src/dataframe.rs 
b/crates/spark-connect/src/dataframe.rs
index ee9e41ae..8d6fc1d0 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -1277,13 +1277,39 @@ impl DataFrame {
     /// raise for their metrics that PySpark does not convert. Not a stable 
API.
     #[doc(hidden)]
     pub fn from_sent_relation(session: SparkSession, relation: 
proto::Relation) -> DataFrame {
+        // A relation of one level holds no plan, as a relation built without 
a pickled plan.
+        DataFrame::from_sent_relation_at(session, relation, 1)
+    }
+
+    /// As [`DataFrame::from_sent_relation`], for a relation of `levels` 
levels, as the plan of
+    /// the DataFrame that was pickled had: the levels count for 
[`MAX_PLAN_DEPTH`] as they did
+    /// there, so a relation deeper than it is a `RecursionError`, as the API 
raises it when it
+    /// sends one. Not a stable API.
+    #[doc(hidden)]
+    pub fn from_sent_relation_levels(
+        session: SparkSession,
+        relation: proto::Relation,
+        levels: usize,
+    ) -> Result<DataFrame> {
+        if levels > crate::plan::MAX_PLAN_DEPTH {
+            return Err(crate::plan::too_deep_a_plan(levels));
+        }
+        Ok(DataFrame::from_sent_relation_at(session, relation, levels))
+    }
+
+    /// The DataFrame of `relation`, of `levels` levels, which is within the 
bound.
+    fn from_sent_relation_at(
+        session: SparkSession,
+        relation: proto::Relation,
+        levels: usize,
+    ) -> DataFrame {
         let plan_id = relation.common.as_ref().and_then(|common| 
common.plan_id);
         let observations = plan_id
             .and_then(|plan_id| session.plan_ids().node_of(plan_id))
             .map(|node| node.observations())
             .unwrap_or_default();
-        // A relation decoded from bytes is shallow: prost decodes at most 100 
nested messages.
-        let dataframe = DataFrame::from_raw_relation(session, relation, None, 
1, observations);
+        // The relation is sent as it is, and its clone and drop take the 
stack of its levels.
+        let dataframe = DataFrame::from_raw_relation(session, relation, None, 
levels, observations);
         if let Some(plan_id) = plan_id {
             dataframe
                 .session
@@ -1293,6 +1319,13 @@ impl DataFrame {
         dataframe
     }
 
+    /// The levels of the plan of this DataFrame, as a pickled DataFrame 
records them for
+    /// [`DataFrame::from_sent_relation_levels`]. Not a stable API.
+    #[doc(hidden)]
+    pub fn plan_levels(&self) -> usize {
+        self.plan.depth()
+    }
+
     /// 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)]
@@ -7264,4 +7297,60 @@ mod deep_request_stack_tests {
             "an expression within the bound is sent: {schema}"
         );
     }
+
+    /// A relation of `levels` levels of limits over a range, as a pickled 
DataFrame's relation.
+    fn limit_relation(levels: usize) -> spark_connect_proto::Relation {
+        use spark_connect_proto as proto;
+        let mut relation = proto::Relation {
+            common: None,
+            rel_type: Some(proto::relation::RelType::Range(proto::Range {
+                start: None,
+                end: 1,
+                step: 1,
+                num_partitions: None,
+            })),
+        };
+        for _ in 1..levels {
+            relation = proto::Relation {
+                common: None,
+                rel_type: 
Some(proto::relation::RelType::Limit(Box::new(proto::Limit {
+                    input: Some(Box::new(relation)),
+                    limit: 1,
+                }))),
+            };
+        }
+        relation
+    }
+
+    #[test]
+    fn 
a_sent_relation_past_the_bound_is_a_recursion_error_as_the_api_raises_it() {
+        let spark = unreachable_session();
+        let error = DataFrame::from_sent_relation_levels(
+            spark.clone(),
+            limit_relation(3),
+            MAX_PLAN_DEPTH + 1,
+        )
+        .err()
+        .expect("a relation past the bound is refused");
+        assert_eq!(error.kind, SparkErrorKind::RecursionError, "{error}");
+        let df = DataFrame::from_sent_relation_levels(spark, 
limit_relation(3), MAX_PLAN_DEPTH)
+            .expect("a relation at the bound is accepted");
+        assert_eq!(df.plan().depth(), MAX_PLAN_DEPTH);
+    }
+
+    #[test]
+    fn 
a_sent_relation_at_the_bound_is_sent_from_a_small_stack_without_overflowing_it()
 {
+        let spark = unreachable_session();
+        let relation = limit_relation(MAX_PLAN_DEPTH);
+        let df = DataFrame::from_sent_relation_levels(spark, relation, 
MAX_PLAN_DEPTH)
+            .expect("a relation at the bound is accepted");
+        let (schema, collect) = on_a_small_stack(move || (df.schema(), 
df.collect()));
+        for error in [schema.unwrap_err(), collect.unwrap_err()] {
+            assert_ne!(
+                error.kind,
+                SparkErrorKind::RecursionError,
+                "a relation at the bound is sent: {error}"
+            );
+        }
+    }
 }
diff --git a/crates/spark-connect/src/expression.rs 
b/crates/spark-connect/src/expression.rs
index f2504392..71ee6479 100644
--- a/crates/spark-connect/src/expression.rs
+++ b/crates/spark-connect/src/expression.rs
@@ -117,15 +117,21 @@ pub(crate) fn with_stack_for_a_level<T>(f: impl FnOnce() 
-> T) -> T {
 /// 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> {
+    with_expression_levels(serialize).map(|(value, _)| value)
+}
+
+/// As [`with_expression_depth_bound`], and the levels that the expressions of 
`serialize` reach.
+fn with_expression_levels<T>(serialize: impl FnOnce() -> T) -> Result<(T, 
usize)> {
     let scope = DepthBoundScope::enter();
     let value = serialize();
-    if scope.deepest() > MAX_EXPRESSION_DEPTH {
+    let levels = scope.deepest();
+    if levels > 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)
+    Ok((value, levels))
 }
 
 /// An immutable, shared expression, mirroring PySpark's base Expression type.
@@ -234,11 +240,13 @@ pub enum ExpressionNode {
 }
 
 /// An expression of [`ExpressionNode::Sent`]: the `spark.connect.Expression` 
of a Column as it
-/// was sent, and its rendering, as `Column<'...'>` shows it.
+/// was sent, its rendering, as `Column<'...'>` shows it, and its levels, as
+/// [`Expression::try_to_proto_with_levels`] counts them when the Column was 
pickled.
 #[derive(Debug, Clone, PartialEq)]
 pub struct SentExpression {
     pub expression: proto::Expression,
     pub rendered: String,
+    pub levels: usize,
 }
 
 /// The type of a [`SubqueryExpression`]. Mirrors the `subquery_type` of
@@ -556,7 +564,17 @@ impl Expression {
         // 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) {
+            // A sent expression has the levels that it was pickled with, 
below this one.
+            let deepest = match self.node() {
+                ExpressionNode::Sent(sent) => {
+                    let deepest = level.0 + sent.levels.saturating_sub(1);
+                    DEEPEST_EXPRESSION_LEVEL
+                        .with(|current| 
current.set(current.get().max(deepest)));
+                    deepest
+                }
+                _ => level.0,
+            };
+            if deepest > 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();
@@ -575,6 +593,38 @@ impl Expression {
         with_expression_depth_bound(|| self.to_proto())
     }
 
+    /// As [`Expression::try_to_proto`], and the levels of the expression, as 
a pickled Column
+    /// records them, so that its unpickled copy, [`Expression::sent`], is as 
deep as it was.
+    pub fn try_to_proto_with_levels(&self) -> Result<(proto::Expression, 
usize)> {
+        with_expression_levels(|| self.to_proto())
+    }
+
+    /// The expression of `expression`, the `spark.connect.Expression` of a 
Column as it was
+    /// sent, with its `rendered` rendering and its `levels`, as a pickled 
Column unpickles: it
+    /// sends the expression as it is. An expression of more levels than
+    /// [`MAX_EXPRESSION_DEPTH`] is a `RecursionError`, as the API raises it 
when it sends one.
+    /// Not a stable API.
+    #[doc(hidden)]
+    pub fn sent(
+        expression: proto::Expression,
+        rendered: String,
+        levels: usize,
+    ) -> Result<Expression> {
+        if levels > MAX_EXPRESSION_DEPTH {
+            return Err(SparkError::recursion_msg(format!(
+                "maximum recursion depth exceeded while unpickling an 
expression of {levels} \
+                 levels; an expression may be at most {MAX_EXPRESSION_DEPTH} 
levels deep"
+            )));
+        }
+        Ok(Expression::new(ExpressionNode::Sent(Box::new(
+            SentExpression {
+                expression,
+                rendered,
+                levels,
+            },
+        ))))
+    }
+
     fn to_proto_with_origin(&self) -> proto::Expression {
         let mut expr = self.node_to_proto();
         if let Some(origin) = &self.origin {
@@ -1990,6 +2040,51 @@ mod tests {
         }
     }
 
+    #[test]
+    fn 
a_sent_expression_has_its_levels_and_counts_them_under_another_expression() {
+        // As a pickled Column of 300 additions: 301 levels, which the Column 
keeps when it is
+        // unpickled, and which count under an expression over it, as the 
levels of the API do.
+        let mut expr = col("id");
+        for _ in 0..300 {
+            expr = Expression::function(
+                "+",
+                vec![expr, Expression::literal(LiteralExpression::Long(1))],
+            );
+        }
+        let rendered = expr.render();
+        let (sent, levels) = expr.try_to_proto_with_levels().unwrap();
+        assert_eq!(levels, 301);
+        let unpickled = Expression::sent(sent.clone(), rendered.clone(), 
levels).unwrap();
+        assert_eq!(unpickled.to_proto(), sent);
+        let over = Expression::function("abs", vec![unpickled.clone()]);
+        assert_eq!(over.try_to_proto_with_levels().unwrap().1, 302);
+        assert_eq!(
+            over.try_to_proto().unwrap(),
+            Expression::function("abs", vec![expr])
+                .try_to_proto()
+                .unwrap()
+        );
+        // At the bound it is sent, and one level more, under an expression, 
is a RecursionError.
+        let at_bound = Expression::sent(sent.clone(), rendered.clone(), 
MAX_EXPRESSION_DEPTH);
+        let at_bound = at_bound.unwrap();
+        assert!(at_bound.try_to_proto().is_ok());
+        let error = Expression::function("abs", vec![at_bound])
+            .try_to_proto()
+            .unwrap_err();
+        assert_eq!(
+            error.kind,
+            spark_connect_core::error::SparkErrorKind::RecursionError
+        );
+        // A sent expression deeper than the bound is refused as it is 
unpickled.
+        let error = Expression::sent(sent, rendered, MAX_EXPRESSION_DEPTH + 1)
+            .err()
+            .unwrap();
+        assert_eq!(
+            error.kind,
+            spark_connect_core::error::SparkErrorKind::RecursionError
+        );
+    }
+
     #[test]
     fn sent_expressions_are_sent_and_rendered_as_they_were() {
         // As a pickled Column unpickles: the expression as it was sent, of 
its rendering, which
@@ -2002,6 +2097,7 @@ mod tests {
         let sent = 
Expression::new(ExpressionNode::Sent(Box::new(SentExpression {
             expression: original.to_proto(),
             rendered: original.render(),
+            levels: 3,
         })));
         assert_eq!(sent.to_proto(), original.to_proto());
         assert_eq!(sent.render(), "+(a, 1) AS b");
diff --git a/crates/spark-connect/src/plan.rs b/crates/spark-connect/src/plan.rs
index 4a12fc05..fe840dbf 100644
--- a/crates/spark-connect/src/plan.rs
+++ b/crates/spark-connect/src/plan.rs
@@ -973,6 +973,14 @@ const RAW_CLONE_STACK_PER_LEVEL: usize = if 
cfg!(debug_assertions) {
     2 << 10
 };
 
+/// The stack that the clone of a [`LogicalPlan::Raw`] relation of `levels` 
levels takes: see
+/// [`RAW_CLONE_STACK_PER_LEVEL`].
+fn raw_relation_stack(levels: usize) -> usize {
+    levels
+        .saturating_mul(RAW_CLONE_STACK_PER_LEVEL)
+        .saturating_add(64 << 10)
+}
+
 thread_local! {
     /// The level of the plan that this thread serializes now, the plans of 
subqueries
     /// included, and the deepest one since the start of the innermost 
`with_plan_depth_bound`.
@@ -1035,7 +1043,7 @@ fn with_plan_depth_bound<T>(serialize: impl FnOnce() -> 
T) -> Result<(T, usize)>
 }
 
 /// The `RecursionError` of a plan of `depth` levels, deeper than 
[`MAX_PLAN_DEPTH`].
-fn too_deep_a_plan(depth: usize) -> SparkError {
+pub(crate) fn too_deep_a_plan(depth: usize) -> SparkError {
     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"
@@ -1700,9 +1708,7 @@ impl LogicalPlan {
                 ..
             } => {
                 // The clone recurses for each level of the relation: grow the 
stack for them all.
-                let stack = depth
-                    .saturating_mul(RAW_CLONE_STACK_PER_LEVEL)
-                    .saturating_add(64 << 10);
+                let stack = raw_relation_stack(*depth);
                 relation = stacker::maybe_grow(stack, stack, || 
raw.as_ref().clone());
                 relation.common.get_or_insert_with(Default::default);
             }
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 16e8b8c0..b9b28267 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -451,3 +451,11 @@ From Python, `pyspark-client-rust` replaces the 
`pyspark-client` package: same
 `import pyspark`, same public API, same server - see 
[Installation](installation.md).
 Use it exactly like 
[PySpark](https://spark.apache.org/docs/latest/api/python/).
 The native [Rust API](dataframes.md) mirrors the same surface.
+
+The drop-in parses the protobufs that a pickled Column or DataFrame carries, 
and the requests
+that session hooks see, at any depth that PySpark's serializer reaches, where 
the parsers of
+protobuf and prost stop at 100 nested messages. Its Rust client enables prost's
+`no-recursion-limit` feature, which applies to every message the drop-in 
decodes. So it also
+decodes server responses deeper than 100 nested messages, such as the schema 
of a struct nested
+34 levels deep, which PySpark's client rejects with "Exception deserializing 
response!". The
+server is trusted, as SECURITY.md sets out, so this is not a bound on the 
responses.
diff --git a/python/pyspark/sql/connect/_column_reduce.py 
b/python/pyspark/sql/connect/_column_reduce.py
index b332238b..d08abef4 100644
--- a/python/pyspark/sql/connect/_column_reduce.py
+++ b/python/pyspark/sql/connect/_column_reduce.py
@@ -14,15 +14,113 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #
-"""The function that a pickled Column of the client unpickles with.
+"""The function that a pickled Column of the client unpickles with, and the 
parser of the deep
+messages that a pickled Column or DataFrame carries.
 
 ``pyspark.sql.connect.column`` registers this module with cloudpickle to 
pickle by value, so a
 Column that a UDF or a ``foreachBatch`` function captures unpickles on a 
Python worker of the
 server, whose PySpark has no Rust client, while ``pickle`` pickles the 
function by reference, of
 this module, on the client.
 """
+from collections import deque
 from typing import Any, Optional
 
+from google.protobuf.descriptor import FieldDescriptor
+from google.protobuf.message import DecodeError
+
+
+def parse_deep(message_class: Any, data: bytes) -> Any:
+    """The message of ``message_class`` that the bytes ``data`` encode, as its 
``FromString``
+    gives it, but of any depth: protobuf's parser refuses a message that nests 
more than 100
+    messages, and a plan that PySpark's serializer writes may nest deeper. 
Such a message is
+    filled field by field, from a work list in place of recursion: each 
message field is parsed
+    on its own, and one that the parser refuses is filled in turn, so that the 
parser never
+    nests past its limit. Where ``FromString`` succeeds, this gives the same 
message."""
+    try:
+        return message_class.FromString(data)
+    except DecodeError:
+        pass
+    message = message_class()
+    pending = deque([(message, data)])
+    try:
+        while pending:
+            target, payload = pending.popleft()
+            fields = target.DESCRIPTOR.fields_by_number
+            # The message fields whose earlier occurrence the parser refused: 
their later
+            # occurrences are filled after that one, in order, rather than 
parsed at once.
+            deferred = set()
+            pos = 0
+            while pos < len(payload):
+                start = pos
+                tag, pos = _varint(payload, pos)
+                number, wire_type = tag >> 3, tag & 7
+                if wire_type == 0:
+                    _, pos = _varint(payload, pos)
+                    end = pos
+                elif wire_type == 1:
+                    end = pos = pos + 8
+                elif wire_type == 5:
+                    end = pos = pos + 4
+                elif wire_type == 2:
+                    length, pos = _varint(payload, pos)
+                    end = pos + length
+                    if end > len(payload):
+                        raise DecodeError("a field longer than its message")
+                    field = fields.get(number)
+                    if (
+                        field is not None
+                        and field.type == FieldDescriptor.TYPE_MESSAGE
+                        and not field.message_type.GetOptions().map_entry
+                    ):
+                        # The element or sub-message of the field, created 
before the parse
+                        # of its bytes, which fills it in either way.
+                        if _is_repeated(field):
+                            child = getattr(target, field.name).add()
+                        else:
+                            child = getattr(target, field.name)
+                        child.SetInParent()
+                        if number not in deferred:
+                            try:
+                                fresh = 
type(child).FromString(payload[pos:end])
+                            except DecodeError:
+                                deferred.add(number)
+                            else:
+                                child.MergeFrom(fresh)
+                                pos = end
+                                continue
+                        pending.append((child, payload[pos:end]))
+                        pos = end
+                        continue
+                elif wire_type in (3, 4):
+                    raise DecodeError("a group, which Spark Connect messages 
do not use")
+                else:
+                    raise DecodeError("an unknown wire type")
+                target.MergeFromString(payload[start:end])
+                pos = end
+    except IndexError as error:
+        raise DecodeError("a truncated varint") from error
+    return message
+
+
+def _varint(data: bytes, pos: int) -> tuple[int, int]:
+    """The varint of ``data`` at ``pos``, and the position after it, as 
protobuf's wire format
+    encodes it. Truncated data raises IndexError."""
+    result = shift = 0
+    while True:
+        byte = data[pos]
+        pos += 1
+        result |= (byte & 0x7F) << shift
+        if not byte & 0x80:
+            return result, pos
+        shift += 7
+
+
+def _is_repeated(field: Any) -> bool:
+    """Whether ``field`` is a repeated field, of protobuf's descriptor of 
either version."""
+    if hasattr(field, "is_repeated"):
+        return field.is_repeated
+    return field.label == FieldDescriptor.LABEL_REPEATED
+
 
 def column_of(
     expression: bytes,
@@ -30,14 +128,15 @@ def column_of(
     branches: Optional[list[tuple[Any, Any]]] = None,
     else_value: Any = None,
     sort: Optional[tuple[Any, str]] = None,
+    levels: int = 1,
 ) -> Any:
-    """The Column of ``expression``, the bytes of a 
``spark.connect.Expression``, and of its
-    rendering ``rendered``, which sends the expression as it is: of the Rust 
client, or, on a
-    Python worker of the server, PySpark Connect's Column of the expression, 
as PySpark Connect's
-    Column of its expression unpickles there, so everything that it calls 
there is of PySpark.
-    For a CASE WHEN, ``branches`` are the (condition, value) Columns of its 
branches and
-    ``else_value`` the Column of its else value, so that it is a CASE WHEN 
again. For a sort
-    order, ``sort`` is its child Column and the name of its sort method, such 
as
+    """The Column of ``expression``, the bytes of a 
``spark.connect.Expression`` of ``levels``
+    levels, and of its rendering ``rendered``, which sends the expression as 
it is: of the Rust
+    client, or, on a Python worker of the server, PySpark Connect's Column of 
the expression, as
+    PySpark Connect's Column of its expression unpickles there, so everything 
that it calls there
+    is of PySpark. For a CASE WHEN, ``branches`` are the (condition, value) 
Columns of its
+    branches and ``else_value`` the Column of its else value, so that it is a 
CASE WHEN again. For
+    a sort order, ``sort`` is its child Column and the name of its sort 
method, such as
     ``desc_nulls_last``, so that it is a sort order again."""
     if sort is not None:
         # The child is a Column of the client, or PySpark Connect's on a 
worker, whose sort
@@ -78,6 +177,6 @@ def column_of(
             def __repr__(self):  # type: ignore[no-untyped-def]
                 return self._rendered
 
-        return ConnectColumn(Sent(proto.Expression.FromString(expression), 
rendered))
+        return ConnectColumn(Sent(parse_deep(proto.Expression, expression), 
rendered))
 
-    return _pyspark.Column._of_expression(expression, rendered, branches, 
else_value)
+    return _pyspark.Column._of_expression(expression, rendered, branches, 
else_value, levels)
diff --git a/python/pyspark/sql/connect/column.py 
b/python/pyspark/sql/connect/column.py
index cda5f4a0..55a77635 100644
--- a/python/pyspark/sql/connect/column.py
+++ b/python/pyspark/sql/connect/column.py
@@ -32,6 +32,7 @@ def _reduce_column(
     branches: Optional[list[tuple[Any, Any]]] = None,
     else_value: Any = None,
     sort: Optional[tuple[Any, str]] = None,
+    levels: int = 1,
 ) -> tuple[Callable[..., Any], tuple[Any, ...]]:
     """The ``__reduce__`` of a Column of the bytes of its 
``spark.connect.Expression`` and of its
     rendering, as PySpark Connect's Column pickles its expression: the 
function of
@@ -41,4 +42,4 @@ def _reduce_column(
     the Column gives back a sort order. cloudpickle pickles that function by 
value, also to a
     Python worker of the server, where it gives back PySpark Connect's Column, 
and ``pickle`` by
     reference."""
-    return _column_reduce.column_of, (expression, rendered, branches, 
else_value, sort)
+    return _column_reduce.column_of, (expression, rendered, branches, 
else_value, sort, levels)
diff --git a/python/pyspark/sql/connect/dataframe.py 
b/python/pyspark/sql/connect/dataframe.py
index 782593ae..4d335aab 100644
--- a/python/pyspark/sql/connect/dataframe.py
+++ b/python/pyspark/sql/connect/dataframe.py
@@ -18,11 +18,16 @@
 from collections.abc import Iterator
 from typing import Any, Callable
 
+from pyspark import cloudpickle as _cloudpickle
 from pyspark._pyspark import DataFrame
+from pyspark.sql.connect import _column_reduce
+from pyspark.sql.connect._column_reduce import parse_deep
 from pyspark.sql.dataframe import DataFrameNaFunctions, DataFrameStatFunctions
 
 __all__ = ["DataFrame", "DataFrameNaFunctions", "DataFrameStatFunctions"]
 
+_cloudpickle.register_pickle_by_value(_column_reduce)
+
 
 def _local_rows(rows: Any) -> Iterator[Any]:
     """The generator that ``DataFrame.toLocalIterator`` returns, as PySpark's: 
the first row
@@ -47,17 +52,19 @@ _local_rows.__code__ = _local_rows.__code__.replace(
 )
 
 
-def _reduce_dataframe(session: Any, relation: bytes) -> tuple[Callable[..., 
Any], tuple[Any, ...]]:
-    """The ``__reduce__`` of a DataFrame of ``session`` and the bytes of its 
``relation``, as
-    PySpark Connect's, of its session and its plan: a function, which 
cloudpickle pickles by
-    value, of the session, which unpickles first, and of the relation.
+def _reduce_dataframe(
+    session: Any, relation: bytes, levels: int = 1
+) -> tuple[Callable[..., Any], tuple[Any, ...]]:
+    """The ``__reduce__`` of a DataFrame of ``session`` and the bytes of its 
``relation`` of
+    ``levels`` levels, as PySpark Connect's, of its session and its plan: a 
function, which
+    cloudpickle pickles by value, of the session, which unpickles first, and 
of the relation.
 
     On a Python worker of the server, whose PySpark has no Rust client, such 
as the worker of a
     ``foreachBatch`` function, which has the active session of the query, the 
function gives
     back PySpark Connect's DataFrame of the relation, as PySpark's DataFrame 
of its plan unpickles
     there. So everything that it calls there is of PySpark, which the worker 
has."""
 
-    def creator(session: Any, relation: bytes) -> Any:
+    def creator(session: Any, relation: bytes, levels: int) -> Any:
         try:
             from pyspark import _pyspark
         except ImportError:
@@ -82,8 +89,8 @@ def _reduce_dataframe(session: Any, relation: bytes) -> 
tuple[Callable[..., Any]
                     sent.CopyFrom(self._relation)
                     return sent
 
-            return 
ConnectDataFrame(Relation(proto.Relation.FromString(relation)), session)
+            return ConnectDataFrame(Relation(parse_deep(proto.Relation, 
relation)), session)
 
-        return _pyspark.DataFrame._of_relation(session, relation)
+        return _pyspark.DataFrame._of_relation(session, relation, levels)
 
-    return creator, (session, relation)
+    return creator, (session, relation, levels)
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index e94dfd61..80257024 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -1168,6 +1168,49 @@ def 
test_pickled_when_columns_chain_on_the_server_as_pyspark(session, tmp_path):
         session.sql(f"DROP TABLE IF EXISTS {table}").collect()
 
 
+def test_pickled_deep_column_on_the_server_as_pyspark(session, tmp_path):
+    # As PySpark's: a pickled Column of 100 additions, deeper than protobuf's 
parser reads,
+    # collects as the Column built without the pickling, and a foreachBatch 
function that captures
+    # it unpickles it on the Python worker of the server, with PySpark's 
Column.
+    import pickle
+
+    (tmp_path / "input.txt").write_text("a\nbb\n")
+    df = session.createDataFrame([(1,), (2,)], "a int")
+    direct = F.length(F.col("a").cast("string"))
+    for _ in range(100):
+        direct = direct + 1
+    copied = pickle.loads(pickle.dumps(direct))
+    assert sorted(row[0] for row in df.select(copied.alias("n")).collect()) == 
[101, 101]
+    assert df.select(copied.alias("n")).collect() == 
df.select(direct.alias("n")).collect()
+
+    captured = F.length(F.col("value"))
+    for _ in range(100):
+        captured = captured + 1
+    # The bytes of the expression that the pickle carries, as 
Column.__reduce__ gives them.
+    expected = len(captured.__reduce__()[1][0])
+    table = "foreach_batch_captured_deep_column"
+
+    def func(batch, batch_id):
+        # The worker's PySpark unpickles the Column, and gives the expression 
back whole. Its own
+        # plans take an expression this deep only with protobuf's pure-Python 
backend: upb copies
+        # a message added to a repeated field through its parser, which stops 
at 100 levels, so
+        # official PySpark raises DecodeError for `batch.select(captured)` 
there too. The worker
+        # checks the expression itself, which any backend gives back.
+        size = captured._expr.to_plan(None).ByteSize()
+        batch.sparkSession.createDataFrame([(batch_id, size)], "b long, size 
long").write.mode(
+            "append"
+        ).saveAsTable(table)
+
+    query = 
session.readStream.format("text").load(str(tmp_path)).writeStream.foreachBatch(func)
+    query = query.start()
+    try:
+        query.processAllAvailable()
+        assert [row.size for row in session.table(table).collect()] == 
[expected]
+    finally:
+        query.stop()
+        session.sql(f"DROP TABLE IF EXISTS {table}").collect()
+
+
 @pytest.mark.parametrize(
     "schema, expected",
     [
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index aa9c1cbf..1f15fdef 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -1813,6 +1813,267 @@ def 
test_pickled_when_columns_chain_as_pyspark(mock_connect):
         assert error.value.getCondition() == "INVALID_WHEN_USAGE"
 
 
+def _deep_addition(column, levels):
+    for _ in range(levels):
+        column = column + 1
+    return column
+
+
+def test_pickled_deep_columns_round_trip_and_send_as_they_were(mock_connect):
+    # As PySpark's Column, which pickles its expression tree and unpickles at 
any depth: a column
+    # of 60, 100 or 300 additions round-trips, and so do a CASE WHEN, a sort 
order and a window
+    # expression over it, each sending the expression that it sends without 
the pickling.
+    import cloudpickle
+    from pyspark.sql import functions as F
+    from pyspark.sql.window import Window
+
+    spark, service = mock_connect
+    df = spark.range(1)
+
+    def sent_root():
+        # ExecutePlanRequest.plan=3, Plan.root=1.
+        return 
parse_message(parse_message(service.execute_requests[-1])[3][0])[1][0]
+
+    def sent_expressions(column):
+        # Relation.project=3, Project.expressions=3.
+        df.select(column.alias("x")).collect()
+        return parse_message(parse_message(sent_root())[3][0])[3]
+
+    def sent_sort_order(column):
+        # Relation.sort=7, Sort.order=2.
+        df.orderBy(column).collect()
+        return parse_message(parse_message(sent_root())[7][0])[2]
+
+    for levels in (60, 100, 300):
+        direct = _deep_addition(F.col("id"), levels)
+        for copied in (pickle.loads(pickle.dumps(direct)),
+                       cloudpickle.loads(cloudpickle.dumps(direct))):
+            assert repr(copied) == repr(direct)
+            assert sent_expressions(copied) == sent_expressions(direct)
+            assert 
sent_expressions(F.sum(copied).over(Window.partitionBy("id"))) == (
+                sent_expressions(F.sum(direct).over(Window.partitionBy("id"))))
+        when = F.when(direct > 0, direct).otherwise(direct)
+        copied = pickle.loads(pickle.dumps(when))
+        assert repr(copied) == repr(when)
+        assert sent_expressions(copied) == sent_expressions(when)
+        order = direct.desc()
+        copied = pickle.loads(pickle.dumps(order))
+        assert sent_sort_order(copied) == sent_sort_order(order)
+    # A column of 300 additions, pickled again, and its copy of 300 with the 
same expression.
+    direct = _deep_addition(F.col("id"), 300)
+    twice = pickle.loads(pickle.dumps(pickle.loads(pickle.dumps(direct))))
+    assert sent_expressions(twice) == sent_expressions(direct)
+
+
+def 
test_pickled_deep_dataframes_round_trip_and_send_as_they_were(mock_connect):
+    # As PySpark's DataFrame, whose pickle keeps its plan: a DataFrame of 60, 
100 or 300
+    # withColumn levels round-trips, and its copy sends the plan that the 
DataFrame sends.
+    import cloudpickle
+    from pyspark.sql import functions as F
+
+    spark, service = mock_connect
+    for levels in (60, 100, 300):
+        df = spark.range(1)
+        for i in range(levels):
+            df = df.withColumn(f"c{i}", F.col("id"))
+        copied = cloudpickle.loads(cloudpickle.dumps(df))
+        assert copied.columns == df.columns
+        # The plan of each request: its operation ID is a new UUID.
+        df.collect()
+        sent = _sent_plan(service.execute_requests)[1][0]
+        copied.collect()
+        assert _sent_plan(service.execute_requests)[1][0] == sent
+
+
+def _project_levels(relation):
+    # Relation.with_columns=23 and WithColumns.input=1, until a relation that 
is not one.
+    levels = 0
+    while 23 in parse_message(relation):
+        levels += 1
+        relation = parse_message(parse_message(relation)[23][0])[1][0]
+    return levels
+
+
[email protected]("levels", [60, 150, 300])
+def test_session_hooks_see_deep_plans_as_pyspark(mock_connect, levels):
+    # As PySpark's hooks, which get the request of the client as it is: a hook 
sees the whole
+    # plan, however deep, and the request is sent as the hook returns it. At 
300 levels the
+    # request is serialized by the Python backend of protobuf, which recurses 
and stops at about
+    # 245 levels, as PySpark's serializer does with that backend; the upb 
backend does not.
+    pytest.importorskip("google.protobuf")
+    from google.protobuf.internal import api_implementation
+    from pyspark.sql import SparkSession
+    from pyspark.sql import functions as F
+
+    _, service = mock_connect
+    seen = []
+
+    class Counting(SparkSession.Hook):
+        def on_execute_plan(self, request):
+            relation = request.plan.root
+            depth = 0
+            while relation.WhichOneof("rel_type") == "with_columns":
+                depth += 1
+                relation = relation.with_columns.input
+            seen.append(depth)
+            return request
+
+    builder = SparkSession.builder.remote(service.remote)
+    builder._registerHook(lambda _: Counting())
+    spark = builder.create()
+    try:
+        df = spark.range(1)
+        for i in range(levels):
+            df = df.withColumn(f"c{i}", F.col("id"))
+        if levels > 200 and api_implementation.Type() == "python":
+            with pytest.raises(RecursionError):
+                df.collect()
+        else:
+            df.collect()
+            assert _project_levels(_sent_plan(service.execute_requests)[1][0]) 
== levels
+        assert seen == [levels]
+    finally:
+        spark.stop()
+
+
+def 
test_a_session_hook_that_replaces_a_deep_plan_sends_the_replacement(mock_connect):
+    # As PySpark's: a hook that puts in the plan of another DataFrame, which 
is deep, sends that
+    # plan, and the request of the replaced plan is not sent.
+    from pyspark.sql import SparkSession
+    from pyspark.sql import functions as F
+
+    _, service = mock_connect
+    spark_plain = SparkSession.builder.remote(service.remote).getOrCreate()
+    replacement = spark_plain.range(1)
+    for i in range(60):
+        replacement = replacement.withColumn(f"r{i}", F.col("id"))
+    replacement.collect()
+    expected = service.execute_requests[-1]
+
+    class Replacing(SparkSession.Hook):
+        def on_execute_plan(self, request):
+            request.plan.root.CopyFrom(replacement._plan.plan(None))
+            return request
+
+    builder = SparkSession.builder.remote(service.remote)
+    builder._registerHook(lambda _: Replacing())
+    spark = builder.create()
+    try:
+        spark.range(1).select(F.lit(1).alias("one")).collect()
+        sent_root = _sent_plan(service.execute_requests)[1][0]
+        assert sent_root == _sent_plan([expected])[1][0]
+        assert _project_levels(sent_root) == 60
+    finally:
+        spark.stop()
+
+
+def test_deep_messages_parse_as_from_string_and_fill_past_protobufs_limit():
+    # The parser of a deep Column or DataFrame: a message that FromString 
gives is the one it
+    # gives, and a message past protobuf's limit of 100 nested messages is 
filled in full, so that
+    # it serializes to the bytes it was parsed from, with a map, a repeated 
message and a oneof.
+    pytest.importorskip("google.protobuf")
+    from google.protobuf.message import DecodeError
+    from pyspark.sql.connect import proto
+    from pyspark.sql.connect._column_reduce import parse_deep
+
+    def deep_expression(levels):
+        root = proto.Expression()
+        current = root
+        for _ in range(levels):
+            function = current.unresolved_function
+            function.function_name = "+"
+            current = function.arguments.add()
+            function.arguments.add().literal.integer = 1
+        current.unresolved_attribute.unparsed_identifier = "id"
+        return root
+
+    for levels in (0, 1, 40):
+        shallow = deep_expression(levels)
+        data = shallow.SerializeToString()
+        assert parse_deep(proto.Expression, data).SerializeToString() == data
+        assert parse_deep(proto.Expression, data).SerializeToString() == (
+            proto.Expression.FromString(data).SerializeToString())
+    for levels in (60, 90):
+        data = deep_expression(levels).SerializeToString()
+        assert parse_deep(proto.Expression, data).SerializeToString() == data
+        with pytest.raises(DecodeError):
+            proto.Expression.FromString(data)
+
+    # A chain of 60 projections over a SQL relation, whose named arguments are 
a map, whose
+    # positional arguments are a repeated message, and whose relation is a 
oneof.
+    leaf = proto.Relation()
+    leaf.sql.query = "SELECT :a, ?"
+    leaf.sql.named_arguments["a"].literal.integer = 7
+    leaf.sql.pos_arguments.add().literal.integer = 8
+    leaf.sql.pos_arguments.add().unresolved_attribute.unparsed_identifier = 
"id"
+    relation = leaf
+    for _ in range(60):
+        project = proto.Relation()
+        project.project.input.CopyFrom(relation)
+        project.project.expressions.add().literal.integer = 1
+        relation = project
+    request = proto.ExecutePlanRequest()
+    request.plan.root.CopyFrom(relation)
+    data = request.SerializeToString()
+    back = parse_deep(proto.ExecutePlanRequest, data)
+    assert back.SerializeToString() == data
+    node = back.plan.root
+    for _ in range(60):
+        assert node.WhichOneof("rel_type") == "project"
+        assert node.project.expressions[0].literal.integer == 1
+        node = node.project.input
+    assert node.WhichOneof("rel_type") == "sql"
+    assert node.sql.named_arguments["a"].literal.integer == 7
+    assert [arg.literal.integer for arg in node.sql.pos_arguments][:1] == [8]
+    assert node.sql.pos_arguments[1].unresolved_attribute.unparsed_identifier 
== "id"
+
+
+def 
test_a_deep_column_unpickles_and_is_used_on_a_thread_of_512_kib(mock_connect):
+    # The unpickling, the use and the drop of a column and a DataFrame of 300 
levels recurse once
+    # per level, on the thread that does them: on a Python thread of 512 KiB, 
which overflowed in
+    # those (SIGBUS). The thread runs in a subprocess, since the crash would 
end this one.
+    import subprocess
+    import sys
+
+    _, service = mock_connect
+    script = """
+import pickle
+import threading
+import cloudpickle
+from pyspark.sql import SparkSession, functions as F
+
+def work():
+    spark = SparkSession.builder.remote(REMOTE_URL).create()
+    column = F.col("id")
+    for _ in range(300):
+        column = column + 1
+    column = pickle.loads(pickle.dumps(column))
+    frame = spark.range(1).select(column.alias("x"))
+    frame.schema
+    print("column", flush=True)
+    frame = spark.range(1)
+    for x in range(300):
+        frame = frame.withColumn(f"c{x}", F.col("id"))
+    frame = cloudpickle.loads(cloudpickle.dumps(frame))
+    frame.schema
+    print("frame", flush=True)
+    del column, frame
+    spark.stop()
+
+threading.stack_size(512 * 1024)
+thread = threading.Thread(target=work)
+thread.start()
+thread.join()
+print("done", flush=True)
+""".replace("REMOTE_URL", repr(service.remote))
+    result = subprocess.run(
+        [sys.executable, "-c", script], env=dict(os.environ, TZ="UTC"),
+        capture_output=True, text=True, timeout=300)
+    assert result.returncode == 0, result.stderr
+    assert "column" in result.stdout and "frame" in result.stdout, 
result.stdout
+    assert "done" in result.stdout, result.stdout
+
+
 def test_functions_build_columns():
     from pyspark.sql import functions as F
     c = F.col("id")


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

Reply via email to