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 2b7632c1 [SPARK-61576][CONNECT][PYTHON][FOLLOWUP] Pickle an 
Observation at every protocol, as PySpark's plain class does
2b7632c1 is described below

commit 2b7632c12f348acdb4d26e8fc6abe8074db67267
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 10:38:05 2026 +0900

    [SPARK-61576][CONNECT][PYTHON][FOLLOWUP] Pickle an Observation at every 
protocol, as PySpark's plain class does
    
    ### What changes were proposed in this pull request?
    
    A follow-up of #578 (SPARK-61576), from a review of it. The Python client's 
`Observation` (`crates/pyspark-rs/src/observation.rs`) did not pickle at 
protocols 0 and 1. It had `__getstate__`, `__setstate__`, `__copy__` and 
`__deepcopy__`, but no `__reduce__`. Below protocol 2, the default reduce of a 
class with a native base fails, so `pickle.dumps(Observation("x"), protocol=0)` 
raised `TypeError: cannot pickle 'Observation' object`.
    
    It now has a `__reduce__` that returns `(copyreg.__newobj__, (type(self),), 
self.__getstate__())`. That is the tuple that `object.__reduce_ex__` gives at 
protocols 2 and up, so the pickles at those protocols do not change, and it 
pickles at 0 and 1 too.
    - The class reference stays `pyspark.sql.connect.observation.Observation`, 
so a worker running plain PySpark unpickles its own class.
    - `copy.copy` and `copy.deepcopy` still go through `__copy__` and 
`__deepcopy__`.
    
    ### Why are the changes needed?
    
    To match PySpark 4.3.0, whose `Observation` is a plain class that pickles 
at every protocol.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, on unreleased changes: an `Observation` pickles at protocols 0 and 1.
    
    ### How was this patch tested?
    
    - `test_an_observation_pickles_at_every_protocol_as_pyspark` in 
`python/tests/test_dropin_offline.py`, new. It round-trips an Observation at 
protocols 0 to 5, before the observed DataFrame runs (it then observes the 
unpickled copy) and after it (`get` is `{"c": 3}`). It pickles an unpickled one 
again at each protocol, and checks REUSE_OBSERVATION on the unpickled copy. It 
fails at protocol 0 without the change and passes with it. The existing pickle 
tests pass: cloudpickle and a worke [...]
    - The state matches official PySpark 4.3.0: `{_error: None, _name: 'o', 
_result: None}` for an unused one.
    - The offline drop-in and ML suites (1957 and 128 passed), the observation 
and pickle tests of `test_dropin_e2e.py` against a Spark 4.3.0 server, `ruff 
check`, and `scripts/audit_no_stubs.sh`.
    
    ### 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 #596 from HyukjinKwon/scr0b-followup-O2.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/observation.rs | 15 ++++++++++++++-
 python/tests/test_dropin_offline.py  | 32 ++++++++++++++++++++++++++++++++
 2 files changed, 46 insertions(+), 1 deletion(-)

diff --git a/crates/pyspark-rs/src/observation.rs 
b/crates/pyspark-rs/src/observation.rs
index b391077e..fea49390 100644
--- a/crates/pyspark-rs/src/observation.rs
+++ b/crates/pyspark-rs/src/observation.rs
@@ -1,7 +1,7 @@
 //! PyO3 wrapper for `spark_connect::observation::Observation` 
(`pyspark.sql.Observation`).
 
 use pyo3::prelude::*;
-use pyo3::types::{PyDict, PyString};
+use pyo3::types::{PyDict, PyString, PyTuple};
 use spark_connect::dataframe::DataFrame;
 use spark_connect::expression::Expression;
 use spark_connect::observation::Observation;
@@ -179,6 +179,19 @@ impl PyObservation {
         Ok(copy)
     }
 
+    /// The reduce of pickle, which an Observation has at every protocol: as
+    /// `object.__reduce_ex__` gives it at the protocols 2 and up, of its 
class, which pickle
+    /// makes by `copyreg.__newobj__`, and of the state of `__getstate__`. 
Below protocol 2, the
+    /// default reduce of a class with a native base fails, as copyreg's does, 
so an Observation
+    /// would not pickle at all there.
+    fn __reduce__<'py>(slf: &Bound<'py, Self>) -> PyResult<Bound<'py, 
PyTuple>> {
+        let py = slf.py();
+        let newobj = py.import("copyreg")?.getattr("__newobj__")?;
+        let args = PyTuple::new(py, [slf.get_type()])?;
+        let state = Self::__getstate__(slf)?;
+        PyTuple::new(py, [newobj, args.into_any(), state.into_any()])
+    }
+
     /// The state that a pickled Observation keeps, that of PySpark's, its 
`__dict__`: `_name`,
     /// `_result`, a dict of the metrics or None before it is used, `_error`, 
the exception that
     /// `get` raises or None, and the attributes of this one. So on a Python 
worker of the server,
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 78ffe886..a1f0a533 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -10551,6 +10551,38 @@ def 
test_an_observation_pickles_as_the_plain_object_of_pyspark(mock_connect):
     assert type(on_worker(failed)["_error"]) is type(raised.value)
 
 
+def test_an_observation_pickles_at_every_protocol_as_pyspark(mock_connect):
+    # As pickle of PySpark's Observation, a plain object, at each protocol: 
the protocols 0 and 1
+    # pickle it too, as the protocols 2 and up do, before and after the 
observed DataFrame ran,
+    # and an unpickled one pickles again with the metrics that it keeps.
+    from pyspark.errors import PySparkAssertionError
+    from pyspark.sql import Observation
+    from pyspark.sql import functions as F
+
+    spark, service = mock_connect
+    protocols = range(pickle.HIGHEST_PROTOCOL + 1)
+    observation = Observation("o")
+    for protocol in protocols:
+        unused = pickle.loads(pickle.dumps(observation, protocol=protocol))
+        assert type(unused) is Observation and unused._name == "o"
+        again = pickle.loads(pickle.dumps(unused, protocol=protocol))
+        assert type(again) is Observation and again._name == "o"
+        spark.range(1).observe(again, F.count(F.lit(1)).alias("c"))
+
+    df = spark.range(3).observe(observation, F.count(F.lit(1)).alias("c"))
+    batch, observed = _count_batch_and_observed_metrics(service, df)
+    service.execute_payload = batch + observed("o", varint_field(7, 3), "c")
+    assert df.count() == 3
+    for protocol in protocols:
+        restored = pickle.loads(pickle.dumps(observation, protocol=protocol))
+        assert type(restored) is Observation and restored._name == "o"
+        assert restored.get == {"c": 3}
+        twice = pickle.loads(pickle.dumps(restored, protocol=protocol))
+        assert twice._name == "o" and twice.get == {"c": 3}
+        with pytest.raises(PySparkAssertionError, match="REUSE_OBSERVATION"):
+            spark.range(1).observe(twice, F.count(F.lit(1)).alias("c"))
+
+
 def 
test_a_failing_action_keeps_the_metrics_of_the_earlier_actions_as_pyspark(mock_connect):
     # As PySpark's client, which converts the metrics of an Observation before 
it updates the
     # Observation with them: the Observation of a metric that it does not 
convert, and those


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

Reply via email to