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 d97ad42f [SPARK-61222][CONNECT][PYTHON] Raise PicklingError, as
PySpark does, for a function or data source that does not pickle
d97ad42f is described below
commit d97ad42f5ab4bea383e5e24d653525f5a58faf75
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Mon Nov 9 17:08:46 2026 +0900
[SPARK-61222][CONNECT][PYTHON] Raise PicklingError, as PySpark does, for a
function or data source that does not pickle
### What changes were proposed in this pull request?
[SPARK-61222](https://issues.apache.org/jira/browse/SPARK-61222): Raise
`pickle.PicklingError` ("Could not serialize object: ...") for a function or
data source that does not pickle in these methods, as PySpark does.
The Rust client pickled these commands with `pyspark.cloudpickle.dumps`
directly, which raises the bare `TypeError` of cloudpickle. It now pickles them
with `pyspark.serializers.CloudPickleSerializer().dumps`, which PySpark uses
for the Python function of these calls (`pyspark/sql/connect/expressions.py`)
and for the data source class (`pyspark/sql/connect/plan.py`). The bytes of a
pickled object are unchanged; only the error for an object that does not pickle
changes, to the class an [...]
### Why are the changes needed?
A function that does not pickle, such as a closure holding
`threading.Lock()`, raised `TypeError: cannot pickle '_thread.lock' object`
from these calls. Official PySpark 4.3.0 raises `pickle.PicklingError: Could
not serialize object: TypeError: cannot pickle '_thread.lock' object`, so
`except pickle.PicklingError` did not catch it here. Scalar and pandas UDFs,
UDTFs and streaming `foreach` already raised `PicklingError`.
For example, `df.groupBy("id").applyInPandas(lambda pdf: (lock, pdf)[1],
"id long")` with a lock `lock` raised a `TypeError` in this client, and a
`PicklingError` in PySpark.
### Does this PR introduce _any_ user-facing change?
Yes. A function or data source that does not pickle now raises
`pickle.PicklingError` with PySpark's message, instead of a plain `TypeError`,
from applyInPandas, applyInArrow, mapInPandas, mapInArrow, cogroup,
transformWithState, transformWithStateInPandas and `spark.dataSource.register`.
### How was this patch tested?
- Added `test_unpicklable_functions_raise_picklingerror_as_pyspark` to
`test_dropin_offline.py`. It checks that each of the nine calls raises exactly
`pickle.PicklingError` whose message starts with "Could not serialize object: "
and contains "cannot pickle". The test fails without this change (`TypeError:
cannot pickle '_thread.lock' object`) and passes with it. The same classes and
messages were checked against official PySpark 4.3.0 on a live Connect server
for transformWithStateIn [...]
- The lib tests of both crates (658 passed), the build of all tests, also
with `wasm-udf`, the offline Python suites (2704 passed, 8 skipped), and the
live drop-in and Arrow suites (224 passed) and live cases (12 passed) against a
local Spark 4.3.0 server. Clippy reports no diagnostics in the changed lines.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5
This pull request and its description were written by Isaac.
Closes #404 from HyukjinKwon/SPARK-61222-fu-p3.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/dataframe.rs | 12 ++++++----
python/tests/test_dropin_offline.py | 45 +++++++++++++++++++++++++++++++++++++
2 files changed, 53 insertions(+), 4 deletions(-)
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index bc2a5aa1..b7244bd1 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -3999,11 +3999,15 @@ pub(crate) fn detached<T: Send>(
/// cloudpickle an arbitrary Python object to bytes (mirrors the scalar UDF
path,
/// where the client serializes the callable for server-side execution).
///
-/// Uses the bundled `pyspark.cloudpickle` (the skin vendors it, matching the
worker's
-/// `pyspark.cloudpickle`), so there is no external `cloudpickle` runtime
dependency.
+/// Uses `CloudPickleSerializer().dumps` as PySpark does, which raises a
`pickle.PicklingError`
+/// ("Could not serialize object: ...") for an object that does not pickle,
rather than the
+/// bare pickling error of `cloudpickle`.
pub(crate) fn py_cloudpickle(py: Python<'_>, obj: &Bound<'_, PyAny>) ->
PyResult<Vec<u8>> {
- let cp = py.import("pyspark.cloudpickle")?;
- cp.call_method1("dumps", (obj,))?.extract()
+ let serializer = py
+ .import("pyspark.serializers")?
+ .getattr("CloudPickleSerializer")?
+ .call0()?;
+ serializer.call_method1("dumps", (obj,))?.extract()
}
/// The running Python's "major.minor" (recorded in the UDF payload).
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 388466e8..24aba59f 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -5639,6 +5639,51 @@ def test_functions_next_day():
assert type(F.next_day(c, "Monday")).__name__ == "Column"
+def test_unpicklable_functions_raise_picklingerror_as_pyspark(mock_connect):
+ # As PySpark's CloudPickleSerializer().dumps: a function of applyInPandas,
applyInArrow,
+ # mapInPandas, mapInArrow, cogroup, transformWithState(InPandas) or a data
source class
+ # that does not pickle raises pickle.PicklingError "Could not serialize
object: ...", not
+ # the bare TypeError of cloudpickle.
+ import pickle
+ import threading
+
+ from pyspark.sql.datasource import DataSource
+
+ spark, _ = mock_connect
+ df = spark.range(2)
+ grouped = df.groupBy("id")
+ lock = threading.Lock()
+
+ class Processor:
+ def __init__(self):
+ self.lock = lock
+
+ class Source(DataSource):
+ @classmethod
+ def name(cls):
+ return "unpicklable"
+
+ def reader(self, schema):
+ return lock
+
+ unpicklable = [
+ lambda: grouped.applyInPandas(lambda pdf: (lock, pdf)[1], "id long"),
+ lambda: grouped.applyInArrow(lambda table: (lock, table)[1], "id
long"),
+ lambda: df.mapInPandas(lambda it: ((lock, p)[1] for p in it), "id
long"),
+ lambda: df.mapInArrow(lambda it: ((lock, p)[1] for p in it), "id
long"),
+ lambda: grouped.cogroup(grouped).applyInPandas(lambda a, b: (lock,
a)[1], "id long"),
+ lambda: grouped.cogroup(grouped).applyInArrow(lambda a, b: (lock,
a)[1], "id long"),
+ lambda: grouped.transformWithStateInPandas(Processor(), "id long",
"append", "NoTimeMode"),
+ lambda: grouped.transformWithState(Processor(), "id long", "append",
"NoTimeMode"),
+ lambda: spark.dataSource.register(Source),
+ ]
+ for call in unpicklable:
+ with pytest.raises(pickle.PicklingError, match="^Could not serialize
object: ") as e:
+ call()
+ assert type(e.value) is pickle.PicklingError
+ assert "cannot pickle" in str(e.value)
+
+
def test_functions_quarter():
"""Test quarter function."""
from pyspark.sql import functions as F
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]