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 59f65eba [SPARK-61416][CONNECT][PYTHON] Raise RecursionError for the 
expressions of merges, writeTo, function registrations, AutoCDC flows and 
pickled Columns too deep to send, as PySpark does
59f65eba is described below

commit 59f65ebacc1eb3d9a4007a903ebc2b4ee11104a5
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 09:54:30 2026 +0900

    [SPARK-61416][CONNECT][PYTHON] Raise RecursionError for the expressions of 
merges, writeTo, function registrations, AutoCDC flows and pickled Columns too 
deep to send, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61416](https://issues.apache.org/jira/browse/SPARK-61416): bound the 
expressions that a request serializes outside the plan of a relation, as 
SPARK-61328 bounded those of a plan in `relation_with_ids`. An expression 
deeper than `MAX_EXPRESSION_DEPTH` (745 levels) is now a `RecursionError` 
before any request is sent, and its proto is built down to the bound only.
    
    - `Expression::try_to_proto` and `Column::try_to_proto` (new) serialize an 
expression as a request serializes it: `to_proto` inside 
`with_expression_depth_bound`, as `LogicalPlan::try_to_proto` does for a plan. 
The paths below use them.
    - `MergeIntoWriter` (`merge.rs`): a clause keeps its condition and 
assignment Columns, and `merge()` serializes them with the merge condition. 
Before, the clause builders serialized them without a bound when the clause was 
added, and `merge()` serialized the merge condition without one.
    - `DataFrameWriterV2::build_operation` (`readwriter.rs`): the partitioning 
columns and the overwrite condition. `build_operation` now takes the condition 
as a Column.
    - `SparkSession::register_function`: the arguments of the function.
    - `GroupedData::new_grouping_sets`, behind the Rust API's `grouping_sets`: 
its de-duplication key encoded the full proto of each column. A column too deep 
to be sent is kept now, and the plan of the grouping fails with the 
`RecursionError`.
    - Drop-in (`crates/pyspark-rs`):
      - the AutoCDC flow (`pipeline_define_auto_cdc_flow`);
      - `Column.__reduce__` (pickling) and `Column.to_plan` / 
`Column._expr.to_plan`;
      - the merge clause methods (`updateAll`, `update`, `delete`, `insertAll`, 
`insert`) serialize the condition and the assignment values of their clause 
first, so they raise the `RecursionError` themselves and do not add the clause. 
PySpark's `_build_merge_action` serializes them when the clause method runs. 
`merge()` serializes them again.
    
    The drop-in raises Python's builtin `RecursionError` for these errors, as 
it already does for a deep `select` (`errors.rs`).
    
    ### Why are the changes needed?
    
    `Expression::to_proto` grows its stack, so it builds the whole proto of an 
expression of any depth. Outside `relation_with_ids` nothing stopped it. prost 
then encodes and drops that proto by recursing: on a runtime worker with a 2 
MiB stack, or on the caller's thread. Encoding also recomputes the nested 
lengths at each level, so it is quadratic in the depth.
    
    Probes of the drop-in on the repository's mock Connect server, before this 
change. The condition is `(col("t.id") == col("s.id")) & lit(True) & ...`, N 
times:
    
    | case | before | after |
    |---|---|---|
    | `mergeInto(...).merge()`, N = 1,000 | sent (1 request) | 
`RecursionError`, 0 requests |
    | `mergeInto(...).merge()`, N = 20,000 | process killed, rc=139 (SIGSEGV) | 
`RecursionError`, 0 requests |
    | `writeTo(...).overwrite(cond)`, N = 1,000 | sent | `RecursionError`, 0 
requests |
    | `writeTo(...).overwrite(cond)`, N = 20,000 | rc=139 | `RecursionError`, 0 
requests |
    | `pickle.dumps(col("id") + 1 + ...)`, 150,000 additions | rc=139 (20,000 
took 21 s in the review) | `RecursionError` at once |
    
    Each case alone at 745 additions, the first depth past the bound (746 
levels): before, the merge, the overwrite and the `partitionedBy(...).create()` 
each sent a request; the two merge clauses were added; pickling succeeded; 
`to_plan` raised protobuf's `DecodeError`. After, each raises `RecursionError` 
and sends nothing. At 744 additions all of them work as before: the commands 
are sent, and the clauses are added.
    
    PySpark builds these protos by recursing in Python, before any request:
    
    - `pyspark/sql/connect/merge.py`: `_build_merge_action` calls 
`condition.to_plan(client)` and `v.to_plan(client)` in the clause method, and 
`merge()` calls `self._condition.to_plan(...)`.
    - `pyspark/sql/connect/plan.py`: `WriteOperationV2.command` serializes the 
partitioning columns and the overwrite condition when the write runs.
    - `pyspark/pipelines/spark_connect_graph_element_registry.py`: 
`register_auto_cdc_flow` serializes the AutoCDC columns with `to_plan`.
    
    Official PySpark 4.3.0 on the same mock server, with the pure-Python 
protobuf backend (and the recursion limit of 3,000 that importing IPython's 
`jedi` sets there):
    
    - At 1,000 levels, `select`, `to_plan`, `mergeInto(...).merge()` and 
`writeTo(...).overwrite(...)` each raise `RecursionError`, and no request is 
sent.
    - At 745, `select` raises `RecursionError`, and `merge` and `overwrite` 
fail to serialize their request (`SparkConnectGrpcException`; nothing reaches 
the server).
    
    With protobuf's default upb backend, official PySpark already fails all 
four at 60 levels with `DecodeError`, raised by the `arguments.extend(...)` of 
`UnresolvedFunction.to_plan`, which parses each child with the decoder's limit 
of 100 nesting levels. The bound of this client is the existing 
`MAX_EXPRESSION_DEPTH`, which `select` already uses.
    
    `Column.to_plan` from about 50 levels (the P3 of the review) is not changed 
here. It encodes the expression in Rust and decodes it with 
`pyspark.sql.connect.proto.Expression.FromString`, whose decoder stops at 100 
nesting levels, two per operator. Under upb, official PySpark fails at almost 
the same depth: its `to_plan` works at 50 additions and raises `DecodeError` 
from 51; this client works at 49 and raises it from 50. The review saw official 
work at 60 and 100 because the machine r [...]
    
    - In the pure-Python backend, raising the decoder's limit 
(`decoder.SetRecursionLimit`) only moves the failure to between 200 and 250 
levels, where the recursive decoder hits Python's `RecursionError`.
    - In upb, the limit can only be raised for the whole process 
(`SetAllowOversizeProtos`), and there is no getter to restore it.
    - Avoiding the decode would take a Rust-to-Python converter for every kind 
of expression.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. A merge, a `writeTo` write, an AutoCDC flow or a function registration 
with an expression deeper than 745 levels now raises `RecursionError`, before 
any request. Pickling such a Column and its `to_plan` raise it too. Before, 
such a merge or overwrite was sent (at 5,000 levels in the review), and at 
20,000 levels the process crashed. Pickling took minutes, and crashed at 
150,000 levels.
    
    In the drop-in, a merge clause method raises `RecursionError` for a clause 
condition or assignment that deep, as PySpark's does, and the clause is not 
added.
    
    In the Rust API, the clause builders of `MergeIntoWriter` keep their 
signatures. Their expressions are serialized, and fail, in `merge()`. 
`Expression::try_to_proto` and `Column::try_to_proto` are new.
    
    ### How was this patch tested?
    
    New tests:
    
    - 
`expression::tests::deep_expressions_of_commands_are_recursion_errors_as_pyspark`
 (`crates/spark-connect/src/expression.rs`, after 
`deep_expressions_do_not_overflow_a_small_stack`). On a 512 KiB thread, with a 
100,000-level column, each of these is a `RecursionError` of the bound: a merge 
condition, a `when_not_matched_by_source` condition, a `when_not_matched` 
insert assignment, a `write_to` overwrite condition, a `partition_by` column of 
`create()`, an argument of `register_functi [...]
    - 
`test_a_command_expression_too_deep_to_send_raises_recursion_error_as_pyspark` 
(`python/tests/test_dropin_offline.py`, after 
`test_an_expression_too_deep_to_send_raises_recursion_error_without_a_request`).
 On the mock server, at 745 and 30,000 additions, each of these raises 
`RecursionError` and no request is recorded: `merge()` with a deep merge 
condition, `whenNotMatchedBySource(deep).updateAll()`, 
`whenNotMatched().insert({"v": deep})`, `writeTo(...).overwrite(deep)`, 
`writeTo(.. [...]
    
    Each fails without the fix. I reverted the source hunks with `patch -R`, 
rebuilt and ran the tests:
    
    - The Rust test aborts the test binary: "thread '<unknown>' has overflowed 
its stack", SIGABRT. It does the same with only `merge.rs`, only 
`readwriter.rs`, only `session.rs` or only `group.rs` reverted.
    - The Python test fails with `DID NOT RAISE <class 'RecursionError'>` at 
its first merge.
    
    Commands run (macOS, release unless noted):
    
    - `cargo test -p apache-spark-connect --release --lib -- deep_expressions 
merge v2_ v1_ grouping register udf readwriter`: 31 passed.
    - `cargo test -p apache-spark-connect --lib -- deep_expressions merge v2_` 
(debug build): 14 passed. CI runs the debug build of these tests too.
    - `python -m pytest tests/test_dropin_offline.py -k "pickle or merge or 
writeTo or write_to or auto_cdc or to_plan or too_deep or writer or grouping or 
pipeline"` with the rebuilt extension: 93 passed.
    - `SPARK_REMOTE=sc://localhost:15014 cargo test -p apache-spark-connect 
--release --test e2e_coverage --test e2e_dataframe -- 
merge_into_builder_surface read_write_roundtrip_surface dataframe_extra_surface 
group_numeric_aggregates_follow_pyspark --test-threads=1`, against a local 
Spark 4.3.0 Connect server: 4 passed.
    - `python -m pytest tests/test_dropin_e2e.py -k 
"writer_v2_takes_its_arguments or pickled_sort_columns_sort_on_the_server or 
pickled_when_columns_chain_on_the_server or merge_asof"` on that server: 4 
passed.
    - On that server, a merge with three clauses and a 
`partitionedBy(...).overwrite(...)` into a missing table get the same 
`AnalysisException` (`TABLE_OR_VIEW_NOT_FOUND`) from both this client and 
official PySpark.
    - `cargo test -p apache-spark-connect --release --no-run` and `--features 
wasm-udf --no-run`: built without warnings.
    - `cargo fmt --all --check` passes. `cargo clippy -p apache-spark-connect 
-p pyspark-rs --release --all-targets` reports nothing in the changed lines.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #492 from HyukjinKwon/SPARK-61416-command-expression-depth.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/column.rs        | 11 ++--
 crates/pyspark-rs/src/dataframe.rs     | 25 +++++++++
 crates/pyspark-rs/src/pipelines.rs     | 20 +++----
 crates/spark-connect/src/column.rs     |  7 +++
 crates/spark-connect/src/expression.rs | 96 ++++++++++++++++++++++++++++++++++
 crates/spark-connect/src/group.rs      |  8 ++-
 crates/spark-connect/src/merge.rs      | 73 ++++++++++++++++++--------
 crates/spark-connect/src/readwriter.rs | 22 ++++----
 crates/spark-connect/src/session.rs    |  4 +-
 python/tests/test_dropin_offline.py    | 53 +++++++++++++++++++
 10 files changed, 274 insertions(+), 45 deletions(-)

diff --git a/crates/pyspark-rs/src/column.rs b/crates/pyspark-rs/src/column.rs
index 2f2ddadf..cd7f12c9 100644
--- a/crates/pyspark-rs/src/column.rs
+++ b/crates/pyspark-rs/src/column.rs
@@ -5,6 +5,7 @@ use pyo3::types::PyDict;
 use spark_connect::column::Column;
 use spark_connect::expression::{Alias, ExpressionNode, NullOrdering};
 
+use crate::errors::ResultExt;
 use crate::functions::{to_column, to_value_column};
 
 /// Raise a `pyspark.errors` exception (`class_name`) carrying the given 
`error_class`
@@ -114,11 +115,13 @@ impl PyColumnExpression {
     }
 
     /// The `spark.connect.Expression` of this expression, of the generated
-    /// `pyspark.sql.connect.proto`.
+    /// `pyspark.sql.connect.proto`. One too deep to be sent is the 
`RecursionError` that
+    /// PySpark's `to_plan`, which recurses, raises.
     fn to_plan(&self, py: Python<'_>, session: &Bound<'_, PyAny>) -> 
PyResult<Py<PyAny>> {
         use prost::Message;
         let _ = session;
-        let bytes = pyo3::types::PyBytes::new(py, 
&self.column.to_proto().encode_to_vec());
+        let expression = self.column.try_to_proto().to_pyerr()?;
+        let bytes = pyo3::types::PyBytes::new(py, &expression.encode_to_vec());
         Ok(py
             .import("pyspark.sql.connect.proto")?
             .getattr("Expression")?
@@ -711,9 +714,11 @@ impl PyColumn {
     /// that `when` and `otherwise` chain on the unpickled Column. A sort 
order pickles its child
     /// Column and its sort method, as PySpark's SortOrder keeps its child and 
direction, so that
     /// 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 = pyo3::types::PyBytes::new(py, 
&self.column.to_proto().encode_to_vec());
+        let expression = self.column.try_to_proto().to_pyerr()?;
+        let expression = pyo3::types::PyBytes::new(py, 
&expression.encode_to_vec());
         let column = |expr: &spark_connect::expression::Expression| -> 
PyResult<Py<PyColumn>> {
             Py::new(py, PyColumn::new(Column::new(expr.clone())))
         };
diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index 59d91a03..b6a0d753 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -3338,6 +3338,23 @@ fn merge_clause_action(
     Ok(writer.clone_ref(py))
 }
 
+/// Serialize the condition and the assignment values of a merge clause, as 
PySpark's
+/// `_build_merge_action` does when its clause method adds the clause: one too 
deep to be sent is
+/// the `RecursionError` of PySpark's serializer there, and the clause is not 
added. The merge
+/// serializes them again when it runs.
+fn check_merge_clause(
+    condition: Option<&spark_connect::column::Column>,
+    assignments: Option<&std::collections::HashMap<String, 
spark_connect::column::Column>>,
+) -> PyResult<()> {
+    let values = assignments
+        .into_iter()
+        .flat_map(|assignments| assignments.values());
+    for column in condition.into_iter().chain(values) {
+        column.try_to_proto().to_pyerr()?;
+    }
+    Ok(())
+}
+
 #[pymethods]
 impl PyMergeIntoWriter {
     /// Nested builder-class references, mirroring pyspark's 
`MergeIntoWriter.WhenMatched`
@@ -3423,6 +3440,7 @@ impl PyWhenMatched {
     #[pyo3(name = "updateAll")]
     fn update_all(&self, py: Python<'_>) -> PyResult<Py<PyMergeIntoWriter>> {
         let cond = self.condition.clone();
+        check_merge_clause(cond.as_ref(), None)?;
         merge_clause_action(py, &self.writer, |w| 
w.when_matched(cond).update_all())
     }
 
@@ -3433,11 +3451,13 @@ impl PyWhenMatched {
     ) -> PyResult<Py<PyMergeIntoWriter>> {
         let cond = self.condition.clone();
         let map = assignments_to_map(py, assignments);
+        check_merge_clause(cond.as_ref(), Some(&map))?;
         merge_clause_action(py, &self.writer, |w| 
w.when_matched(cond).update(map))
     }
 
     fn delete(&self, py: Python<'_>) -> PyResult<Py<PyMergeIntoWriter>> {
         let cond = self.condition.clone();
+        check_merge_clause(cond.as_ref(), None)?;
         merge_clause_action(py, &self.writer, |w| 
w.when_matched(cond).delete())
     }
 }
@@ -3455,6 +3475,7 @@ impl PyWhenNotMatched {
     #[pyo3(name = "insertAll")]
     fn insert_all(&self, py: Python<'_>) -> PyResult<Py<PyMergeIntoWriter>> {
         let cond = self.condition.clone();
+        check_merge_clause(cond.as_ref(), None)?;
         merge_clause_action(py, &self.writer, |w| 
w.when_not_matched(cond).insert_all())
     }
 
@@ -3465,6 +3486,7 @@ impl PyWhenNotMatched {
     ) -> PyResult<Py<PyMergeIntoWriter>> {
         let cond = self.condition.clone();
         let map = assignments_to_map(py, assignments);
+        check_merge_clause(cond.as_ref(), Some(&map))?;
         merge_clause_action(py, &self.writer, |w| 
w.when_not_matched(cond).insert(map))
     }
 }
@@ -3482,6 +3504,7 @@ impl PyWhenNotMatchedBySource {
     #[pyo3(name = "updateAll")]
     fn update_all(&self, py: Python<'_>) -> PyResult<Py<PyMergeIntoWriter>> {
         let cond = self.condition.clone();
+        check_merge_clause(cond.as_ref(), None)?;
         merge_clause_action(py, &self.writer, |w| {
             w.when_not_matched_by_source(cond).update_all()
         })
@@ -3494,6 +3517,7 @@ impl PyWhenNotMatchedBySource {
     ) -> PyResult<Py<PyMergeIntoWriter>> {
         let cond = self.condition.clone();
         let map = assignments_to_map(py, assignments);
+        check_merge_clause(cond.as_ref(), Some(&map))?;
         merge_clause_action(py, &self.writer, |w| {
             w.when_not_matched_by_source(cond).update(map)
         })
@@ -3501,6 +3525,7 @@ impl PyWhenNotMatchedBySource {
 
     fn delete(&self, py: Python<'_>) -> PyResult<Py<PyMergeIntoWriter>> {
         let cond = self.condition.clone();
+        check_merge_clause(cond.as_ref(), None)?;
         merge_clause_action(py, &self.writer, |w| {
             w.when_not_matched_by_source(cond).delete()
         })
diff --git a/crates/pyspark-rs/src/pipelines.rs 
b/crates/pyspark-rs/src/pipelines.rs
index 3e273278..a1ef0555 100644
--- a/crates/pyspark-rs/src/pipelines.rs
+++ b/crates/pyspark-rs/src/pipelines.rs
@@ -211,24 +211,26 @@ pub fn pipeline_define_auto_cdc_flow(
     track_history_except_column_list: Option<Vec<PyRef<'_, PyColumn>>>,
     sql_conf: Option<HashMap<String, String>>,
 ) -> PyResult<()> {
-    let to_expr = |c: &PyColumn| c.column.expression().to_proto();
+    // As a request serializes its expressions: one too deep to be sent is the 
RecursionError of
+    // PySpark's serializer, before any request.
+    let to_expr = |c: &PyColumn| c.column.try_to_proto().to_pyerr();
     let to_exprs = |cs: Option<Vec<PyRef<'_, PyColumn>>>| {
         cs.unwrap_or_default()
             .iter()
             .map(|c| to_expr(c))
-            .collect::<Vec<_>>()
+            .collect::<PyResult<Vec<_>>>()
     };
     let details = proto::pipeline_command::define_flow::AutoCdcFlowDetails {
         source: Some(source),
-        keys: keys.iter().map(|c| to_expr(c)).collect(),
-        sequence_by: Some(to_expr(&sequence_by)),
-        apply_as_deletes: apply_as_deletes.as_ref().map(|c| to_expr(c)),
+        keys: keys.iter().map(|c| to_expr(c)).collect::<PyResult<_>>()?,
+        sequence_by: Some(to_expr(&sequence_by)?),
+        apply_as_deletes: apply_as_deletes.as_ref().map(|c| 
to_expr(c)).transpose()?,
         apply_as_truncates: None,
-        column_list: to_exprs(column_list),
-        except_column_list: to_exprs(except_column_list),
+        column_list: to_exprs(column_list)?,
+        except_column_list: to_exprs(except_column_list)?,
         stored_as_scd_type,
-        track_history_column_list: to_exprs(track_history_column_list),
-        track_history_except_column_list: 
to_exprs(track_history_except_column_list),
+        track_history_column_list: to_exprs(track_history_column_list)?,
+        track_history_except_column_list: 
to_exprs(track_history_except_column_list)?,
         ignore_null_updates_column_list: vec![],
         ignore_null_updates_except_column_list: vec![],
     };
diff --git a/crates/spark-connect/src/column.rs 
b/crates/spark-connect/src/column.rs
index 6729036f..00b86efd 100644
--- a/crates/spark-connect/src/column.rs
+++ b/crates/spark-connect/src/column.rs
@@ -393,6 +393,13 @@ impl Column {
         self.expr.to_proto()
     }
 
+    /// Convert to proto expression as a request serializes it: an expression 
deeper than
+    /// [`crate::expression::MAX_EXPRESSION_DEPTH`] is a `RecursionError`, as 
PySpark's
+    /// serializer raises it (see [`Expression::try_to_proto`]).
+    pub fn try_to_proto(&self) -> 
spark_connect_core::error::Result<proto::Expression> {
+        self.expr.try_to_proto()
+    }
+
     /// 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/expression.rs 
b/crates/spark-connect/src/expression.rs
index a2fdf832..ed129136 100644
--- a/crates/spark-connect/src/expression.rs
+++ b/crates/spark-connect/src/expression.rs
@@ -563,6 +563,16 @@ impl Expression {
         })
     }
 
+    /// Converts the expression to a Spark Connect protobuf expression as a 
request serializes
+    /// it, outside the plan of a relation: the expressions of a command, such 
as the condition of
+    /// a merge or of an overwrite, and of a pickled Column. One deeper than
+    /// [`MAX_EXPRESSION_DEPTH`] is a `RecursionError`, as PySpark's 
serializer raises it before
+    /// any request is sent, and its proto is not built past the bound: prost 
encodes and drops a
+    /// proto by recursing, so a deeper one could overflow the stack there.
+    pub fn try_to_proto(&self) -> Result<proto::Expression> {
+        with_expression_depth_bound(|| self.to_proto())
+    }
+
     fn to_proto_with_origin(&self) -> proto::Expression {
         let mut expr = self.node_to_proto();
         if let Some(origin) = &self.origin {
@@ -1819,6 +1829,92 @@ mod tests {
             .unwrap();
     }
 
+    /// The expressions of a command are serialized as those of a plan: as 
PySpark's serializer,
+    /// which raises `RecursionError` for a merge condition or an overwrite 
condition of about
+    /// 1,000 levels before any request, one deeper than 
`MAX_EXPRESSION_DEPTH` is a
+    /// `RecursionError`, rather than a request whose proto overflows the 
stack where it is
+    /// encoded or dropped. The session has no server and does not retry, so a 
request that the
+    /// client should not send fails the test at once.
+    #[test]
+    fn deep_expressions_of_commands_are_recursion_errors_as_pyspark() {
+        use crate::column::{col, Column};
+
+        std::thread::Builder::new()
+            .stack_size(512 << 10)
+            .spawn(|| {
+                let builder =
+                    
spark_connect_core::channel::ChannelBuilder::parse("sc://127.0.0.1:1")
+                        .expect("valid URL");
+                let mut client = spark_connect_core::runtime::block_on(
+                    
spark_connect_core::client::SparkConnectClient::connect(&builder),
+                )
+                .expect("failed to build client");
+                
client.set_retry_policy(spark_connect_core::retries::RetryPolicy::no_retries());
+                let spark = crate::session::SparkSession::new(client);
+                let df = spark.range(3).unwrap();
+                let deep = Column::new(chained_additions(100_000));
+                let assert_too_deep = |result: Result<()>| {
+                    let error = result.expect_err("too deep to be sent");
+                    assert_eq!(
+                        error.kind,
+                        
spark_connect_core::error::SparkErrorKind::RecursionError,
+                        "{error}"
+                    );
+                    assert!(
+                        error
+                            .message()
+                            .contains("an expression may be at most 745 levels 
deep"),
+                        "{error}"
+                    );
+                };
+
+                // The condition of a merge, and the condition and an 
assignment of its clauses.
+                assert_too_deep(
+                    df.merge_into("t", deep.clone())
+                        .when_matched(None)
+                        .update_all()
+                        .merge(),
+                );
+                assert_too_deep(
+                    df.merge_into("t", col("id"))
+                        .when_not_matched_by_source(Some(deep.clone()))
+                        .delete()
+                        .merge(),
+                );
+                let assignments =
+                    std::collections::HashMap::from([("v".to_string(), 
deep.clone())]);
+                assert_too_deep(
+                    df.merge_into("t", col("id"))
+                        .when_not_matched(None)
+                        .insert(assignments)
+                        .merge(),
+                );
+                // The condition of an overwrite, and a partitioning column of 
`writeTo`.
+                assert_too_deep(df.write_to("t").overwrite(deep.clone()));
+                
assert_too_deep(df.write_to("t").partition_by([deep.clone()]).create());
+                // An argument of a function to register.
+                let function = 
crate::udf::CommonInlineUserDefinedFunctionExpression::new(
+                    "f".to_string(),
+                    false,
+                    vec![deep.expression().clone()],
+                    crate::udf::PythonUDFPayload::new(
+                        DataType::Integer,
+                        crate::udf::eval_type::SQL_BATCHED_UDF,
+                        vec![0],
+                        "3.11".to_string(),
+                    ),
+                );
+                assert_too_deep(spark.register_function(function));
+                // The grouping sets of a column too deep to be sent group it, 
and the plan of
+                // the grouping is the `RecursionError`.
+                let grouped = df.grouping_sets(vec![vec![deep.clone()], 
vec![deep.clone()]]);
+                assert_too_deep(grouped.count().to_relation().map(drop));
+            })
+            .unwrap()
+            .join()
+            .unwrap();
+    }
+
     #[test]
     fn test_literal_integer() {
         let lit = LiteralExpression::int(42);
diff --git a/crates/spark-connect/src/group.rs 
b/crates/spark-connect/src/group.rs
index 73e92e44..c288705d 100644
--- a/crates/spark-connect/src/group.rs
+++ b/crates/spark-connect/src/group.rs
@@ -165,7 +165,13 @@ impl GroupedData {
         let mut group_cols: Vec<Column> = Vec::new();
         for set in &grouping_sets {
             for col in set {
-                let key = 
prost::Message::encode_to_vec(&col.expression().clone().to_proto());
+                // Serialized as a request serializes it: a column too deep to 
be sent is kept,
+                // and the request of the grouping fails with its 
`RecursionError`.
+                let Ok(expression) = col.try_to_proto() else {
+                    group_cols.push(col.clone());
+                    continue;
+                };
+                let key = prost::Message::encode_to_vec(&expression);
                 if !seen.contains(&key) {
                     seen.push(key);
                     group_cols.push(col.clone());
diff --git a/crates/spark-connect/src/merge.rs 
b/crates/spark-connect/src/merge.rs
index 0bf5ac54..cc4b76c7 100644
--- a/crates/spark-connect/src/merge.rs
+++ b/crates/spark-connect/src/merge.rs
@@ -18,23 +18,47 @@ fn merge_action(
     action_type: proto::merge_action::ActionType,
     condition: Option<&Column>,
     assignments: Option<HashMap<String, Column>>,
-) -> proto::Expression {
-    let mut action = proto::MergeAction::default();
-    action.action_type = action_type as i32;
-    action.condition = condition.map(|c| Box::new(c.to_proto()));
-    if let Some(assignments) = assignments {
-        action.assignments = assignments
-            .into_iter()
-            .map(|(k, v)| proto::merge_action::Assignment {
+) -> MergeClause {
+    MergeClause {
+        action_type,
+        condition: condition.cloned(),
+        assignments,
+    }
+}
+
+/// A clause of a merge: its action, and its condition and assignments, which 
are serialized when
+/// the merge runs, as a request serializes them (see 
[`MergeIntoWriter::merge`]).
+#[derive(Clone)]
+struct MergeClause {
+    action_type: proto::merge_action::ActionType,
+    condition: Option<Column>,
+    assignments: Option<HashMap<String, Column>>,
+}
+
+impl MergeClause {
+    /// The `MergeAction` expression of the clause, as PySpark's 
`_build_merge_action` builds it.
+    fn to_proto(&self) -> Result<proto::Expression> {
+        let assignments = self.assignments.iter().flatten().map(|(k, v)| {
+            Ok(proto::merge_action::Assignment {
                 // Mirrors the reference `expr(k)` for the assignment target.
-                key: Some(crate::functions::expr(&k).to_proto()),
-                value: Some(v.to_proto()),
+                key: Some(crate::functions::expr(k).try_to_proto()?),
+                value: Some(v.try_to_proto()?),
             })
-            .collect();
+        });
+        let action = proto::MergeAction {
+            action_type: self.action_type as i32,
+            assignments: assignments.collect::<Result<_>>()?,
+            condition: self
+                .condition
+                .as_ref()
+                .map(|c| c.try_to_proto().map(Box::new))
+                .transpose()?,
+        };
+        Ok(proto::Expression {
+            expr_type: 
Some(proto::expression::ExprType::MergeAction(Box::new(action))),
+            ..Default::default()
+        })
     }
-    let mut expr = proto::Expression::default();
-    expr.expr_type = 
Some(proto::expression::ExprType::MergeAction(Box::new(action)));
-    expr
 }
 
 /// Fluent builder for a MERGE INTO command. Create it via 
[`crate::dataframe::DataFrame::merge_into`].
@@ -45,9 +69,9 @@ pub struct MergeIntoWriter {
     target_table: String,
     condition: Column,
     schema_evolution: bool,
-    matched_actions: Vec<proto::Expression>,
-    not_matched_actions: Vec<proto::Expression>,
-    not_matched_by_source_actions: Vec<proto::Expression>,
+    matched_actions: Vec<MergeClause>,
+    not_matched_actions: Vec<MergeClause>,
+    not_matched_by_source_actions: Vec<MergeClause>,
     execution: Option<crate::dataframe::ExecutionSlot>,
 }
 
@@ -127,15 +151,20 @@ impl MergeIntoWriter {
         self
     }
 
-    /// Execute the merge.
+    /// Execute the merge. As PySpark's serializer, it fails with a 
`RecursionError`, before any
+    /// request is sent, if its condition, or a condition or an assignment of 
one of its clauses,
+    /// is deeper than [`crate::expression::MAX_EXPRESSION_DEPTH`].
     pub fn merge(mut self) -> Result<()> {
+        let actions = |clauses: &[MergeClause]| -> 
Result<Vec<proto::Expression>> {
+            clauses.iter().map(MergeClause::to_proto).collect()
+        };
         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)?),
-            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),
-            not_matched_by_source_actions: std::mem::take(&mut 
self.not_matched_by_source_actions),
+            merge_condition: Some(self.condition.try_to_proto()?),
+            match_actions: actions(&self.matched_actions)?,
+            not_matched_actions: actions(&self.not_matched_actions)?,
+            not_matched_by_source_actions: 
actions(&self.not_matched_by_source_actions)?,
             with_schema_evolution: self.schema_evolution,
         };
         self.run(proto::command::CommandType::MergeIntoTableCommand(cmd))
diff --git a/crates/spark-connect/src/readwriter.rs 
b/crates/spark-connect/src/readwriter.rs
index 515c3e4d..cff16e54 100644
--- a/crates/spark-connect/src/readwriter.rs
+++ b/crates/spark-connect/src/readwriter.rs
@@ -610,22 +610,28 @@ impl DataFrameWriterV2 {
         self
     }
 
-    /// Build the `WriteOperationV2` command proto for the given mode.
+    /// Build the `WriteOperationV2` command proto for the given mode. As 
PySpark's serializer,
+    /// it fails with a `RecursionError`, before any request is sent, if a 
partitioning column or
+    /// the overwrite condition is deeper than 
[`crate::expression::MAX_EXPRESSION_DEPTH`].
     pub(crate) fn build_operation(
         &self,
         mode: proto::write_operation_v2::Mode,
-        overwrite_condition: Option<proto::Expression>,
+        overwrite_condition: Option<&Column>,
     ) -> Result<proto::WriteOperationV2> {
         let mut op = proto::WriteOperationV2::default();
         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();
+        op.partitioning_columns = self
+            .partition_cols
+            .iter()
+            .map(Column::try_to_proto)
+            .collect::<Result<_>>()?;
         op.clustering_columns = self.cluster_cols.clone();
         op.options = self.options.clone();
         op.table_properties = self.table_properties.clone();
         op.mode = mode as i32;
-        op.overwrite_condition = overwrite_condition;
+        op.overwrite_condition = 
overwrite_condition.map(Column::try_to_proto).transpose()?;
         Ok(op)
     }
 
@@ -656,10 +662,8 @@ impl DataFrameWriterV2 {
 
     /// Overwrite rows matching `condition` with the DataFrame's rows.
     pub fn overwrite(self, condition: Column) -> Result<()> {
-        let op = self.build_operation(
-            proto::write_operation_v2::Mode::Overwrite,
-            Some(condition.to_proto()),
-        )?;
+        let op =
+            self.build_operation(proto::write_operation_v2::Mode::Overwrite, 
Some(&condition))?;
         self.run(proto::command::CommandType::WriteOperationV2(op))
     }
 
@@ -822,7 +826,7 @@ mod tests {
             .write_to("t")
             .build_operation(
                 proto::write_operation_v2::Mode::Overwrite,
-                Some(crate::column::col("id").to_proto()),
+                Some(&crate::column::col("id")),
             )
             .unwrap();
         assert_eq!(op.mode, proto::write_operation_v2::Mode::Overwrite as i32);
diff --git a/crates/spark-connect/src/session.rs 
b/crates/spark-connect/src/session.rs
index 1ca809c7..7ec8b520 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -1173,9 +1173,11 @@ impl SparkSession {
         &self,
         udf: crate::udf::CommonInlineUserDefinedFunctionExpression,
     ) -> Result<()> {
+        // An argument of the function is serialized as a request serializes 
its expressions.
+        let function = crate::expression::with_expression_depth_bound(|| 
udf.to_proto())?;
         crate::dataframe::execute_command_unreported(
             self,
-            proto::command::CommandType::RegisterFunction(udf.to_proto()),
+            proto::command::CommandType::RegisterFunction(function),
         )
     }
 
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index a04644d2..cdbdd157 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -15907,6 +15907,59 @@ def 
test_an_expression_too_deep_to_send_raises_recursion_error_without_a_request
     assert len(service.execute_requests) == 1
 
 
+def 
test_a_command_expression_too_deep_to_send_raises_recursion_error_as_pyspark(mock_connect):
+    # As PySpark, whose serializer raises RecursionError, before any request, 
for an expression of
+    # about 1,000 levels as a merge condition, a condition or an assignment of 
a merge clause (as
+    # the clause method adds the clause, which is not added then), a 
partitioning column or an
+    # overwrite condition, and as it pickles a Column or builds its to_plan; 
20,000 levels killed
+    # the process, and pickling took minutes. 744 additions, the 745 levels of 
the bound, are sent.
+    import pickle
+
+    from pyspark.sql import functions as F
+
+    spark, service = mock_connect
+
+    def chained(additions):
+        c = F.col("id")
+        for _ in range(additions):
+            c = c + 1
+        return c
+
+    df = spark.range(3).alias("s")
+    writer = df.mergeInto("t", F.col("id")).whenMatched().delete()
+    too_deep = "an expression may be at most 745 levels"
+    for additions in [745, 30_000]:
+        deep = chained(additions)
+        with pytest.raises(RecursionError, match=too_deep):
+            df.mergeInto("t", deep).whenMatched().updateAll().merge()
+        with pytest.raises(RecursionError, match=too_deep):
+            writer.whenNotMatchedBySource(deep).updateAll()
+        with pytest.raises(RecursionError, match=too_deep):
+            writer.whenNotMatched().insert({"v": deep})
+        with pytest.raises(RecursionError, match=too_deep):
+            df.writeTo("t").overwrite(deep)
+        with pytest.raises(RecursionError, match=too_deep):
+            df.writeTo("t").partitionedBy(deep).create()
+        with pytest.raises(RecursionError, match=too_deep):
+            pickle.dumps(deep)
+        with pytest.raises(RecursionError, match=too_deep):
+            deep._expr.to_plan(spark.client)
+        del deep
+    assert service.execute_requests == []
+    # The merge sends the one clause that was added: 
ExecutePlanRequest.plan=3, Plan.command=2,
+    # Command.merge_into_table_command=16, of match_actions=4, 
not_matched_actions=5 and
+    # not_matched_by_source_actions=6.
+    writer.merge()
+    plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+    merge = parse_message(parse_message(plan[2][0])[16][0])
+    assert [len(merge.get(field, [])) for field in [4, 5, 6]] == [1, 0, 0]
+    at_bound = chained(744)
+    df.mergeInto("t", at_bound).whenMatched(at_bound).update({"v": 
at_bound}).merge()
+    df.writeTo("t").partitionedBy(at_bound).overwrite(at_bound)
+    assert len(service.execute_requests) == 3
+    assert pickle.dumps(at_bound)
+
+
 def test_window_and_lambda_reprs_as_pyspark():
     import re
 


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

Reply via email to