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 ca930136 [SPARK-61576][CONNECT][PYTHON] Let copy.copy, copy.deepcopy 
and pickle copy an Observation in the Python client, as PySpark does
ca930136 is described below

commit ca9301362e7bfbc693623e6db06aad9bd2e21fe7
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 08:50:13 2026 +0900

    [SPARK-61576][CONNECT][PYTHON] Let copy.copy, copy.deepcopy and pickle copy 
an Observation in the Python client, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    This PR lets `copy.copy`, `copy.deepcopy` and `pickle` work on an 
`Observation` of the Python client, as they do on PySpark's, which is a plain 
Python class under Spark Connect 
(`pyspark.sql.connect.observation.Observation`).
    
    - `copy.copy` returns an Observation with the same name and state. A copy 
of a used Observation shares its metrics, the way PySpark's shallow copy shares 
the `_result` dict, so it also sees metrics that later actions set. An error 
reported later is set on the original only. A copy of an unused Observation can 
be used on its own.
    - `copy.deepcopy` returns a detached copy of the name and state as they are 
now.
    - Both copy the instance attributes the way a plain object's are copied; 
`deepcopy` goes through its memo.
    - Pickling uses PySpark's state, its `__dict__`: `_name`, `_result`, 
`_error` and the attributes. The class's module is now 
`pyspark.sql.connect.observation`, the module of PySpark's Connect Observation. 
`pyspark.sql.observation` imports that module, so that cloudpickle pickles the 
class by reference: it only does that for a module already in `sys.modules`.
      - A server-side Python worker, whose PySpark has no Rust client, 
unpickles PySpark's own Observation.
      - The client unpickles its own: `__setstate__` restores the name and 
keeps `_result` and `_error`, which `get` returns as PySpark's does. An 
unpickled used Observation is used, so it raises `REUSE_OBSERVATION`.
    - The core's `Observation` keeps its metrics in a list that a shallow copy 
shares. It gains hidden (`#[doc(hidden)]`) `shallow_copy()`, `detached()` and 
`state()` for the drop-in.
    
    ### Why are the changes needed?
    
    For parity with PySpark 4.3.0. All three operations raised in the client:
    
    ```python
    import copy, pickle
    from pyspark.sql import Observation, functions as F
    
    o = Observation("o")
    df = spark.range(3).observe(o, F.count(F.lit(1)).alias("n"))
    s, d = copy.copy(o), copy.deepcopy(o)
    df.collect()
    print(o.get, s.get, d.get, pickle.loads(pickle.dumps(o)).get)
    ```
    
    - PySpark 4.3.0: `{'n': 3} {'n': 3} {} {'n': 3}`
    - Before: `TypeError: cannot pickle 'pyspark.sql.observation.Observation' 
object` from `copy.copy`, and the same from `copy.deepcopy` and `pickle.dumps`
    - After: `{'n': 3} {'n': 3} {} {'n': 3}`
    
    A UDF or `foreachBatch` function that refers to an Observation also failed, 
because cloudpickle could not pickle it.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. `copy.copy`, `copy.deepcopy`, `pickle` and cloudpickle now work on an 
Observation, as in PySpark. `type(Observation()).__module__` is now 
`pyspark.sql.connect.observation`, as it is for PySpark's under Spark Connect. 
Both are unreleased behavior of this client.
    
    ### How was this patch tested?
    
    New tests, each checked to fail without the fix:
    
    - Rust: 
`a_shallow_copy_shares_the_metrics_of_a_used_observation_but_not_a_later_error`.
    - Offline, against the mock server:
      - `test_an_observation_copies_as_the_plain_object_of_pyspark`: copies of 
unused and used Observations, reuse, shared and snapshotted metrics, 
attributes, the memo.
      - `test_an_observation_pickles_as_the_plain_object_of_pyspark`: pickle 
and cloudpickle of unused, used and failed Observations; the worker-side state, 
read with a plain stand-in class; the module in `sys.modules` in a new process.
    - e2e: 
`test_an_observation_copies_and_pickles_as_the_plain_object_of_pyspark`, where 
the server's Python worker unpickles an Observation captured by a UDF.
    
    The same probe script against PySpark 4.3.0 and the client gives the same 
output for every case except `get`'s identity: `o.get is o.get` is true in 
PySpark and false here. That part is unchanged by this PR.
    
    Also ran, with `TZ=UTC` under protobuf's default (upb) backend: CI's 
offline set (`test_dropin_offline.py`, `test_arrow_handoff.py`, 
`test_ml_offline.py`), 3263 passed; `test_dropin_e2e.py` against Spark 4.3.0, 
274 passed and 1 skipped; the Rust lib tests; the `--no-run` builds with and 
without `wasm-udf`; `cargo fmt`; `scripts/audit_no_stubs.sh`; and ruff 0.14.0 
`check` and `format --check`.
    
    ### 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 #578 from HyukjinKwon/SPARK-61576-observation-copy.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/observation.rs    | 216 ++++++++++++++++++++++++++++++--
 crates/spark-connect/src/observation.rs | 112 +++++++++++++++--
 python/pyspark/sql/observation.py       |   6 +
 python/tests/test_dropin_e2e.py         |  22 ++++
 python/tests/test_dropin_offline.py     | 143 +++++++++++++++++++++
 5 files changed, 482 insertions(+), 17 deletions(-)

diff --git a/crates/pyspark-rs/src/observation.rs 
b/crates/pyspark-rs/src/observation.rs
index c1cb5c12..b391077e 100644
--- a/crates/pyspark-rs/src/observation.rs
+++ b/crates/pyspark-rs/src/observation.rs
@@ -15,12 +15,35 @@ use crate::errors::ResultExt;
 /// Python wrapper for an Observation of metrics, as PySpark Connect's 
`Observation`.
 #[pyclass(
     name = "Observation",
-    module = "pyspark.sql.observation",
+    module = "pyspark.sql.connect.observation",
     weakref,
     dict
 )]
 pub struct PyObservation {
     pub(crate) inner: Observation,
+    /// The `_result` and `_error` of an Observation unpickled from the state 
of PySpark's (see
+    /// `__setstate__`), which no action sets, and which `get` gives back as 
PySpark's does.
+    restored: Restored,
+}
+
+/// The `_result` and `_error` of the state of a pickled Observation, which 
its Rust state does
+/// not hold: none for an Observation that was not unpickled.
+#[derive(Default)]
+struct Restored {
+    /// The metrics of an Observation unpickled from a used one, a dict as 
PySpark's.
+    result: Option<Py<PyAny>>,
+    /// The exception that `get` raises.
+    error: Option<Py<PyAny>>,
+}
+
+impl Restored {
+    /// The same objects, as a shallow copy of PySpark's Observation keeps 
them.
+    fn clone_ref(&self, py: Python<'_>) -> Restored {
+        Restored {
+            result: self.result.as_ref().map(|result| result.clone_ref(py)),
+            error: self.error.as_ref().map(|error| error.clone_ref(py)),
+        }
+    }
 }
 
 #[pymethods]
@@ -58,7 +81,10 @@ impl PyObservation {
                 Observation::new(&name)
             }
         };
-        Ok(PyObservation { inner })
+        Ok(PyObservation {
+            inner,
+            restored: Restored::default(),
+        })
     }
 
     /// The name of the observation, as PySpark's `_name`: None for an unnamed 
observation
@@ -72,14 +98,17 @@ impl PyObservation {
     /// actions run so far observed, by their names, and empty before an 
action runs. The metrics
     /// of an execution that PySpark's client does not convert (see 
[`check_observed_metrics`])
     /// are never set, so these are those of the executions before it, as 
PySpark's.
+    /// An unpickled Observation gives back its `_error` and its `_result`, as 
PySpark's.
     #[getter]
-    fn get<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
-        let metrics = self.inner.get().to_pyerr()?;
-        let result = PyDict::new(py);
-        for (name, value) in metrics {
-            result.set_item(name, crate::dataframe::literal_to_py(py, &value, 
None)?)?;
+    fn get<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
+        if let Some(error) = &self.restored.error {
+            return Err(PyErr::from_value(error.bind(py).clone()));
+        }
+        if let Some(result) = &self.restored.result {
+            return Ok(result.bind(py).clone());
         }
-        Ok(result)
+        let metrics = self.inner.get().to_pyerr()?;
+        Ok(metrics_dict(py, metrics)?.into_any())
     }
 
     /// Observe the metrics of the Columns `exprs` on `df` with this 
observation, as PySpark's
@@ -96,6 +125,168 @@ impl PyObservation {
             .collect();
         observe(slf.py(), &df.dataframe, slf, exprs)
     }
+
+    /// `copy.copy`, as of PySpark's Observation, a plain object: an 
Observation of the name, the
+    /// state and the attributes of this one, which shares the metrics of a 
used one, as the copy
+    /// of PySpark's shares its result dict (see `Observation::shallow_copy`).
+    fn __copy__<'py>(slf: &Bound<'py, Self>) -> PyResult<Bound<'py, 
PyObservation>> {
+        let py = slf.py();
+        let this = slf.borrow();
+        let copy = PyObservation {
+            inner: this.inner.shallow_copy(),
+            restored: this.restored.clone_ref(py),
+        };
+        let copy = Bound::new(py, copy)?;
+        copy_attributes(slf, &copy, None)?;
+        Ok(copy)
+    }
+
+    /// `copy.deepcopy`, as of PySpark's Observation: an Observation of the 
name and the state
+    /// of this one as they are now, which the actions of this one do not set, 
with deep copies
+    /// of its attributes.
+    fn __deepcopy__<'py>(
+        slf: &Bound<'py, Self>,
+        memo: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, PyObservation>> {
+        let py = slf.py();
+        let inner = slf.borrow().inner.detached();
+        let copy = Bound::new(
+            py,
+            PyObservation {
+                inner,
+                restored: Restored::default(),
+            },
+        )?;
+        // As copy.deepcopy of a plain object, which records the copy in 
`memo` before it copies
+        // the attributes, so that an attribute that refers to this 
observation refers to the copy.
+        memo.set_item(slf.as_ptr() as usize, &copy)?;
+        let deepcopy = py.import("copy")?.getattr("deepcopy")?;
+        let copied = |object: &Option<Py<PyAny>>| -> 
PyResult<Option<Py<PyAny>>> {
+            object
+                .as_ref()
+                .map(|object| Ok(deepcopy.call1((object, memo))?.unbind()))
+                .transpose()
+        };
+        let restored = {
+            let this = slf.borrow();
+            Restored {
+                result: copied(&this.restored.result)?,
+                error: copied(&this.restored.error)?,
+            }
+        };
+        copy.borrow_mut().restored = restored;
+        copy_attributes(slf, &copy, Some(memo))?;
+        Ok(copy)
+    }
+
+    /// 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,
+    /// whose PySpark has no Rust client, it unpickles as PySpark's 
Observation, and here as this
+    /// one (see `__setstate__`).
+    fn __getstate__<'py>(slf: &Bound<'py, Self>) -> PyResult<Bound<'py, 
PyDict>> {
+        let py = slf.py();
+        let this = slf.borrow();
+        let (metrics, error) = this.inner.state();
+        let result = match &this.restored.result {
+            Some(result) => Some(result.bind(py).clone()),
+            None => metrics
+                .map(|metrics| metrics_dict(py, metrics).map(Bound::into_any))
+                .transpose()?,
+        };
+        let error = match &this.restored.error {
+            Some(error) => Some(error.bind(py).clone()),
+            None => error.map(|error| {
+                crate::errors::spark_error_to_py_exception(error)
+                    .value(py)
+                    .clone()
+                    .into_any()
+            }),
+        };
+        let state = PyDict::new(py);
+        state.set_item("_name", this.inner.name())?;
+        state.set_item("_result", result)?;
+        state.set_item("_error", error)?;
+        state.call_method1("update", (slf.getattr(pyo3::intern!(py, 
"__dict__"))?,))?;
+        Ok(state)
+    }
+
+    /// The Observation of the state of `__getstate__`, as pickle sets the 
`__dict__` of
+    /// PySpark's: of the name `_name`, whose `get` gives back `_error` and 
`_result`, which no
+    /// action sets, and so used if `_result` is not None, and of the other 
attributes.
+    fn __setstate__<'py>(slf: &Bound<'py, Self>, state: &Bound<'py, PyDict>) 
-> PyResult<()> {
+        let py = slf.py();
+        let state = state.copy()?;
+        let take = |key: &str| -> PyResult<Option<Bound<'py, PyAny>>> {
+            let value = state.get_item(key)?;
+            if value.is_some() {
+                state.del_item(key)?;
+            }
+            Ok(value.filter(|value| !value.is_none()))
+        };
+        let name: Option<String> = take("_name")?.map(|name| 
name.extract()).transpose()?;
+        let result = take("_result")?.map(Bound::unbind);
+        let error = take("_error")?.map(Bound::unbind);
+        {
+            let mut this = slf.borrow_mut();
+            this.inner = match name {
+                Some(name) => Observation::new(&name),
+                None => Observation::unnamed(),
+            };
+            this.restored = Restored { result, error };
+        }
+        slf.getattr(pyo3::intern!(py, "__dict__"))?
+            .call_method1(pyo3::intern!(py, "update"), (state,))?;
+        Ok(())
+    }
+
+    /// The `_result` and `_error` of an unpickled Observation, Python 
objects, which Python's
+    /// garbage collector sees, as those of PySpark's: so a reference cycle 
through them is freed.
+    fn __traverse__(&self, visit: pyo3::PyVisit<'_>) -> Result<(), 
pyo3::PyTraverseError> {
+        if let Some(result) = &self.restored.result {
+            visit.call(result)?;
+        }
+        if let Some(error) = &self.restored.error {
+            visit.call(error)?;
+        }
+        Ok(())
+    }
+
+    /// Break a reference cycle that the garbage collector found unreachable.
+    fn __clear__(&mut self) {
+        self.restored = Restored::default();
+    }
+}
+
+/// A dict of `metrics` by their names, as PySpark's `_result` of an 
Observation.
+fn metrics_dict(
+    py: Python<'_>,
+    metrics: Vec<(String, spark_connect_proto::expression::Literal)>,
+) -> PyResult<Bound<'_, PyDict>> {
+    let result = PyDict::new(py);
+    for (name, value) in metrics {
+        result.set_item(name, crate::dataframe::literal_to_py(py, &value, 
None)?)?;
+    }
+    Ok(result)
+}
+
+/// Set the attributes of `observation` on `copy`, as `copy` sets the 
`__dict__` of the copy of a
+/// plain object: the same values, or, of a deep copy, their deep copies of 
`memo`.
+fn copy_attributes(
+    observation: &Bound<'_, PyObservation>,
+    copy: &Bound<'_, PyObservation>,
+    memo: Option<&Bound<'_, PyAny>>,
+) -> PyResult<()> {
+    let py = observation.py();
+    let mut attributes = observation.getattr(pyo3::intern!(py, "__dict__"))?;
+    if let Some(memo) = memo {
+        attributes = py
+            .import("copy")?
+            .call_method1("deepcopy", (attributes, memo))?;
+    }
+    copy.getattr(pyo3::intern!(py, "__dict__"))?
+        .call_method1(pyo3::intern!(py, "update"), (attributes,))?;
+    Ok(())
 }
 
 /// `df` observing the metrics `exprs` with `observation`, as PySpark's 
`Observation._on`, which
@@ -107,6 +298,15 @@ pub(crate) fn observe(
     observation: &Bound<'_, PyObservation>,
     exprs: Vec<Expression>,
 ) -> PyResult<PyDataFrame> {
+    // An Observation unpickled from a used one is used, as PySpark's of a 
`_result`.
+    if observation.borrow().restored.result.is_some() {
+        return Err(raise_pyspark(
+            py,
+            "PySparkAssertionError",
+            "REUSE_OBSERVATION",
+            &[],
+        ));
+    }
     let inner = observation.borrow().inner.clone();
     let observed = crate::interrupt::interruptible(py, &df.spark_session(), || 
{
         df.observe_with(&inner, exprs)
diff --git a/crates/spark-connect/src/observation.rs 
b/crates/spark-connect/src/observation.rs
index e5ab57d1..3b15faa7 100644
--- a/crates/spark-connect/src/observation.rs
+++ b/crates/spark-connect/src/observation.rs
@@ -18,11 +18,15 @@ pub struct Observation {
     state: Arc<Mutex<ObservationState>>,
 }
 
+/// The metrics of an observation, by their names, in order.
+type Metrics = Vec<(String, proto::expression::Literal)>;
+
 #[derive(Default)]
 struct ObservationState {
     name: Option<String>,
-    /// None before the observation is used; then the metrics observed so far, 
in order.
-    result: Option<Vec<(String, proto::expression::Literal)>>,
+    /// None before the observation is used; then the metrics observed so far, 
which a shallow
+    /// copy of the observation shares, as a copy of PySpark's shares its 
result dict.
+    result: Option<Arc<Mutex<Metrics>>>,
     /// The error of collecting the metrics, which the server reported.
     error: Option<SparkError>,
 }
@@ -66,9 +70,32 @@ impl Observation {
         if let Some(error) = &state.error {
             return Err(error.clone());
         }
-        state.result.clone().ok_or_else(|| {
-            SparkError::classed(SparkErrorKind::AssertionError, 
"NO_OBSERVE_BEFORE_GET", &[])
-        })
+        match &state.result {
+            Some(result) => Ok(lock_metrics(result).clone()),
+            None => Err(SparkError::classed(
+                SparkErrorKind::AssertionError,
+                "NO_OBSERVE_BEFORE_GET",
+                &[],
+            )),
+        }
+    }
+
+    /// The metrics observed so far, None before the observation is used, and 
the error of
+    /// collecting them, if the server reported one: the `_result` and 
`_error` of PySpark's
+    /// Observation, which a pickled one keeps. Not a stable API.
+    #[doc(hidden)]
+    pub fn state(
+        &self,
+    ) -> (
+        Option<Vec<(String, proto::expression::Literal)>>,
+        Option<SparkError>,
+    ) {
+        let state = self.lock();
+        let result = state
+            .result
+            .as_ref()
+            .map(|result| lock_metrics(result).clone());
+        (result, state.error.clone())
     }
 
     /// Whether `self` and `other` are the same observation, of which one is a 
clone.
@@ -78,7 +105,29 @@ impl Observation {
 
     /// A copy of this observation, of its name and of its state as it is now, 
which the actions
     /// of the copy set and this one does not, as PySpark's `copy.deepcopy` of 
an Observation.
-    pub(crate) fn detached(&self) -> Observation {
+    /// Not a stable API.
+    #[doc(hidden)]
+    pub fn detached(&self) -> Observation {
+        let state = self.lock();
+        Observation {
+            state: Arc::new(Mutex::new(ObservationState {
+                name: state.name.clone(),
+                result: state
+                    .result
+                    .as_ref()
+                    .map(|result| 
Arc::new(Mutex::new(lock_metrics(result).clone()))),
+                error: state.error.clone(),
+            })),
+        }
+    }
+
+    /// A copy of this observation, of its name and of its state as it is now, 
as PySpark's
+    /// `copy.copy` of an Observation, which shares its result dict: the copy 
of a used
+    /// observation shares its metrics, which the actions that set those of 
this observation
+    /// set, while an error that one of them reports later is set on this 
observation only. The
+    /// copy of an unused observation is used on its own. Not a stable API.
+    #[doc(hidden)]
+    pub fn shallow_copy(&self) -> Observation {
         let state = self.lock();
         Observation {
             state: Arc::new(Mutex::new(ObservationState {
@@ -109,16 +158,17 @@ impl Observation {
 
     /// Mark the observation used, with no metrics until an action observes 
them.
     pub(crate) fn start(&self) {
-        self.lock().result = Some(Vec::new());
+        self.lock().result = Some(Arc::default());
     }
 
     /// Set the metrics that an action observed, as PySpark's client updates 
the result of
     /// the observation with them: a metric replaces the value of a metric of 
its name.
     pub(crate) fn update(&self, keys: &[String], values: 
&[proto::expression::Literal]) {
-        let mut state = self.lock();
-        let Some(result) = state.result.as_mut() else {
+        let state = self.lock();
+        let Some(result) = &state.result else {
             return;
         };
+        let mut result = lock_metrics(result);
         for (key, value) in keys.iter().zip(values) {
             match result.iter_mut().find(|(name, _)| name == key) {
                 Some((_, existing)) => *existing = value.clone(),
@@ -137,6 +187,12 @@ impl Observation {
     }
 }
 
+/// The lock of `metrics`, which is taken while the state of the observation 
is locked, never
+/// the other way around.
+fn lock_metrics(metrics: &Mutex<Metrics>) -> MutexGuard<'_, Metrics> {
+    metrics.lock().unwrap_or_else(|e| e.into_inner())
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -249,4 +305,42 @@ mod tests {
             .message()
             .contains("failed"));
     }
+
+    #[test]
+    fn 
a_shallow_copy_shares_the_metrics_of_a_used_observation_but_not_a_later_error() 
{
+        let names = |o: &Observation| -> Vec<String> {
+            o.get().unwrap().into_iter().map(|(name, _)| name).collect()
+        };
+        // A copy of an unused observation is used on its own, and keeps no 
name that the
+        // observation gets when it is used.
+        let unnamed = Observation::unnamed();
+        let unused = unnamed.shallow_copy();
+        assert!(!unused.same(&unnamed));
+        unnamed.name_to_observe().unwrap();
+        unnamed.start();
+        assert_eq!(unused.name(), None);
+        assert!(unused.get().is_err());
+        unused.name_to_observe().unwrap();
+
+        // A copy of a used observation has the metrics that the actions set 
later too, as
+        // PySpark's copy of an Observation shares its result dict, and is 
used already.
+        let obs = Observation::new("s");
+        obs.start();
+        obs.update(&["a".to_string()], &[long(1)]);
+        let copy = obs.shallow_copy();
+        assert!(!copy.same(&obs));
+        assert_eq!(copy.name().as_deref(), Some("s"));
+        obs.update(&["b".to_string()], &[long(2)]);
+        assert_eq!(names(&copy), vec!["a", "b"]);
+        let err = copy.name_to_observe().unwrap_err();
+        assert_eq!(err.get_condition().as_deref(), Some("REUSE_OBSERVATION"));
+
+        // An error that an action reports later is set on the observation 
only, and a copy of a
+        // failed observation keeps its error.
+        obs.set_error(SparkError::connect_msg("failed"));
+        assert!(obs.get().is_err());
+        assert_eq!(names(&copy), vec!["a", "b"]);
+        let failed = obs.shallow_copy().get().unwrap_err();
+        assert!(failed.message().contains("failed"));
+    }
 }
diff --git a/python/pyspark/sql/observation.py 
b/python/pyspark/sql/observation.py
index d8f85547..ba813a5e 100644
--- a/python/pyspark/sql/observation.py
+++ b/python/pyspark/sql/observation.py
@@ -2,3 +2,9 @@
 from pyspark._pyspark import Observation
 
 __all__ = ["Observation"]
+
+# The module of the class, pyspark.sql.connect.observation, that of PySpark's 
Observation of
+# Spark Connect, is imported with this one, after the class, which it 
re-exports: cloudpickle
+# finds a module only in sys.modules, so it then pickles the class by 
reference to it, as it
+# pickles PySpark's, and a Python worker of the server unpickles PySpark's 
Observation.
+import pyspark.sql.connect.observation  # noqa: E402,F401
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 8f81e551..25cdc9b7 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -3945,6 +3945,28 @@ def 
test_a_deep_copy_of_a_dataframe_sets_its_own_observations_as_pyspark(session
     assert first.get == {"c": 3} and second.get == {"c": 5}
 
 
+def 
test_an_observation_copies_and_pickles_as_the_plain_object_of_pyspark(session):
+    # As PySpark's Observation, a plain object: a shallow copy shares the 
metrics that the actions
+    # set later, a deep copy keeps those that it had, and one pickled into the 
server's Python
+    # worker, whose PySpark has no Rust client, unpickles as PySpark's of its 
name and metrics.
+    import copy
+
+    from pyspark.sql import Observation
+
+    observation = Observation("copied")
+    df = session.range(3).observe(observation, F.count(F.lit(1)).alias("c"))
+    shallow, deep = copy.copy(observation), copy.deepcopy(observation)
+    assert df.count() == 3
+    assert observation.get == {"c": 3} and shallow.get == {"c": 3} and 
deep.get == {}
+
+    @F.udf("string")
+    def unpickled(_):
+        return f"{type(observation).__module__} {observation._name} 
{observation.get}"
+
+    assert session.range(1).select(unpickled("id")).first()[0] == (
+        "pyspark.sql.connect.observation copied {'c': 3}")
+
+
 def test_try_cast_and_isin_raise_the_errors_of_pyspark(session):
     # As PySpark Connect's: try_cast of an int, and isin of a tuple, raise 
PySpark's errors.
     from pyspark.errors import PySparkTypeError
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 82d2f726..01100dd2 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -10223,6 +10223,149 @@ def 
test_a_deep_copy_of_a_join_sets_the_observations_of_its_copy_as_pyspark(mock
     assert first.get == {"c": 3} and second.get == {"c": 5}
 
 
+def test_an_observation_copies_as_the_plain_object_of_pyspark(mock_connect):
+    # As copy.copy and copy.deepcopy of PySpark's Observation, a plain object: 
a copy of an unused
+    # one is of its name and is used on its own; a shallow copy of a used one 
shares its result
+    # dict, so it has the metrics that the actions set later too, while a deep 
copy keeps those
+    # that it had; both are used; and the attributes are copied as a plain 
object's.
+    import copy
+
+    from pyspark.errors import PySparkAssertionError
+    from pyspark.sql import Observation
+    from pyspark.sql import functions as F
+
+    spark, service = mock_connect
+    observation = Observation("o")
+    for unused in (copy.copy(observation), copy.deepcopy(observation)):
+        assert unused is not observation and unused._name == "o"
+        with pytest.raises(PySparkAssertionError, 
match="NO_OBSERVE_BEFORE_GET"):
+            unused.get
+    unnamed = Observation()
+    copied = copy.copy(unnamed)
+    spark.range(1).observe(copied, F.count(F.lit(1)).alias("c"))
+    assert copied._name is not None and unnamed._name is None
+    with pytest.raises(PySparkAssertionError, match="NO_OBSERVE_BEFORE_GET"):
+        unnamed.get
+    spark.range(1).observe(unnamed, F.count(F.lit(1)).alias("c"))
+    assert unnamed._name not in (None, copied._name)
+
+    df = spark.range(3).observe(observation, F.count(F.lit(1)).alias("c"))
+    shallow, deep = copy.copy(observation), copy.deepcopy(observation)
+    assert shallow.get == {} and deep.get == {}
+    batch, observed = _count_batch_and_observed_metrics(service, df)
+    service.execute_payload = batch + observed("o", varint_field(7, 3), "c")
+    assert df.count() == 3
+    assert observation.get == {"c": 3} and shallow.get == {"c": 3} and 
deep.get == {}
+    later = copy.deepcopy(observation)
+    for used in (shallow, deep, later, copy.copy(observation)):
+        with pytest.raises(PySparkAssertionError, match="REUSE_OBSERVATION"):
+            spark.range(1).observe(used, F.count(F.lit(1)).alias("c"))
+    service.execute_payload = batch + observed("o", varint_field(7, 4), "c")
+    assert df.count() == 3
+    assert observation.get == {"c": 4} and shallow.get == {"c": 4} and 
later.get == {"c": 3}
+
+    observation.tags = ["t"]
+    observation.me = observation
+    shallow = copy.copy(observation)
+    assert shallow.tags is observation.tags and shallow.me is observation
+    deep = copy.deepcopy(observation)
+    assert deep.tags == ["t"] and deep.tags is not observation.tags and 
deep.me is deep
+    both = copy.deepcopy([observation, observation])
+    assert both[0] is both[1] and both[0] is not observation and both[0].get 
== {"c": 4}
+
+
+def test_an_observation_pickles_as_the_plain_object_of_pyspark(mock_connect):
+    # As pickle of PySpark's Observation, a plain object of 
pyspark.sql.connect.observation, of
+    # its __dict__: _name, _result and _error. So a Python worker of the 
server, whose PySpark
+    # has no Rust client, unpickles PySpark's Observation, and this client its 
own: an unused one
+    # is used on its own, a used one keeps its metrics, which no action sets, 
and a failed one
+    # raises its error, of the class and the message of the error that the 
server sent.
+    import copy
+    import copyreg
+    import io
+    import pickle
+    import subprocess
+    import sys
+
+    from pyspark import cloudpickle
+    from pyspark.errors import PySparkAssertionError
+    from pyspark.sql import Observation
+    from pyspark.sql import functions as F
+
+    class Worker(pickle.Unpickler):
+        # The classes that a worker's PySpark finds: a plain class for the 
Observation.
+        def find_class(self, module, name):
+            if (module, name) == ("pyspark.sql.connect.observation", 
"Observation"):
+                return type("Observation", (), {})
+            return super().find_class(module, name)
+
+    def on_worker(observation):
+        # As cloudpickle pickles it into a worker, by reference to the class, 
and as pickle does.
+        pickled = [vars(Worker(io.BytesIO(dumps(observation))).load())
+                   for dumps in (pickle.dumps, cloudpickle.dumps)]
+        # An exception is equal only to itself: compare its class and message.
+        same = [{k: (type(v), str(v)) if isinstance(v, BaseException) else v
+                 for k, v in state.items()} for state in pickled]
+        assert same[0] == same[1]
+        return pickled[1]
+
+    # cloudpickle finds the module of a class only in sys.modules, which 
pyspark.sql fills with it,
+    # in a new process too.
+    script = "import sys, pyspark.sql\nprint('pyspark.sql.connect.observation' 
in sys.modules)\n"
+    imported = subprocess.run([sys.executable], input=script, 
capture_output=True, text=True,
+                              check=True)
+    assert imported.stdout.strip() == "True"
+    spark, service = mock_connect
+    unused = pickle.loads(pickle.dumps(Observation("u")))
+    assert type(unused) is Observation and unused._name == "u"
+    assert on_worker(Observation("u")) == {"_name": "u", "_result": None, 
"_error": None}
+    spark.range(1).observe(unused, F.count(F.lit(1)).alias("c"))
+    assert pickle.loads(pickle.dumps(unused)).get == {}
+
+    observation = Observation("o")
+    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
+    observation.tag = "t"
+    restored = pickle.loads(pickle.dumps(observation))
+    assert restored.get == {"c": 3} and restored._name == "o" and restored.tag 
== "t"
+    assert restored.get is restored.get
+    assert on_worker(observation) == {"_name": "o", "_result": {"c": 3}, 
"_error": None,
+                                      "tag": "t"}
+    assert pickle.loads(pickle.dumps(observation, protocol=2)).get == {"c": 3}
+    assert observation.__reduce_ex__(4)[:2] == (copyreg.__newobj__, 
(Observation,))
+    with pytest.raises(PySparkAssertionError, match="REUSE_OBSERVATION"):
+        spark.range(1).observe(restored, F.count(F.lit(1)).alias("c"))
+    service.execute_payload = batch + observed("o", varint_field(7, 4), "c")
+    assert df.count() == 3
+    assert observation.get == {"c": 4} and restored.get == {"c": 3}
+    shallow, deep = copy.copy(restored), copy.deepcopy(restored)
+    assert shallow.get is restored.get and deep.get == {"c": 3} and deep.get 
is not restored.get
+
+    # ExecutePlanResponse.observed_metrics=6: ObservedMetrics.name=1, 
root_error_idx=5, errors=6;
+    # Error.error_type_hierarchy=1, message=2, spark_throwable=5; 
SparkThrowable.error_class=1,
+    # sql_state=4.
+    failed = Observation("f")
+    failing = spark.range(3).observe(failed, F.count(F.lit(1)).alias("c"))
+    error = (message_field(1, "org.apache.spark.SparkArithmeticException")
+             + message_field(1, "java.lang.ArithmeticException")
+             + message_field(2, "[DIVIDE_BY_ZERO] Division by zero. SQLSTATE: 
22012")
+             + message_field(5, message_field(1, "DIVIDE_BY_ZERO") + 
message_field(4, "22012")))
+    service.execute_payload = batch + message_field(
+        6, message_field(1, "f") + varint_field(5, 0) + message_field(6, 
error))
+    assert failing.count() == 3
+    with pytest.raises(Exception, match="DIVIDE_BY_ZERO") as raised:
+        failed.get
+    assert type(raised.value).__name__ == "ArithmeticException"
+    for copied in (pickle.loads(pickle.dumps(failed)), 
copy.deepcopy(pickle.loads(
+            pickle.dumps(failed)))):
+        with pytest.raises(type(raised.value)) as again:
+            copied.get
+        assert str(again.value) == str(raised.value)
+    assert type(on_worker(failed)["_error"]) is type(raised.value)
+
+
 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