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 447dfab1 [SPARK-61291][CONNECT][PYTHON] Let VariantVal be subclassed 
in the Python client, as PySpark's can
447dfab1 is described below

commit 447dfab11c4e50a7e9f34ddc32609f8b10c829d1
Author: Timothy Meehan <[email protected]>
AuthorDate: Wed Nov 11 06:19:10 2026 +0900

    [SPARK-61291][CONNECT][PYTHON] Let VariantVal be subclassed in the Python 
client, as PySpark's can
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61291](https://issues.apache.org/jira/browse/SPARK-61291): let 
`VariantVal` be subclassed in the Python client, as PySpark's can.
    
    - `crates/pyspark-rs/src/values.rs`: the `VariantVal` pyclass gets 
`subclass`, so `class TaggedVariant(VariantVal): pass` no longer raises 
`TypeError`.
    - The constructor is split as PySpark's is: `__new__` accepts any arguments 
and `__init__(value, metadata)` sets the bytes. A subclass's `__init__` may 
take other arguments, and `super().__init__(value, metadata)` works.
    - `__reduce__` pickles as a plain class instance does: the class is rebuilt 
through `copyreg.__newobj__` without calling `__init__`, and `__setstate__` 
restores the value, metadata and instance attributes.
    
    Subclass instances behave as the base class does everywhere the Rust code 
and the Python shims check for a `VariantVal`: `createDataFrame` sends them as 
variants, `_infer_type` types them as `VariantType`, and a row of one is 
rejected with the existing "Rows cannot be of type VariantVal" error. 
`collect()` still returns the base `VariantVal`, as PySpark's does.
    
    ### Why are the changes needed?
    
    PySpark's `VariantVal` is a plain class, so a subclass of it is a variant, 
and code that tags values this way fails on the Python client at the class 
statement. The reference is PySpark 4.3.0 against the same server: the issue's 
repro prints `{"a":1}` on it and raised `TypeError` here before this change.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. A subclass of `VariantVal` can be defined and passed to 
`createDataFrame`, where it previously raised `TypeError` at the class 
statement. `VariantVal` pickles with a different payload: it is rebuilt through 
`copyreg.__newobj__` with a state, instead of by calling `VariantVal(value, 
metadata)`. Pickles of the previous form still load, because pickle calls the 
class with those arguments, which runs `__init__`. Checked: a `VariantVal` 
pickled by the build before this change loads wi [...]
    
    ### How was this patch tested?
    
    - Repro from the issue, before the change: `TypeError: type 
'pyspark.sql.types.VariantVal' is not an acceptable base type`. After the 
change: `{"a":1}`, as `pyspark-client` 4.3.0 prints it on the same server.
    - `python/tests/test_dropin_offline.py`:
      - `test_variant_val_subclass_as_pyspark`: a subclass is repr'd, str'd and 
typed as the class, compares by identity, pickles with its attributes without 
running its `__init__`, infers as a variant, and a row of it is rejected. It 
fails without the change, since the module's subclass cannot be defined.
      - `test_variant_val_subclass_is_sent_as_its_variant` (mock server): the 
local relation of a subclass equals that of the `VariantVal` it subclasses.
    - `python/tests/test_dropin_e2e.py`: 
`test_variant_val_subclass_round_trips_as_pyspark` runs on a live server: 
`createDataFrame` of a subclass, collected as a `VariantVal` that prints 
`{"a":1}`.
    - Offline suites: `tests/test_dropin_offline.py tests/test_ml_offline.py 
tests/test_arrow_handoff.py`: 2929 passed, 8 skipped.
    - Live suites: `tests/test_arrow_e2e.py tests/test_dropin_e2e.py 
tests/test_ml_e2e.py` against the Spark 4.3.0 Connect server: 237 passed, 1 
skipped, 0 failed.
    - `cargo test -p apache-spark-connect --release --lib`: 528 passed.
    - `cargo test -p apache-spark-connect --release --no-run`, and with 
`--features wasm-udf`: both build.
    - `cargo fmt --all --check`: clean.
    - `cargo clippy --workspace --all-targets --release`: no diagnostic in 
`values.rs`; the other diagnostics in `pyspark-rs` and `spark-connect` are in 
files this change does not touch.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5 and Claude Haiku 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #471 from tdcmeehan/SPARK-61291-subclassable-variantval.
    
    Authored-by: Timothy Meehan <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/values.rs     | 60 +++++++++++++++++++++++++++----------
 python/tests/test_dropin_e2e.py     | 16 ++++++++++
 python/tests/test_dropin_offline.py | 60 +++++++++++++++++++++++++++++++++++++
 3 files changed, 121 insertions(+), 15 deletions(-)

diff --git a/crates/pyspark-rs/src/values.rs b/crates/pyspark-rs/src/values.rs
index 1af1a40d..253cf820 100644
--- a/crates/pyspark-rs/src/values.rs
+++ b/crates/pyspark-rs/src/values.rs
@@ -2,11 +2,17 @@
 //! mirroring `pyspark.sql.types.{VariantVal, Geometry, Geography}`.
 
 use pyo3::prelude::*;
-use pyo3::types::PyBytes;
+use pyo3::types::{PyBytes, PyDict, PyTuple};
 
 /// A Variant value (the `value`/`metadata` binary components). Mirrors
 /// `pyspark.sql.types.VariantVal`.
-#[pyclass(name = "VariantVal", module = "pyspark.sql.types", weakref, dict)]
+#[pyclass(
+    name = "VariantVal",
+    module = "pyspark.sql.types",
+    weakref,
+    dict,
+    subclass
+)]
 pub struct PyVariantVal {
     pub(crate) value: Vec<u8>,
     pub(crate) metadata: Vec<u8>,
@@ -21,25 +27,49 @@ impl PyVariantVal {
 
 #[pymethods]
 impl PyVariantVal {
+    /// Accepts any arguments, so that a subclass's `__init__` may take 
others; `__init__` sets
+    /// the value and metadata.
     #[new]
-    fn new(value: Vec<u8>, metadata: Vec<u8>) -> Self {
-        PyVariantVal { value, metadata }
-    }
-    /// Pickled as `VariantVal(value, metadata)`, which PySpark's own class 
also takes.
-    fn __reduce__<'py>(slf: &Bound<'py, Self>) -> PyResult<Bound<'py, 
pyo3::types::PyTuple>> {
+    #[pyo3(signature = (*_args, **_kwargs))]
+    fn new(_args: &Bound<'_, PyTuple>, _kwargs: Option<&Bound<'_, PyDict>>) -> 
Self {
+        PyVariantVal {
+            value: Vec::new(),
+            metadata: Vec::new(),
+        }
+    }
+    #[pyo3(signature = (value, metadata))]
+    fn __init__(&mut self, value: Vec<u8>, metadata: Vec<u8>) {
+        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__`.
+    fn __reduce__<'py>(slf: &Bound<'py, Self>) -> PyResult<Bound<'py, 
PyTuple>> {
         let py = slf.py();
         let this = slf.borrow();
-        let args = (
-            PyBytes::new(py, &this.value),
-            PyBytes::new(py, &this.metadata),
-        );
-        pyo3::types::PyTuple::new(
+        let newobj = py.import("copyreg")?.getattr("__newobj__")?;
+        let args = PyTuple::new(py, [slf.get_type().into_any()])?;
+        let state = PyTuple::new(
             py,
             [
-                slf.get_type().into_any(),
-                args.into_pyobject(py)?.into_any(),
+                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();
+            this.value = value;
+            this.metadata = metadata;
+        }
+        slf.getattr("__dict__")?
+            .call_method1("update", (attributes,))?;
+        Ok(())
     }
     #[getter]
     fn value<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 67669ce0..5e4e755a 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -2587,6 +2587,22 @@ def 
test_variant_spatial_and_user_defined_values_round_trip_as_pyspark(session):
     assert geometry == Geometry.fromWKB(wkb, 0)
 
 
+def test_variant_val_subclass_round_trips_as_pyspark(session):
+    # As PySpark's: a subclass of VariantVal is createDataFrame's variant, and 
collects as a
+    # VariantVal.
+    from pyspark.sql.types import VariantVal
+
+    variant = session.sql("""SELECT parse_json('{"a": 1}') AS v""").first()[0]
+
+    class TaggedVariant(VariantVal):
+        pass
+
+    tagged = TaggedVariant(variant.value, variant.metadata)
+    collected = session.createDataFrame([(tagged,)], "v variant").first()[0]
+    assert type(collected) is VariantVal
+    assert str(collected) == collected.toJson() == '{"a":1}'
+
+
 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 0d23d653..6fc44878 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -6394,6 +6394,66 @@ def test_variant_val_pickles_as_pyspark():
     assert (value.value, value.metadata) == (b"\x0c\x01", b"\x01\x00\x00")
 
 
+class _TaggedVariant(T.VariantVal):
+    # Unpickling must not call this __init__, which needs the tag.
+    def __init__(self, value, metadata, tag):
+        super().__init__(value, metadata)
+        self.tag = tag
+
+
+def test_variant_val_subclass_as_pyspark():
+    # As PySpark's VariantVal, which a subclass of it is: it is repr'd, str'd 
and typed as the
+    # class does, compares by identity, and pickles as its class with its 
attributes, without
+    # running its __init__.
+    import pickle
+
+    from pyspark.errors import PySparkValueError
+
+    class TaggedVariant(T.VariantVal):
+        pass
+
+    v = T.VariantVal.parseJson('{"a": 1}')
+    tagged = TaggedVariant(v.value, v.metadata)
+    assert repr(tagged) == repr(v) and str(tagged) == str(v) == '{"a":1}'
+    assert tagged.toJson() == v.toJson() and tagged.toPython() == {"a": 1}
+    assert tagged != TaggedVariant(v.value, v.metadata)
+
+    original = _TaggedVariant(v.value, v.metadata, "x")
+    original.extra = "kept"
+    restored = pickle.loads(pickle.dumps(original))
+    assert (type(restored), restored.tag, restored.extra) == (_TaggedVariant, 
"x", "kept")
+    assert (restored.value, restored.metadata) == (v.value, v.metadata)
+
+    assert T._infer_type(tagged) == T.VariantType()
+    struct = T.StructType([T.StructField("v", T.VariantType())])
+    with pytest.raises(PySparkValueError, match="Rows cannot be of type 
VariantVal"):
+        _offline_session().createDataFrame([tagged], struct)
+
+
+def test_variant_val_subclass_is_sent_as_its_variant(mock_connect):
+    # As PySpark's LocalDataToArrowConversion: a subclass of VariantVal is 
sent as the struct of
+    # its value and metadata, as the VariantVal of which it is a subclass is.
+    import pyarrow as pa
+
+    spark, service = mock_connect
+
+    def local_table(df):
+        df.toArrow()
+        request = parse_message(service.execute_requests[-1])
+        relation = parse_message(parse_message(request[3][0])[1][0])
+        while 18 in relation:  # Relation.to_df -> ToDF.input.
+            relation = parse_message(parse_message(relation[18][0])[1][0])
+        # Relation.local_relation=11 -> LocalRelation.data=1.
+        local = parse_message(relation[11][0])
+        return pa.ipc.open_stream(local[1][0]).read_all()
+
+    value, metadata = b"\x0c\x01", b"\x01\x00\x00"
+    tagged = _TaggedVariant(value, metadata, "x")
+    sent = local_table(spark.createDataFrame([(tagged,)], "v variant"))
+    assert sent.to_pylist() == local_table(
+        spark.createDataFrame([(T.VariantVal(value, metadata),)], "v 
variant")).to_pylist()
+
+
 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]

Reply via email to