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 888ecff5 [SPARK-61402][CONNECT][PYTHON] Pickle VariantVal, Geometry
and Geography as PySpark's plain classes in the Python client, so that the
server's Python workers load them
888ecff5 is described below
commit 888ecff5abeec42321a137221e11a0bf07859449
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 08:42:46 2026 +0900
[SPARK-61402][CONNECT][PYTHON] Pickle VariantVal, Geometry and Geography as
PySpark's plain classes in the Python client, so that the server's Python
workers load them
### What changes were proposed in this pull request?
[SPARK-61402](https://issues.apache.org/jira/browse/SPARK-61402):
`VariantVal`, `Geometry` and `Geography` of the Python client pickle as PySpark
pickles its plain classes, and `Geometry` and `Geography` can be subclassed, as
`VariantVal` can since SPARK-61291 (#471).
In `crates/pyspark-rs/src/values.rs`:
- A value pickles as `copyreg.__newobj__` of its class, with the state that
`object.__reduce_ex__` gives a plain class. That state is the dict of its
instance attributes and its fields (`value`/`metadata`, or `wkb`/`srid`), or
`(dict, slots)` for a subclass that has slots.
- `__setstate__` takes that state and also PySpark's pickles of the
classes. The fields go to the Rust fields and the rest to the instance's
`__dict__` and slots.
- `Geometry` and `Geography` get `subclass`, a `__new__` that takes any
arguments, and an `__init__(wkb, srid)`, as `VariantVal` has.
### Why are the changes needed?
- SPARK-61291 pickled a `VariantVal`'s state as the tuple `(value,
metadata, __dict__)`. PySpark's `VariantVal` is a plain class without
`__setstate__`, and pickle's BUILD gives such a class a dict state only. So
official PySpark cannot load a `VariantVal` that the Python client pickled:
```
_pickle.UnpicklingError: state is not a dictionary
```
The server's Python workers run official PySpark. So a UDF, pandas UDF,
UDTF, `foreachBatch` or other function that refers to a `VariantVal` fails on
the server. With a UDF that returns `v.toJson()` of a collected
`parse_json('{"a":1}')`:
| Client | Result |
|---|---|
| master | `PythonException: ... _pickle.UnpicklingError: state is not a
dictionary` |
| before SPARK-61291 | `[Row(j='{"a":1}')]` |
| official PySpark | `[Row(j='{"a":1}')]` |
- The `Geometry` and `Geography` values of the Python client could not be
pickled, copied or subclassed at all. The errors were `TypeError: cannot pickle
'pyspark.sql.types.Geometry' object` and `type 'pyspark.sql.types.Geometry' is
not an acceptable base type`. So a `Row` that holds one could not be pickled or
deep-copied either, and a UDF that refers to one could not be sent. PySpark's
are plain classes, which support all of these.
- A subclass of `VariantVal` with `__slots__` lost the values of its slots
in a pickle. PySpark keeps them.
- PySpark's own pickles of these classes did not load in the Python client:
`TypeError: argument 'state': 'dict' object is not an instance of 'tuple'`.
### Does this PR introduce _any_ user-facing change?
Yes, in the Python client, as PySpark behaves:
- UDFs and other server-side Python functions that refer to a `VariantVal`,
`Geometry` or `Geography` run.
- `Geometry` and `Geography` values, and the Rows that hold them, can be
pickled and copied.
- `Geometry` and `Geography` can be subclassed.
- PySpark's pickles of the three classes load.
### How was this patch tested?
- New offline tests in `python/tests/test_dropin_offline.py`, placed before
`test_str_of_variant_values_is_their_json_and_they_are_no_rows_as_pyspark`:
-
`test_variant_and_spatial_values_pickle_as_pysparks_plain_classes_which_load_them`,
at every protocol from 2 up:
- an unpickler that resolves the three classes to plain classes like
PySpark's loads the client's pickles, with their attributes;
- PySpark's byte-exact pickles of the classes load in the client. The
test makes them by pickling a plain class while `pyspark.sql.types.<name>` is
temporarily that class.
- `test_spatial_values_copy_pickle_and_are_subclassed_as_pyspark`:
- `copy`, `deepcopy` and pickling of `Geometry` and `Geography`, also
in a `Row`;
- subclasses whose `__init__` takes another argument, which unpickling
does not run;
- the slots of a subclass of `VariantVal`.
- A new live test in `python/tests/test_dropin_e2e.py`, placed before
`test_create_dataframe_of_multi_and_categorical_labels_as_pyspark`:
`test_udfs_that_refer_to_variant_and_spatial_values_run_on_the_server_as_pyspark`
runs a UDF that refers to a collected `VariantVal`, a `Geometry` and a
`Geography` against a local Spark 4.3.0 server.
- Without the fix, on a build of master:
- the first offline test fails with `_pickle.UnpicklingError: state is
not a dictionary`;
- the module of the second does not import (`not an acceptable base
type`);
- the live test fails with `cannot pickle 'pyspark.sql.types.Geography'
object`.
- A `VariantVal` pickled by the fixed client loads in official PySpark
4.3.0.
- The offline Python suites, the existing VariantVal, Geometry and
Geography tests (offline and live), `cargo fmt --all --check`, and clippy,
which reports nothing in `values.rs`.
### 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 #476 from HyukjinKwon/SPARK-61402-value-classes-pickle.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/values.rs | 207 +++++++++++++++++++++++++++++++-----
python/tests/test_dropin_e2e.py | 18 ++++
python/tests/test_dropin_offline.py | 100 +++++++++++++++++
3 files changed, 297 insertions(+), 28 deletions(-)
diff --git a/crates/pyspark-rs/src/values.rs b/crates/pyspark-rs/src/values.rs
index 253cf820..752f9ed1 100644
--- a/crates/pyspark-rs/src/values.rs
+++ b/crates/pyspark-rs/src/values.rs
@@ -2,7 +2,74 @@
//! mirroring `pyspark.sql.types.{VariantVal, Geometry, Geography}`.
use pyo3::prelude::*;
-use pyo3::types::{PyBytes, PyDict, PyTuple};
+use pyo3::types::{PyBytes, PyDict, PyString, PyTuple};
+
+/// Pickle `slf` as PySpark pickles its plain class: rebuilt by
`copyreg.__newobj__`, without
+/// `__init__`, with the state `object.__reduce_ex__` gives, the dict of its
instance attributes
+/// and `fields`, or that dict and the values of its slots, `(dict, slots)`,
for a subclass of
+/// slots. PySpark's class, which has no `__setstate__`, takes this state as
its attributes, so
+/// a value pickled here loads in PySpark, as in the server's Python workers.
+fn reduce_as_a_plain_class<'py>(
+ slf: &Bound<'py, PyAny>,
+ fields: [(&str, Bound<'py, PyAny>); 2],
+) -> PyResult<Bound<'py, PyTuple>> {
+ let py = slf.py();
+ let copyreg = py.import("copyreg")?;
+ let attributes = slf.getattr("__dict__")?.cast::<PyDict>()?.copy()?;
+ for (name, value) in fields {
+ attributes.set_item(name, value)?;
+ }
+ let slots = PyDict::new(py);
+ for name in copyreg
+ .call_method1("_slotnames", (slf.get_type(),))?
+ .try_iter()?
+ {
+ let name = name?.cast_into::<PyString>()?;
+ // As `object.__getstate__`: the slots that have a value.
+ if let Ok(value) = slf.getattr(&name) {
+ slots.set_item(name, value)?;
+ }
+ }
+ let state = if slots.is_empty() {
+ attributes.into_any()
+ } else {
+ PyTuple::new(py, [attributes.into_any(), slots.into_any()])?.into_any()
+ };
+ let args = PyTuple::new(py, [slf.get_type().into_any()])?;
+ PyTuple::new(py, [copyreg.getattr("__newobj__")?, args.into_any(), state])
+}
+
+/// Restore on `slf` a state of [`reduce_as_a_plain_class`], or of PySpark's
pickle of its plain
+/// class, as pickle's BUILD restores a plain class: its instance attributes,
and its slots of a
+/// `(dict, slots)`. The values of `fields`, which are not instance attributes
here, are returned.
+fn restore_plain_class_state<'py>(
+ slf: &Bound<'py, PyAny>,
+ state: &Bound<'py, PyAny>,
+ fields: [&str; 2],
+) -> PyResult<[Option<Bound<'py, PyAny>>; 2]> {
+ let (attributes, slots) = match state.cast::<PyTuple>() {
+ Ok(pair) if pair.len() == 2 => (pair.get_item(0)?,
Some(pair.get_item(1)?)),
+ _ => (state.clone(), None),
+ };
+ let mut values = [None, None];
+ if !attributes.is_none() {
+ let attributes = attributes.cast::<PyDict>()?.copy()?;
+ for (value, name) in values.iter_mut().zip(fields) {
+ if let Some(field) = attributes.get_item(name)? {
+ attributes.del_item(name)?;
+ *value = Some(field);
+ }
+ }
+ slf.getattr("__dict__")?
+ .call_method1("update", (attributes,))?;
+ }
+ if let Some(slots) = slots.filter(|slots| !slots.is_none()) {
+ for (name, value) in slots.cast::<PyDict>()?.iter() {
+ slf.setattr(name.cast_into::<PyString>()?, value)?;
+ }
+ }
+ Ok(values)
+}
/// A Variant value (the `value`/`metadata` binary components). Mirrors
/// `pyspark.sql.types.VariantVal`.
@@ -42,33 +109,31 @@ impl PyVariantVal {
self.value = value;
self.metadata = metadata;
}
- /// Pickled as a plain class instance is: its class is rebuilt without
`__init__`, and its
- /// value, metadata and instance attributes are restored by `__setstate__`.
+ /// Pickled as PySpark's plain class is, with its value and metadata as
attributes, so that
+ /// PySpark loads it, as PySpark's pickles of it load here.
fn __reduce__<'py>(slf: &Bound<'py, Self>) -> PyResult<Bound<'py,
PyTuple>> {
let py = slf.py();
- let this = slf.borrow();
- let newobj = py.import("copyreg")?.getattr("__newobj__")?;
- let args = PyTuple::new(py, [slf.get_type().into_any()])?;
- let state = PyTuple::new(
- py,
+ let fields = {
+ let this = slf.borrow();
[
- PyBytes::new(py, &this.value).into_any(),
- PyBytes::new(py, &this.metadata).into_any(),
- slf.getattr("__dict__")?,
- ],
- )?;
- PyTuple::new(py, [newobj, args.into_any(), state.into_any()])
- }
- fn __setstate__(slf: &Bound<'_, Self>, state: &Bound<'_, PyTuple>) ->
PyResult<()> {
- let (value, metadata, attributes): (Vec<u8>, Vec<u8>, Bound<'_,
PyAny>) =
- state.extract()?;
- {
- let mut this = slf.borrow_mut();
+ ("value", PyBytes::new(py, &this.value).into_any()),
+ ("metadata", PyBytes::new(py, &this.metadata).into_any()),
+ ]
+ };
+ reduce_as_a_plain_class(slf.as_any(), fields)
+ }
+ fn __setstate__(slf: &Bound<'_, Self>, state: &Bound<'_, PyAny>) ->
PyResult<()> {
+ let [value, metadata] =
+ restore_plain_class_state(slf.as_any(), state, ["value",
"metadata"])?;
+ let value: Option<Vec<u8>> = value.map(|v| v.extract()).transpose()?;
+ let metadata: Option<Vec<u8>> = metadata.map(|m|
m.extract()).transpose()?;
+ let mut this = slf.borrow_mut();
+ if let Some(value) = value {
this.value = value;
+ }
+ if let Some(metadata) = metadata {
this.metadata = metadata;
}
- slf.getattr("__dict__")?
- .call_method1("update", (attributes,))?;
Ok(())
}
#[getter]
@@ -121,16 +186,59 @@ impl PyVariantVal {
}
/// A Geography value (WKB bytes + SRID). Mirrors
`pyspark.sql.types.Geography`.
-#[pyclass(name = "Geography", module = "pyspark.sql.types", weakref, dict)]
+#[pyclass(
+ name = "Geography",
+ module = "pyspark.sql.types",
+ weakref,
+ dict,
+ subclass
+)]
pub struct PyGeography {
pub(crate) wkb: Vec<u8>,
pub(crate) srid: i32,
}
#[pymethods]
impl PyGeography {
+ /// Accepts any arguments, so that a subclass's `__init__` may take
others, as of PySpark's
+ /// plain class; `__init__` sets the WKB and the SRID.
#[new]
- fn new(wkb: Vec<u8>, srid: i32) -> Self {
- PyGeography { wkb, srid }
+ #[pyo3(signature = (*_args, **_kwargs))]
+ fn new(_args: &Bound<'_, PyTuple>, _kwargs: Option<&Bound<'_, PyDict>>) ->
Self {
+ PyGeography {
+ wkb: Vec::new(),
+ srid: 0,
+ }
+ }
+ #[pyo3(signature = (wkb, srid))]
+ fn __init__(&mut self, wkb: Vec<u8>, srid: i32) {
+ self.wkb = wkb;
+ self.srid = srid;
+ }
+ /// Pickled as PySpark's plain class is, with its WKB and SRID as
attributes, so that PySpark
+ /// loads it, as PySpark's pickles of it load here.
+ fn __reduce__<'py>(slf: &Bound<'py, Self>) -> PyResult<Bound<'py,
PyTuple>> {
+ let py = slf.py();
+ let fields = {
+ let this = slf.borrow();
+ [
+ ("wkb", PyBytes::new(py, &this.wkb).into_any()),
+ ("srid", this.srid.into_pyobject(py)?.into_any()),
+ ]
+ };
+ reduce_as_a_plain_class(slf.as_any(), fields)
+ }
+ fn __setstate__(slf: &Bound<'_, Self>, state: &Bound<'_, PyAny>) ->
PyResult<()> {
+ let [wkb, srid] = restore_plain_class_state(slf.as_any(), state,
["wkb", "srid"])?;
+ let wkb: Option<Vec<u8>> = wkb.map(|w| w.extract()).transpose()?;
+ let srid: Option<i32> = srid.map(|s| s.extract()).transpose()?;
+ let mut this = slf.borrow_mut();
+ if let Some(wkb) = wkb {
+ this.wkb = wkb;
+ }
+ if let Some(srid) = srid {
+ this.srid = srid;
+ }
+ Ok(())
}
fn getSrid(&self) -> i32 {
self.srid
@@ -165,16 +273,59 @@ impl PyGeography {
}
/// A Geometry value (WKB bytes + SRID). Mirrors `pyspark.sql.types.Geometry`.
-#[pyclass(name = "Geometry", module = "pyspark.sql.types", weakref, dict)]
+#[pyclass(
+ name = "Geometry",
+ module = "pyspark.sql.types",
+ weakref,
+ dict,
+ subclass
+)]
pub struct PyGeometry {
pub(crate) wkb: Vec<u8>,
pub(crate) srid: i32,
}
#[pymethods]
impl PyGeometry {
+ /// Accepts any arguments, so that a subclass's `__init__` may take
others, as of PySpark's
+ /// plain class; `__init__` sets the WKB and the SRID.
#[new]
- fn new(wkb: Vec<u8>, srid: i32) -> Self {
- PyGeometry { wkb, srid }
+ #[pyo3(signature = (*_args, **_kwargs))]
+ fn new(_args: &Bound<'_, PyTuple>, _kwargs: Option<&Bound<'_, PyDict>>) ->
Self {
+ PyGeometry {
+ wkb: Vec::new(),
+ srid: 0,
+ }
+ }
+ #[pyo3(signature = (wkb, srid))]
+ fn __init__(&mut self, wkb: Vec<u8>, srid: i32) {
+ self.wkb = wkb;
+ self.srid = srid;
+ }
+ /// Pickled as PySpark's plain class is, with its WKB and SRID as
attributes, so that PySpark
+ /// loads it, as PySpark's pickles of it load here.
+ fn __reduce__<'py>(slf: &Bound<'py, Self>) -> PyResult<Bound<'py,
PyTuple>> {
+ let py = slf.py();
+ let fields = {
+ let this = slf.borrow();
+ [
+ ("wkb", PyBytes::new(py, &this.wkb).into_any()),
+ ("srid", this.srid.into_pyobject(py)?.into_any()),
+ ]
+ };
+ reduce_as_a_plain_class(slf.as_any(), fields)
+ }
+ fn __setstate__(slf: &Bound<'_, Self>, state: &Bound<'_, PyAny>) ->
PyResult<()> {
+ let [wkb, srid] = restore_plain_class_state(slf.as_any(), state,
["wkb", "srid"])?;
+ let wkb: Option<Vec<u8>> = wkb.map(|w| w.extract()).transpose()?;
+ let srid: Option<i32> = srid.map(|s| s.extract()).transpose()?;
+ let mut this = slf.borrow_mut();
+ if let Some(wkb) = wkb {
+ this.wkb = wkb;
+ }
+ if let Some(srid) = srid {
+ this.srid = srid;
+ }
+ Ok(())
}
fn getSrid(&self) -> i32 {
self.srid
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 19a82237..369d269e 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -2603,6 +2603,24 @@ def
test_variant_val_subclass_round_trips_as_pyspark(session):
assert str(collected) == collected.toJson() == '{"a":1}'
+
+def
test_udfs_that_refer_to_variant_and_spatial_values_run_on_the_server_as_pyspark(session):
+ # As PySpark's: the VariantVal, Geometry and Geography that a UDF refers
to are pickled as
+ # PySpark's plain classes, which the server's Python workers, of PySpark,
unpickle.
+ from pyspark.sql import functions as F
+ from pyspark.sql.types import Geography, Geometry
+
+ wkb = bytes.fromhex("0101000000000000000000F03F0000000000000040")
+ variant = session.sql("""SELECT parse_json('{"a": 1}') AS v""").first()[0]
+ geometry, geography = Geometry.fromWKB(wkb, 4326), Geography(wkb, 3857)
+
+ @F.udf("string")
+ def described(_):
+ return "%s %d %d" % (variant.toJson(), geometry.getSrid(),
geography.getSrid())
+
+ assert session.range(1).select(described("id")).first()[0] == '{"a":1}
4326 3857'
+
+
def test_create_dataframe_of_multi_and_categorical_labels_as_pyspark(session):
# As PySpark's: a frame whose labels are a MultiIndex or a
CategoricalIndex converts its
# cells as a frame of default labels does. A naive datetime of a list
reads back unchanged
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index b93b26a8..7d3a86a4 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -6670,6 +6670,106 @@ def
test_variant_val_subclass_is_sent_as_its_variant(mock_connect):
spark.createDataFrame([(T.VariantVal(value, metadata),)], "v
variant")).to_pylist()
+
+class _SlottedVariant(T.VariantVal):
+ __slots__ = ("note",)
+
+
+class _TaggedGeometry(T.Geometry):
+ # Unpickling must not call this __init__, which needs the tag.
+ def __init__(self, wkb, srid, tag):
+ super().__init__(wkb, srid)
+ self.tag = tag
+
+
+class _TaggedGeography(T.Geography):
+ def __init__(self, wkb, srid, tag):
+ super().__init__(wkb, srid)
+ self.tag = tag
+
+
+def
test_variant_and_spatial_values_pickle_as_pysparks_plain_classes_which_load_them(
+ monkeypatch):
+ # As PySpark's VariantVal, Geometry and Geography, plain classes without
__setstate__: a
+ # value pickles as its class, rebuilt without __init__, with the dict of
its attributes as
+ # the state, which PySpark's classes take, as the server's Python workers
do for the values
+ # of a UDF. And PySpark's pickles of them load here.
+ import io
+ import pickle
+
+ class VariantVal: # PySpark's, as far as pickling goes.
+ def __init__(self, value, metadata):
+ self.value, self.metadata = value, metadata
+
+ class Geometry:
+ def __init__(self, wkb, srid):
+ self.wkb, self.srid = wkb, srid
+
+ class Geography(Geometry):
+ pass
+
+ pyspark_classes = {"VariantVal": VariantVal, "Geometry": Geometry,
"Geography": Geography}
+ for name, cls in pyspark_classes.items():
+ cls.__module__, cls.__qualname__ = "pyspark.sql.types", name
+
+ class PySparkUnpickler(pickle.Unpickler):
+ def find_class(self, module, name):
+ if module == "pyspark.sql.types" and name in pyspark_classes:
+ return pyspark_classes[name]
+ return super().find_class(module, name)
+
+ def pyspark_pickle(name, attributes, protocol):
+ # PySpark's pickle of its value of `attributes`, which refers to its
class by name.
+ value = pyspark_classes[name].__new__(pyspark_classes[name])
+ vars(value).update(attributes)
+ with monkeypatch.context() as patched:
+ patched.setattr(T, name, pyspark_classes[name])
+ return pickle.dumps(value, protocol)
+
+ wkb = bytes.fromhex("0101000000000000000000F03F0000000000000040")
+ for value, fields in [
+ (T.VariantVal(b"\x0c\x01", b"\x01\x00\x00"),
+ {"value": b"\x0c\x01", "metadata": b"\x01\x00\x00"}),
+ (T.Geometry(wkb, 4326), {"wkb": wkb, "srid": 4326}),
+ (T.Geography(wkb, 4326), {"wkb": wkb, "srid": 4326}),
+ ]:
+ value.tag = "kept"
+ name = type(value).__name__
+ for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1):
+ loaded = PySparkUnpickler(io.BytesIO(pickle.dumps(value,
protocol))).load()
+ assert type(loaded) is pyspark_classes[name]
+ assert vars(loaded) == {"tag": "kept", **fields}
+ restored = pickle.loads(pyspark_pickle(name, {"tag": "x",
**fields}, protocol))
+ assert type(restored) is type(value) and restored.tag == "x"
+ assert {field: getattr(restored, field) for field in fields} ==
fields
+
+
+def test_spatial_values_copy_pickle_and_are_subclassed_as_pyspark():
+ # As PySpark's Geometry and Geography, plain classes: they are copied and
pickled, also in a
+ # Row, and subclassed, of an __init__ that unpickling does not run. And as
of PySpark's
+ # VariantVal, the slots of a subclass are pickled.
+ import copy
+ import pickle
+
+ wkb = bytes.fromhex("0101000000000000000000F03F0000000000000040")
+ for cls, tagged in ((T.Geometry, _TaggedGeometry), (T.Geography,
_TaggedGeography)):
+ value = cls(wkb, 4326)
+ for restored in (copy.copy(value), copy.deepcopy(value),
pickle.loads(pickle.dumps(value))):
+ assert type(restored) is cls and restored == value
+ assert (restored.wkb, restored.getSrid()) == (wkb, 4326)
+ assert pickle.loads(pickle.dumps(T.Row(g=value))) == T.Row(g=value)
+ original = tagged(wkb, 3857, "x")
+ restored = pickle.loads(pickle.dumps(original))
+ assert (type(restored), restored.tag, restored.srid) == (tagged, "x",
3857)
+ assert restored == original and repr(restored) == repr(original)
+
+ slotted = _SlottedVariant(b"\x0c\x01", b"\x01\x00\x00")
+ slotted.note = "slot"
+ restored = pickle.loads(pickle.dumps(slotted))
+ assert (type(restored), restored.note) == (_SlottedVariant, "slot")
+ assert (restored.value, restored.metadata) == (b"\x0c\x01",
b"\x01\x00\x00")
+
+
def test_str_of_variant_values_is_their_json_and_they_are_no_rows_as_pyspark():
# As PySpark's VariantVal: str is its JSON, in UTC, as toJson(); repr is
of its bytes. And
# as PySpark's createDataFrame, whose VariantVal has a __dict__, so that
it is a row, which
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]