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 f75107f3 [SPARK-61537][FOLLOWUP][CONNECT][PYTHON] Copy the 
Observations, the execution info and the HTML repr state of copies, deep copies 
and unpickles of a DataFrame as PySpark does
f75107f3 is described below

commit f75107f301266415d160e077b0dc8d8acfd105fa
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 14:02:53 2026 +0900

    [SPARK-61537][FOLLOWUP][CONNECT][PYTHON] Copy the Observations, the 
execution info and the HTML repr state of copies, deep copies and unpickles of 
a DataFrame as PySpark does
    
    ### What changes were proposed in this pull request?
    
    A follow-up of SPARK-61537 (43158969, the Observations of a deep copy), 
from a post-merge review. In PySpark 4.3.0, `copy.copy`, `copy.deepcopy` and 
pickling of a Connect DataFrame all go through `DataFrame.__reduce__`. 
`copy._reconstruct` deep-copies the plan and the session with the memo of the 
whole `deepcopy` call, and restores the state (`_support_repr_html`, 
`_cached_schema`). The drop-in's `__copy__`/`__deepcopy__` from SPARK-61537 
differed from that in several ways:
    
    - `copy.deepcopy` ignored the memo. A deep copy of a DataFrame and its 
Observation in one call, such as `copy.deepcopy((df, o))`, a list or an object 
holding both, gave the copied DataFrame a hidden copy of the Observation, so 
the user's copied Observation never got the metrics; PySpark's does. The plan's 
Observations are now copied with `copy.deepcopy(py_obs, memo)`, through a weak 
handle from each Observation's state to its Python object. Memo identity then 
holds: either order, seve [...]
    - The session is deep-copied with the memo too, as `_reconstruct` does, so 
a deep copy on a thread without an active session raises `NO_ACTIVE_SESSION`, 
as PySpark's. Before, it copied.
    - `copy.copy` shared the original's `executionInfo`, which was a 
regression: the copy showed the original's last execution and overwrote it. A 
copy now starts with its own, as PySpark's starts at `None`.
    - A deep copy, and an unpickle, dropped `_support_repr_html`, so with eager 
evaluation on, `repr` of a copy printed the table where PySpark prints 
`DataFrame[id: bigint]`.
    - An unpickled DataFrame shared the Observations of the live plan with its 
plan ID. Unpickling a deep copy therefore set the original's Observation, the 
bug that SPARK-61537 fixed, reached by another route. It now gets copies, as 
PySpark's unpickled plan has.
    
    `docs/compatibility.md` also notes a PyO3 limit: an Observation that 
PySpark pickled at protocol 0 or 1 does not load in this client, since its 
class has a native base. Protocols 2 to 5 are byte-identical both ways.
    
    ### Why are the changes needed?
    
    To match PySpark 4.3.0. The review's probes (`df_deep.py`, `df_ei.py`, 
`unpickle_obs.py`, `df_copy2.py`) and new probes of threads, memos and sessions 
now give the same results on official pyspark-client 4.3.0 and on this client, 
in every case. The one exception, pickling a `(DataFrame, Observation)` tuple, 
needs a redesign of the Observation pickle and is left as a known difference.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, in the Python client. The copies, deep copies and unpickles of a 
DataFrame keep, share or copy its Observations, its execution info and its HTML 
repr state as PySpark's do. A deep copy without an active session raises 
`NO_ACTIVE_SESSION`.
    
    ### How was this patch tested?
    
    - 5 new offline tests and 1 e2e test. They fail without the change, each on 
its own finding.
    - New and updated Rust tests.
    - The whole `test_dropin_offline.py` (1967 passed, 8 skipped), and the 
related e2e tests against a Spark 4.3.0 server.
    - `cargo test -p apache-spark-connect --release --lib` (676 passed), the 
build of all tests, `cargo fmt --all --check` and ruff.
    
    ### 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 #610 from HyukjinKwon/SPARK-61537-followup.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/dataframe.rs      |  89 ++++++++---
 crates/pyspark-rs/src/observation.rs    |  54 +++++++
 crates/spark-connect/src/dataframe.rs   | 253 ++++++++++++++++++++++++++++----
 crates/spark-connect/src/observation.rs |  34 +++++
 crates/spark-connect/src/plan.rs        |  10 +-
 docs/compatibility.md                   |   5 +
 python/pyspark/sql/connect/dataframe.py |  18 ++-
 python/tests/test_dropin_e2e.py         |  37 +++++
 python/tests/test_dropin_offline.py     | 198 +++++++++++++++++++++++++
 9 files changed, 633 insertions(+), 65 deletions(-)

diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index b31aac2b..198aa899 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -212,6 +212,19 @@ impl PyDataFrame {
         }
     }
 
+    /// The DataFrame of `dataframe`, a copy of this one, with the 
`_support_repr_html` of this
+    /// one, as the state of PySpark's DataFrame carries it to its copies. Its 
other answers are
+    /// its own, as PySpark keeps them for each DataFrame.
+    fn copy_of(&self, dataframe: DataFrame) -> PyDataFrame {
+        let copy = PyDataFrame::new(dataframe);
+        copy.support_repr_html.store(
+            self.support_repr_html
+                .load(std::sync::atomic::Ordering::SeqCst),
+            std::sync::atomic::Ordering::SeqCst,
+        );
+        copy
+    }
+
     /// The number of rows and the truncation of the eager evaluation, as 
PySpark's `int` of
     /// each setting, if it is enabled.
     fn eager_eval(&self, py: Python<'_>) -> PyResult<Option<(i32, i32)>> {
@@ -686,9 +699,11 @@ impl PyDataFrame {
     }
 
     /// A DataFrame pickles, as PySpark Connect's, of its session, which gives 
back the active
-    /// session of its ID, and of its plan, here the bytes of its relation. 
The session unpickles
-    /// first: so on a Python worker of the server, which has no active 
session, a pickled
-    /// DataFrame raises `NO_ACTIVE_SESSION`, as PySpark's does.
+    /// session of its ID, of its plan, here the bytes of its relation, and of 
the
+    /// `_support_repr_html` of its state. The session unpickles first: so on 
a Python worker of
+    /// the server, which has no active session, a pickled DataFrame raises 
`NO_ACTIVE_SESSION`,
+    /// as PySpark's does. The unpickled DataFrame has copies of the 
Observations of this one
+    /// (see `DataFrame::from_sent_relation`).
     fn __reduce__<'py>(slf: &Bound<'py, Self>) -> PyResult<Bound<'py, PyAny>> {
         let py = slf.py();
         let this = slf.borrow();
@@ -698,38 +713,64 @@ impl PyDataFrame {
                 this.spark_session(py)?,
                 this._relation_bytes(py)?,
                 this.dataframe.plan_levels(),
+                this.support_repr_html
+                    .load(std::sync::atomic::Ordering::SeqCst),
             ))
     }
 
     /// The shallow copy of a DataFrame, as PySpark's `copy.copy` of its 
`__reduce__`: the same
     /// plan, and so the same Observations, as PySpark's copy shares its plan, 
with the
-    /// `_support_repr_html` that its state carries.
+    /// `_support_repr_html` and the schema that its state carries, and an 
`executionInfo` of its
+    /// own, None until it executes, as that of PySpark's `DataFrame(plan, 
session)`.
     fn __copy__(&self) -> PyDataFrame {
-        let copy = PyDataFrame::new(self.dataframe.clone());
-        copy.support_repr_html.store(
-            self.support_repr_html
-                .load(std::sync::atomic::Ordering::SeqCst),
-            std::sync::atomic::Ordering::SeqCst,
-        );
-        copy
-    }
-
-    /// The deep copy of a DataFrame, as PySpark's `copy.deepcopy`: the same 
plan, whose
-    /// Observations are copies of its own, which the actions of the copy set. 
`copy.copy` and
-    /// pickling keep sharing them.
-    fn __deepcopy__(&self, _memo: &Bound<'_, PyAny>) -> PyResult<PyDataFrame> {
-        let copy = crate::on_grown_stack(|| 
self.dataframe.detached_copy()).to_pyerr()?;
-        Ok(PyDataFrame::new(copy))
+        self.copy_of(self.dataframe.shallow_copy())
+    }
+
+    /// The deep copy of a DataFrame, as PySpark's `copy.deepcopy` of its 
`__reduce__`, which
+    /// copies its plan and then its session with the memo of the call: the 
same relation and
+    /// plan ID, with the `_support_repr_html` and the schema that its state 
carries and an
+    /// `executionInfo` of its own, whose Observations are the copies of those 
of this DataFrame
+    /// in `memo` (see `observation::deep_copy_in`). So an Observation that 
the call copies too,
+    /// in a tuple or an object that holds both, is copied once, and the 
actions of the copied
+    /// DataFrame set the copy; the Observations of this DataFrame stay as 
they are. The copy of
+    /// the session is that of its `__reduce__`, the active session of its ID, 
once in a call: so
+    /// a deep copy raises `NO_ACTIVE_SESSION` where no session is active, as 
on another thread,
+    /// and `PySparkAssertionError` where another one is, while `copy.copy` 
keeps the session.
+    fn __deepcopy__(&self, py: Python<'_>, memo: &Bound<'_, PyAny>) -> 
PyResult<PyDataFrame> {
+        let observations = self
+            .dataframe
+            .observations()
+            .into_iter()
+            .map(|(name, observation)| {
+                Ok((
+                    name,
+                    crate::observation::deep_copy_in(py, &observation, memo)?,
+                ))
+            })
+            .collect::<PyResult<Vec<_>>>()?;
+        let session = py
+            .import("copy")?
+            .call_method1(
+                pyo3::intern!(py, "deepcopy"),
+                (self.spark_session(py)?, memo),
+            )?
+            .extract::<PyRef<'_, crate::session::PySparkSession>>()?
+            .session
+            .clone();
+        let copy = crate::on_grown_stack(|| 
self.dataframe.deep_copy_with(session, observations))
+            .to_pyerr()?;
+        Ok(self.copy_of(copy))
     }
 
     /// The DataFrame of `relation`, the bytes of a relation of `levels` 
levels of `session`, as a
-    /// pickled DataFrame unpickles.
+    /// pickled DataFrame unpickles, with the `_support_repr_html` of its 
state.
     #[staticmethod]
-    #[pyo3(signature = (session, relation, levels=1))]
+    #[pyo3(signature = (session, relation, levels=1, support_repr_html=false))]
     fn _of_relation(
         session: &Bound<'_, crate::session::PySparkSession>,
         relation: &[u8],
         levels: usize,
+        support_repr_html: bool,
     ) -> PyResult<PyDataFrame> {
         let session = session.borrow().session.clone();
         use prost::Message;
@@ -742,7 +783,11 @@ impl PyDataFrame {
         })
         .map_err(|error| 
pyo3::exceptions::PyValueError::new_err(error.to_string()))?
         .to_pyerr()?;
-        Ok(PyDataFrame::new(dataframe))
+        let dataframe = PyDataFrame::new(dataframe);
+        dataframe
+            .support_repr_html
+            .store(support_repr_html, std::sync::atomic::Ordering::SeqCst);
+        Ok(dataframe)
     }
 
     /// The plan of this DataFrame, as PySpark Connect's `DataFrame._plan`, 
whose
diff --git a/crates/pyspark-rs/src/observation.rs 
b/crates/pyspark-rs/src/observation.rs
index fea49390..d09ca781 100644
--- a/crates/pyspark-rs/src/observation.rs
+++ b/crates/pyspark-rs/src/observation.rs
@@ -157,6 +157,9 @@ impl PyObservation {
                 restored: Restored::default(),
             },
         )?;
+        // The copy is the Observation of the state that the deep copy of a 
DataFrame of the call
+        // holds, which a deep copy of that DataFrame copies with the copy.
+        keep_handle(&copy)?;
         // 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)?;
@@ -283,6 +286,54 @@ fn metrics_dict(
     Ok(result)
 }
 
+/// Keep a weak reference to `observation` on its state, by which the deep 
copy of a DataFrame
+/// whose plan holds the state finds it (see [`deep_copy_in`]).
+fn keep_handle(observation: &Bound<'_, PyObservation>) -> PyResult<()> {
+    let weak = 
pyo3::types::PyWeakrefReference::new(observation.as_any())?.unbind();
+    observation
+        .borrow()
+        .inner
+        .set_handle(std::sync::Arc::new(weak));
+    Ok(())
+}
+
+/// The Python Observation of `observation`, a state that a plan holds, while 
it is alive: the
+/// one of [`keep_handle`], if it still has this state.
+fn python_observation<'py>(
+    py: Python<'py>,
+    observation: &Observation,
+) -> Option<Bound<'py, PyObservation>> {
+    let handle = observation.handle()?;
+    let weak = handle.downcast_ref::<Py<pyo3::types::PyWeakrefReference>>()?;
+    let python = weak.bind(py).upgrade_as::<PyObservation>().ok().flatten()?;
+    // `__setstate__` gives an Observation a state of its own.
+    let same = python.borrow().inner.same(observation);
+    same.then_some(python)
+}
+
+/// The copy of `observation`, an Observation of the plan of a DataFrame that 
`copy.deepcopy`
+/// copies with `memo`, as PySpark's deep copy of a plan copies the 
Observation that it holds,
+/// with the memo of the call: the deep copy of its Python Observation in 
`memo`, the copy that
+/// the call made already, of the Observation itself or for another DataFrame, 
or that it makes
+/// now and gives to the objects that it copies later. So in the copy of a 
tuple of a DataFrame
+/// and its Observation, or of an object that holds both, the actions of the 
copied DataFrame
+/// set the copied Observation. A state that no Python Observation holds any 
more, which no
+/// other object of the call can refer to, has a copy of its own.
+pub(crate) fn deep_copy_in(
+    py: Python<'_>,
+    observation: &Observation,
+    memo: &Bound<'_, PyAny>,
+) -> PyResult<Observation> {
+    let Some(python) = python_observation(py, observation) else {
+        return Ok(observation.detached());
+    };
+    let copy = py
+        .import("copy")?
+        .call_method1(pyo3::intern!(py, "deepcopy"), (python, memo))?;
+    let copy = copy.extract::<PyRef<'_, PyObservation>>()?;
+    Ok(copy.inner.clone())
+}
+
 /// 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(
@@ -324,6 +375,9 @@ pub(crate) fn observe(
     let observed = crate::interrupt::interruptible(py, &df.spark_session(), || 
{
         df.observe_with(&inner, exprs)
     })?;
+    // The plan holds the state of the Observation, as PySpark's holds the 
Observation itself,
+    // which a deep copy of the plan copies with the memo of the call.
+    keep_handle(observation)?;
     Ok(PyDataFrame::new(observed))
 }
 
diff --git a/crates/spark-connect/src/dataframe.rs 
b/crates/spark-connect/src/dataframe.rs
index 961e1a04..c1b85898 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -1301,9 +1301,10 @@ impl DataFrame {
     /// The DataFrame of `relation`, a relation that `session` sent, such as 
that of a DataFrame
     /// that was pickled, which keeps its plan ID, as PySpark Connect's 
pickled plans keep
     /// theirs: so it is sent as it is, and the columns of the DataFrame it 
was of resolve
-    /// against it. While the DataFrame that it was of is alive, it has its 
Observations, as a
-    /// copy of PySpark's DataFrame has those of its plan: the actions of this 
one set them, and
-    /// raise for their metrics that PySpark does not convert. Not a stable 
API.
+    /// against it. While the DataFrame that it was of is alive, it has copies 
of its
+    /// Observations, as PySpark's unpickled plan has copies of those of the 
pickled one: the
+    /// actions of this one set the copies, not the Observations of that 
DataFrame, and raise for
+    /// their metrics that PySpark does not convert. Not a stable API.
     #[doc(hidden)]
     pub fn from_sent_relation(session: SparkSession, relation: 
proto::Relation) -> DataFrame {
         // A relation of one level holds no plan, as a relation built without 
a pickled plan.
@@ -1335,7 +1336,12 @@ impl DataFrame {
         let plan_id = relation.common.as_ref().and_then(|common| 
common.plan_id);
         let observations = plan_id
             .and_then(|plan_id| session.plan_ids().node_of(plan_id))
-            .map(|node| node.observations())
+            .map(|node| {
+                node.observations()
+                    .into_iter()
+                    .map(|(name, observation)| (name, observation.detached()))
+                    .collect()
+            })
             .unwrap_or_default();
         DataFrame::from_sent_relation_with(session, relation, levels, 
observations)
     }
@@ -1360,25 +1366,52 @@ impl DataFrame {
         dataframe
     }
 
-    /// The copy of this DataFrame that PySpark's `copy.deepcopy` makes: the 
same relation and
-    /// plan ID, whose Observations are detached copies of those of this 
DataFrame, as PySpark's
-    /// deep copy of its plan copies its Observations. So the actions of the 
copy set the copies,
-    /// and those of this DataFrame stay as they are. Not a stable API.
+    /// The Observations of the plan of this DataFrame by their names, whose 
metrics its actions
+    /// set, as PySpark's `LogicalPlan.observations`. Not a stable API.
+    #[doc(hidden)]
+    pub fn observations(&self) -> Vec<(String, 
crate::observation::Observation)> {
+        self.plan.observations()
+    }
+
+    /// The copy of this DataFrame that PySpark's `copy.copy` makes of its 
`__reduce__`: of the
+    /// same plan, and so of the same plan IDs and Observations, with the 
schema that this one
+    /// resolved, which the state of PySpark's DataFrame carries. The 
information of its last
+    /// execution is its own, empty until it executes, as that of PySpark's
+    /// `DataFrame(plan, session)`, and so is the answer of 
`is_local_on_server` that it keeps,
+    /// as PySpark's `isLocal` keeps one for each DataFrame. Not a stable API.
     #[doc(hidden)]
-    pub fn detached_copy(&self) -> Result<DataFrame> {
+    pub fn shallow_copy(&self) -> DataFrame {
+        DataFrame {
+            session: self.session.clone(),
+            plan: Arc::clone(&self.plan),
+            schema_cache: Arc::new(Mutex::new(self.cached_schema())),
+            is_local_cache: Arc::new(Mutex::new(None)),
+            execution: Arc::new(Mutex::new(None)),
+        }
+    }
+
+    /// The copy of this DataFrame that PySpark's `copy.deepcopy` makes, of 
`session`, the copy of
+    /// its session, whose Observations are `observations`, copies of those of 
this DataFrame
+    /// ([`DataFrame::observations`]) by their names: the same relation and 
plan ID, with the
+    /// schema that this one resolved, as the state of PySpark's DataFrame 
carries it, and an
+    /// information of executions of its own. PySpark's deep copy copies the 
plan, and so its
+    /// Observations, and then the session with the memo of the call, so that 
the copy of an
+    /// Observation or of the session that the call copies too is the one that 
the copied
+    /// DataFrame holds; 
[`Observation::detached`](crate::observation::Observation::detached)
+    /// gives a copy that nothing else shares, and the session of this 
DataFrame is its own copy
+    /// where nothing else is. So the actions of the copy set `observations`, 
and those of this
+    /// DataFrame its own. Not a stable API.
+    #[doc(hidden)]
+    pub fn deep_copy_with(
+        &self,
+        session: SparkSession,
+        observations: Vec<(String, crate::observation::Observation)>,
+    ) -> Result<DataFrame> {
         let relation = self.to_relation()?;
-        let observations = self
-            .plan
-            .observations()
-            .into_iter()
-            .map(|(name, observation)| (name, observation.detached()))
-            .collect();
-        Ok(DataFrame::from_sent_relation_with(
-            self.session.clone(),
-            relation,
-            self.plan_levels(),
-            observations,
-        ))
+        let mut copy =
+            DataFrame::from_sent_relation_with(session, relation, 
self.plan_levels(), observations);
+        copy.schema_cache = Arc::new(Mutex::new(self.cached_schema()));
+        Ok(copy)
     }
 
     /// The levels of the plan of this DataFrame, as a pickled DataFrame 
records them for
@@ -5853,6 +5886,17 @@ mod plan_construction_tests {
         assert_eq!(error.get_error_class().as_deref(), 
Some("SESSION_NOT_SAME"));
     }
 
+    /// The deep copy of `df` whose Observations are detached copies of its 
own, as the Python
+    /// client copies those that no Python object holds.
+    fn detached_copy(df: &DataFrame) -> DataFrame {
+        let observations = df
+            .observations()
+            .into_iter()
+            .map(|(name, observation)| (name, observation.detached()))
+            .collect();
+        df.deep_copy_with(df.session.clone(), observations).unwrap()
+    }
+
     /// As PySpark's `copy.deepcopy` of a DataFrame: the copy keeps the plan 
ID, and its
     /// Observations are detached copies of those of the DataFrame, with their 
state as it is
     /// when it is copied. So the metrics that the actions of the copy observe 
set the copy's,
@@ -5899,7 +5943,7 @@ mod plan_construction_tests {
             capture_execution(&mut resp, &mut info, &spark, 
&df.plan.observations()).unwrap();
         };
 
-        let copy = df.detached_copy().unwrap();
+        let copy = detached_copy(&df);
         assert_eq!(
             spark.plan_ids().id_of(&copy.plan),
             spark.plan_ids().id_of(&df.plan)
@@ -5917,7 +5961,7 @@ mod plan_construction_tests {
         // The copy keeps the state of the Observation as it was when copied.
         assert!(value(&copied[0].1).is_empty());
         // A copy of the DataFrame after the action has the metrics of the 
action.
-        let later = df.detached_copy().unwrap();
+        let later = detached_copy(&df);
         assert_eq!(
             value(&later.plan.observations()[0].1),
             vec![("c".to_string(), Some(LiteralType::Long(5)))]
@@ -5932,14 +5976,157 @@ mod plan_construction_tests {
             value(&observation),
             vec![("c".to_string(), Some(LiteralType::Long(5)))]
         );
+    }
+
+    /// `df` observed by `observation` with `count(1)` by the name `c`, as 
`observe_with` makes
+    /// it.
+    fn observe_count(df: &DataFrame, observation: 
&crate::observation::Observation) -> DataFrame {
+        let count = crate::functions::count(crate::column::lit(1));
+        df.observed_with(
+            observation,
+            "c".to_string(),
+            vec![count.expression().clone()],
+        )
+    }
+
+    /// Set `value` as the metric `c` of an action of `df`, as the server 
reports it by the plan
+    /// ID of `df`, on the Observations of its plan.
+    fn report_count(df: &DataFrame, value: i64) {
+        let mut resp = proto::ExecutePlanResponse {
+            observed_metrics: 
vec![proto::execute_plan_response::ObservedMetrics {
+                name: "c".to_string(),
+                values: vec![proto::expression::Literal {
+                    literal_type: 
Some(proto::expression::literal::LiteralType::Long(value)),
+                    ..Default::default()
+                }],
+                keys: vec!["c".to_string()],
+                plan_id: df.session.plan_ids().id_of(&df.plan),
+                ..Default::default()
+            }],
+            ..Default::default()
+        };
+        let mut info = ExecutionInfo::default();
+        capture_execution(&mut resp, &mut info, &df.session, 
&df.observations()).unwrap();
+    }
+
+    /// The values of the metrics of `observation`, which are longs.
+    fn counts(observation: &crate::observation::Observation) -> Vec<i64> {
+        use proto::expression::literal::LiteralType;
+        observation
+            .get()
+            .unwrap()
+            .into_iter()
+            .map(|(_, value)| match value.literal_type {
+                Some(LiteralType::Long(value)) => value,
+                other => panic!("not a long: {other:?}"),
+            })
+            .collect()
+    }
+
+    /// As PySpark's `copy.deepcopy` of a DataFrame, which copies the plan, 
and so its
+    /// Observations, and the session with the memo of the call: the copy is 
of the session and
+    /// holds the copies that it is given, which its actions set, and keeps 
the plan ID and the
+    /// schema that the DataFrame resolved, with an information of executions 
of its own.
+    #[test]
+    fn 
a_deep_copy_holds_the_given_copies_of_the_observations_as_pyspark_deep_copies() 
{
+        use crate::observation::Observation;
+        let spark = session();
+        let observation = Observation::new("c");
+        let df = observe_count(&spark.range(3).unwrap(), &observation);
+        let schema = DataType::Struct { fields: vec![] };
+        *df.schema_cache.lock().unwrap() = Some(Arc::new(schema.clone()));
+        df.record_execution(ExecutionInfo::default());
+
+        let given = observation.detached();
+        let copy = df
+            .deep_copy_with(spark.clone(), vec![("c".to_string(), 
given.clone())])
+            .unwrap();
+        assert!(copy.session.is_same_session(&spark));
+        assert_eq!(
+            spark.plan_ids().id_of(&copy.plan),
+            spark.plan_ids().id_of(&df.plan)
+        );
+        let held = copy.observations();
+        assert_eq!(held.len(), 1);
+        assert!(held[0].0 == "c" && held[0].1.same(&given));
+        assert_eq!(copy.cached_schema().as_deref(), Some(&schema));
+        assert!(copy.execution_info().is_err());
+
+        report_count(&copy, 3);
+        assert_eq!(counts(&given), [3]);
+        assert!(counts(&observation).is_empty());
+
+        // The copy of the session that a memo of the caller gives, as 
PySpark's copy is of it.
+        let other = spark.new_session();
+        let moved = df.deep_copy_with(other.clone(), Vec::new()).unwrap();
+        assert!(moved.session.is_same_session(&other) && 
!moved.session.is_same_session(&spark));
+        assert_eq!(
+            other.plan_ids().id_of(&moved.plan),
+            spark.plan_ids().id_of(&df.plan)
+        );
+    }
+
+    /// As PySpark's unpickled plan, which has copies of the Observations of 
the pickled one: a
+    /// DataFrame of a relation that the session sent has copies of the 
Observations of the
+    /// DataFrame that the relation is of, with their state as it is, which 
its actions set, and
+    /// not those of that DataFrame.
+    #[test]
+    fn 
a_dataframe_of_a_sent_relation_copies_the_observations_as_pysparks_unpickled_plan()
 {
+        use crate::observation::Observation;
+        let spark = session();
+        let observation = Observation::new("c");
+        let df = observe_count(&spark.range(3).unwrap(), &observation);
+        report_count(&df, 5);
+
+        let unpickled = DataFrame::from_sent_relation(spark.clone(), 
df.to_relation().unwrap());
+        let copies = unpickled.observations();
+        assert_eq!(copies.len(), 1);
+        assert!(copies[0].0 == "c" && !copies[0].1.same(&observation));
+        assert_eq!(counts(&copies[0].1), [5]);
+        report_count(&unpickled, 9);
+        assert_eq!(counts(&copies[0].1), [9]);
+        assert_eq!(counts(&observation), [5]);
+        report_count(&df, 7);
+        assert_eq!(counts(&copies[0].1), [9]);
+        assert_eq!(counts(&observation), [7]);
+    }
+
+    /// As PySpark's `copy.copy` of a DataFrame, of its `__reduce__`: the copy 
is of the same plan,
+    /// so of its plan ID and its Observations, and of the schema that the 
DataFrame resolved,
+    /// while the information of its last execution is its own, empty until it 
executes, as that
+    /// of PySpark's `DataFrame(plan, session)`. An exact clone shares it.
+    #[test]
+    fn 
a_shallow_copy_shares_the_plan_and_has_its_own_execution_as_pyspark_copies() {
+        use crate::observation::Observation;
+        let spark = session();
+        let observation = Observation::new("c");
+        let df = observe_count(&spark.range(3).unwrap(), &observation);
+        let schema = DataType::Struct { fields: vec![] };
+        *df.schema_cache.lock().unwrap() = Some(Arc::new(schema.clone()));
+        *df.is_local_cache.lock().unwrap() = Some(true);
+        let executed = |operation_id: &str| ExecutionInfo {
+            operation_id: Some(operation_id.to_string()),
+            ..Default::default()
+        };
+        let operation_id =
+            |df: &DataFrame| df.execution_info().ok().and_then(|info| 
info.operation_id);
+        df.record_execution(executed("original"));
+
+        let copy = df.shallow_copy();
+        assert!(Arc::ptr_eq(&copy.plan, &df.plan));
+        assert!(copy.observations()[0].1.same(&observation));
+        assert_eq!(copy.cached_schema().as_deref(), Some(&schema));
+        assert_eq!(*copy.is_local_cache.lock().unwrap(), None);
+        assert_eq!(operation_id(&copy), None);
+        copy.record_execution(executed("copy"));
+        assert_eq!(operation_id(&copy).as_deref(), Some("copy"));
+        assert_eq!(operation_id(&df).as_deref(), Some("original"));
+        report_count(&copy, 4);
+        assert_eq!(counts(&observation), [4]);
 
-        // A copy of the relation, as copy.copy and pickling make, shares the 
Observations of the
-        // DataFrame that the relation is of while it is alive, and then those 
of the first copy.
-        let shared = DataFrame::from_sent_relation(spark.clone(), 
df.to_relation().unwrap());
-        assert!(shared.plan.observations()[0].1.same(&observation));
-        std::mem::drop(df);
-        let shared = DataFrame::from_sent_relation(spark.clone(), 
copy.to_relation().unwrap());
-        assert!(shared.plan.observations()[0].1.same(&copied[0].1));
+        df.clone().record_execution(executed("clone"));
+        assert_eq!(operation_id(&df).as_deref(), Some("clone"));
+        assert_eq!(operation_id(&copy).as_deref(), Some("copy"));
     }
 
     /// As PySpark's client, which sets the metrics of `observations[name]`, 
of the Observations
@@ -6105,9 +6292,11 @@ mod plan_construction_tests {
         };
         let transformed = DataFrame::from_relation(spark.clone(), transform, 
None).unwrap();
         assert_observations(&transformed.limit(1), &[("m", &model_input)]);
-        // A copy, of a relation that the session sent, while the DataFrame it 
was of is alive.
+        // A copy, of a relation that the session sent, while the DataFrame it 
was of is alive:
+        // copies of its Observations, as PySpark's unpickled plan has.
         let copied = DataFrame::from_sent_relation(spark.clone(), 
input.to_relation().unwrap());
-        assert_observations(&copied.limit(1), &[("m", &model_input)]);
+        let copies = copied.limit(1).plan.observations();
+        assert!(copies.len() == 1 && copies[0].0 == "m" && 
!copies[0].1.same(&model_input));
         let sent = spark.range(1).unwrap().to_relation().unwrap();
         assert_observations(&DataFrame::from_sent_relation(spark.clone(), 
sent), &[]);
     }
diff --git a/crates/spark-connect/src/observation.rs 
b/crates/spark-connect/src/observation.rs
index 3b15faa7..ceb606bf 100644
--- a/crates/spark-connect/src/observation.rs
+++ b/crates/spark-connect/src/observation.rs
@@ -29,6 +29,9 @@ struct ObservationState {
     result: Option<Arc<Mutex<Metrics>>>,
     /// The error of collecting the metrics, which the server reported.
     error: Option<SparkError>,
+    /// What a binding of another language keeps for this observation (see
+    /// [`Observation::set_handle`]), which no copy of it has.
+    handle: Option<Arc<dyn std::any::Any + Send + Sync>>,
 }
 
 impl std::fmt::Debug for Observation {
@@ -117,10 +120,27 @@ impl Observation {
                     .as_ref()
                     .map(|result| 
Arc::new(Mutex::new(lock_metrics(result).clone()))),
                 error: state.error.clone(),
+                handle: None,
             })),
         }
     }
 
+    /// Keep `handle` for this observation, by which a binding of another 
language finds what
+    /// it made of it from the Observations of a plan: the Python client keeps 
a weak reference to
+    /// its Python Observation, which a deep copy of a DataFrame copies with 
the other objects of
+    /// the call, as PySpark's deep copy of a plan copies the Observation that 
the plan holds.
+    /// Not a stable API.
+    #[doc(hidden)]
+    pub fn set_handle(&self, handle: Arc<dyn std::any::Any + Send + Sync>) {
+        self.lock().handle = Some(handle);
+    }
+
+    /// The handle of [`Observation::set_handle`], if any. Not a stable API.
+    #[doc(hidden)]
+    pub fn handle(&self) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
+        self.lock().handle.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
@@ -134,6 +154,7 @@ impl Observation {
                 name: state.name.clone(),
                 result: state.result.clone(),
                 error: state.error.clone(),
+                handle: None,
             })),
         }
     }
@@ -343,4 +364,17 @@ mod tests {
         let failed = obs.shallow_copy().get().unwrap_err();
         assert!(failed.message().contains("failed"));
     }
+
+    #[test]
+    fn 
a_handle_is_kept_by_the_clones_of_an_observation_and_not_by_its_copies() {
+        // The handle of a binding, which finds its object by it from a clone 
of the observation
+        // that a plan holds; a copy is an observation of its own, which has 
none.
+        let obs = Observation::new("h");
+        assert!(obs.handle().is_none());
+        obs.set_handle(Arc::new("python"));
+        let kept = obs.clone().handle().unwrap();
+        assert_eq!(kept.downcast_ref::<&str>(), Some(&"python"));
+        assert!(obs.detached().handle().is_none());
+        assert!(obs.shallow_copy().handle().is_none());
+    }
 }
diff --git a/crates/spark-connect/src/plan.rs b/crates/spark-connect/src/plan.rs
index 1fb6e219..103444d5 100644
--- a/crates/spark-connect/src/plan.rs
+++ b/crates/spark-connect/src/plan.rs
@@ -706,10 +706,12 @@ impl PlanIds {
     /// relation within the `WithRelations` that sends it), and of each node 
that was given it
     /// (`assign`): each DataFrame of a relation that the session sent, such 
as each unpickled
     /// copy of a DataFrame, or a deep copy of one, is a node of its own with 
the plan ID of the
-    /// DataFrame it was of, which may be alive too. A deep copy has 
Observations of its own
-    /// (`DataFrame::detached_copy`), so the nodes of an ID may differ in 
them: the first given
-    /// the ID is taken, which is the DataFrame that the copies were made of, 
as long as it is
-    /// alive, so that a copy of a relation shares its Observations as 
PySpark's `copy.copy` does.
+    /// DataFrame it was of, which may be alive too. Each copy has 
Observations of its own
+    /// (`DataFrame::deep_copy_with`, `DataFrame::from_sent_relation`), so the 
nodes of an ID may
+    /// differ in them: the first given the ID is taken, which is the 
DataFrame that the copies
+    /// were made of, as long as it is alive, so that an unpickled DataFrame 
copies the
+    /// Observations of the DataFrame that was pickled, as PySpark's unpickled 
plan has copies of
+    /// those of the pickled one.
     ///
     /// This scans every node of the session, once for each DataFrame made of 
a sent relation,
     /// which costs less than keeping a second map by plan ID in step with the 
first on every
diff --git a/docs/compatibility.md b/docs/compatibility.md
index d8e2a8a4..ac2b542a 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -565,6 +565,11 @@ decodes server responses deeper than 100 nested messages, 
such as the schema of
 34 levels deep, which PySpark's client rejects with "Exception deserializing 
response!". The
 server is trusted, as SECURITY.md sets out, so this is not a bound on the 
responses.
 
+An `Observation` that PySpark pickled at protocol 0 or 1 raises a `TypeError` 
when the drop-in
+unpickles it, as CPython's `copyreg._reconstructor` cannot create the 
drop-in's `Observation`, a
+class with a native base; protocols 2 and up, pickle's default, load in both 
clients, and PySpark
+loads the drop-in's at every protocol.
+
 ## Native NaiveBayes
 
 The Rust `ml::NaiveBayes` and `ml::NaiveBayesModel` train and predict through 
Spark
diff --git a/python/pyspark/sql/connect/dataframe.py 
b/python/pyspark/sql/connect/dataframe.py
index 4d335aab..5358fc3d 100644
--- a/python/pyspark/sql/connect/dataframe.py
+++ b/python/pyspark/sql/connect/dataframe.py
@@ -53,18 +53,20 @@ _local_rows.__code__ = _local_rows.__code__.replace(
 
 
 def _reduce_dataframe(
-    session: Any, relation: bytes, levels: int = 1
+    session: Any, relation: bytes, levels: int = 1, support_repr_html: bool = 
False
 ) -> tuple[Callable[..., Any], tuple[Any, ...]]:
     """The ``__reduce__`` of a DataFrame of ``session`` and the bytes of its 
``relation`` of
-    ``levels`` levels, as PySpark Connect's, of its session and its plan: a 
function, which
-    cloudpickle pickles by value, of the session, which unpickles first, and 
of the relation.
+    ``levels`` levels, as PySpark Connect's, of its session, its plan and its 
state: a function,
+    which cloudpickle pickles by value, of the session, which unpickles first, 
of the relation,
+    and of ``support_repr_html``, the ``_support_repr_html`` of the state, 
which the DataFrame
+    that it gives back keeps.
 
     On a Python worker of the server, whose PySpark has no Rust client, such 
as the worker of a
     ``foreachBatch`` function, which has the active session of the query, the 
function gives
     back PySpark Connect's DataFrame of the relation, as PySpark's DataFrame 
of its plan unpickles
     there. So everything that it calls there is of PySpark, which the worker 
has."""
 
-    def creator(session: Any, relation: bytes, levels: int) -> Any:
+    def creator(session: Any, relation: bytes, levels: int, support_repr_html: 
bool) -> Any:
         try:
             from pyspark import _pyspark
         except ImportError:
@@ -89,8 +91,10 @@ def _reduce_dataframe(
                     sent.CopyFrom(self._relation)
                     return sent
 
-            return ConnectDataFrame(Relation(parse_deep(proto.Relation, 
relation)), session)
+            df = ConnectDataFrame(Relation(parse_deep(proto.Relation, 
relation)), session)
+            df._support_repr_html = support_repr_html
+            return df
 
-        return _pyspark.DataFrame._of_relation(session, relation, levels)
+        return _pyspark.DataFrame._of_relation(session, relation, levels, 
support_repr_html)
 
-    return creator, (session, relation, levels)
+    return creator, (session, relation, levels, support_repr_html)
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 4b83aed2..feeca9eb 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -3962,6 +3962,43 @@ 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_copies_of_a_dataframe_set_the_copies_of_its_call_or_their_own_as_pyspark(session):
+    # As PySpark's DataFrame.__reduce__: a deep copy copies the plan with the 
memo of the call, so
+    # the copy of an Observation that the call copies too, in a tuple, a list 
or an object that
+    # holds both, is the one whose metrics the actions of the copied DataFrame 
set; an unpickled
+    # DataFrame, or an unpickled deep copy, sets copies of its own; the 
Observation keeps its
+    # metrics. A shallow copy has an executionInfo of its own.
+    import copy
+    import pickle
+
+    from pyspark import cloudpickle
+    from pyspark.sql import Observation
+
+    class Holder:
+        def __init__(self, df, observation):
+            self.df, self.observation = df, observation
+
+    observation = Observation("of_the_call")
+    df = session.range(3).observe(observation, F.count(F.lit(1)).alias("c"))
+    holder = copy.deepcopy(Holder(df, observation))
+    pairs = [copy.deepcopy((df, observation)), copy.deepcopy([observation, 
df])[::-1],
+             (holder.df, holder.observation)]
+    for copied, copied_observation in pairs:
+        assert copied.count() == 3 and copied_observation.get == {"c": 3}
+    assert observation.get == {}
+    for unpickled in (pickle.loads(cloudpickle.dumps(df)),
+                      pickle.loads(cloudpickle.dumps(copy.deepcopy(df)))):
+        assert unpickled.count() == 3
+    assert observation.get == {}
+
+    named = session.range(3).observe("named_of_a_copy", 
F.count(F.lit(1)).alias("c"))
+    shallow = copy.copy(named)
+    assert shallow.collect() == [Row(id=0), Row(id=1), Row(id=2)]
+    assert named.executionInfo is None
+    assert shallow.executionInfo.flows == [("named_of_a_copy", {"c": 3})]
+    assert copy.copy(shallow).executionInfo is None
+
+
 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
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 9232fddf..d40a85bd 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -10719,6 +10719,204 @@ 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_a_deep_copy_copies_an_observation_once_with_the_objects_of_its_call_as_pyspark(
+        mock_connect):
+    # As PySpark's DataFrame.__reduce__, whose deep copy copies the plan, and 
so the Observation of
+    # its CollectMetrics, with the memo of the call: an Observation that the 
call copies too, in a
+    # tuple, a list or an object that holds both, in either order, is copied 
once, with its
+    # attributes, and the actions of the copied DataFrame set that copy; so do 
those of another
+    # DataFrame of the call, and of one copied with the same memo of the 
caller. The Observation
+    # itself keeps its metrics.
+    import copy
+
+    from pyspark.sql import Observation
+    from pyspark.sql import functions as F
+
+    class Holder:
+        def __init__(self, df, observation):
+            self.df, self.observation = df, observation
+
+    spark, service = mock_connect
+    observation = Observation("o")
+    observation.tags = ["t"]
+    df = spark.range(3).observe(observation, F.count(F.lit(1)).alias("c"))
+    batch, observed = _count_batch_and_observed_metrics(service, df)
+
+    def count(frame, value):
+        service.execute_payload = batch + observed("o", varint_field(7, 
value), "c")
+        return frame.count()
+
+    holder = copy.deepcopy(Holder(df, observation))
+    pairs = [copy.deepcopy((df, observation)), copy.deepcopy([observation, 
df])[::-1],
+             (holder.df, holder.observation)]
+    for value, (copied, copied_observation) in enumerate(pairs, start=3):
+        assert copied_observation is not observation and 
copied_observation._name == "o"
+        assert copied_observation.tags == ["t"] and copied_observation.tags is 
not observation.tags
+        assert count(copied, value) == 3
+        assert copied_observation.get == {"c": value} and observation.get == {}
+
+    first, second, copied_observation = copy.deepcopy([df, df.where("id > 0"), 
observation])
+    assert count(first, 6) == 3 and copied_observation.get == {"c": 6}
+    assert count(second, 7) == 3 and copied_observation.get == {"c": 7}
+    memo = {}
+    copied = copy.deepcopy(df, memo)
+    copied_observation = copy.deepcopy(observation, memo)
+    assert copy.deepcopy(df, memo) is copied
+    assert count(copied, 8) == 3 and copied_observation.get == {"c": 8}
+    # A deep copy of the copies copies them so too, and a shallow copy of a 
copy shares its copy.
+    copied, copied_observation = copy.deepcopy((df, observation))
+    again, copied_again = copy.deepcopy((copied, copied_observation))
+    assert count(again, 9) == 3 and copied_again.get == {"c": 9}
+    assert copied_observation.get == {} and observation.get == {}
+    assert count(copy.copy(copied), 11) == 3 and copied_observation.get == 
{"c": 11}
+    assert copied_again.get == {"c": 9} and observation.get == {}
+    # An attribute of the Observation that refers to the DataFrame refers to a 
copy of it of its
+    # own, of the copied Observation, as the copy of the plan copies the 
Observation first.
+    observation.df = df
+    copied, copied_observation = copy.deepcopy((df, observation))
+    assert copied_observation.df is not copied and copied_observation.df is 
not df
+    assert count(copied_observation.df, 10) == 3 and copied_observation.get == 
{"c": 10}
+    assert observation.get == {}
+
+
+def 
test_a_deep_copy_copies_the_session_with_the_objects_of_its_call_as_pyspark(mock_connect):
+    # As PySpark's DataFrame.__reduce__, whose deep copy copies the session 
after the plan with
+    # the memo of the call, by SparkSession.__reduce__: the active session of 
its ID, once in a
+    # call, so the copies of two DataFrames of the session share it, and a 
memo of the caller that
+    # maps it to another session gives a copy of that one. Where no session is 
active, as on
+    # another thread, a deep copy raises NO_ACTIVE_SESSION, and where another 
one is,
+    # PySparkAssertionError; copy.copy keeps the session.
+    import copy
+    import threading
+
+    from pyspark.errors import PySparkAssertionError, PySparkRuntimeError
+    from pyspark.sql import SparkSession
+
+    spark, service = mock_connect
+    df = spark.range(3)
+    memo = {}
+    copies = copy.deepcopy([df, spark.range(5)], memo)
+    assert all(copied.sparkSession is spark for copied in copies)
+    assert memo[id(spark)] is spark
+    seen = []
+
+    def on_a_thread():
+        try:
+            copy.deepcopy(df)
+        except PySparkRuntimeError as error:
+            seen.append(error.getCondition())
+        seen.append(copy.copy(df).sparkSession is spark)
+
+    thread = threading.Thread(target=on_a_thread)
+    thread.start()
+    thread.join()
+    assert seen == ["NO_ACTIVE_SESSION", True]
+    other = SparkSession.builder.remote(service.remote).create()
+    try:
+        assert SparkSession.getActiveSession() is spark
+        with pytest.raises(PySparkAssertionError, match="Expected session ID 
does not match"):
+            copy.deepcopy(other.range(1))
+        assert copy.deepcopy(df, {id(spark): other}).sparkSession is other
+    finally:
+        other.stop()
+
+
+def 
test_a_copy_of_a_dataframe_has_an_execution_info_of_its_own_as_pyspark(mock_connect):
+    # As PySpark's copy.copy of a DataFrame, a DataFrame(plan, session) of its 
plan: its
+    # executionInfo is None until it executes, also of a DataFrame that 
executed, and then that of
+    # its own executions, which leave the DataFrame's as it is; so is that of 
a deep copy and of an
+    # unpickled DataFrame.
+    import copy
+
+    from pyspark.serializers import CloudPickleSerializer
+
+    spark, service = mock_connect
+    serializer = CloudPickleSerializer()
+    df = spark.range(3)
+    copied = copy.copy(df)
+    copied.collect()
+    assert df.executionInfo is None
+    first = copied.executionInfo.operation_id
+    assert first == _request_operation_id(service.execute_requests[-1])
+    df.collect()
+    original = df.executionInfo.operation_id
+    assert original not in (None, first)
+    copied.collect()
+    assert df.executionInfo.operation_id == original
+    assert copied.executionInfo.operation_id not in (first, original)
+    for later in (copy.copy(df), copy.copy(copied), copy.deepcopy(df),
+                  serializer.loads(serializer.dumps(df))):
+        assert later.executionInfo is None
+
+
+def 
test_copies_and_unpickled_dataframes_keep_support_repr_html_as_pyspark(mock_connect):
+    # As PySpark's DataFrame.__reduce__, whose state carries 
_support_repr_html to a copy, a deep
+    # copy and an unpickled DataFrame: once _repr_html_ was called, their repr 
is the string of the
+    # schema with eager evaluation, else the table of eager evaluation; the 
_repr_html_ of a copy
+    # leaves the DataFrame as it is.
+    import copy
+
+    import pyarrow as pa
+    from pyspark.serializers import CloudPickleSerializer
+
+    spark, service = mock_connect
+    service.confs = {"spark.sql.repl.eagerEval.enabled": "true",
+                     "spark.sql.repl.eagerEval.maxNumRows": "7",
+                     "spark.sql.repl.eagerEval.truncate": "3"}
+    table = pa.table({"html_string": ["<table/>"]})
+    sink = pa.BufferOutputStream()
+    with pa.ipc.new_stream(sink, table.schema) as writer:
+        writer.write_table(table)
+    # ExecutePlanResponse.arrow_batch=2: ArrowBatch.row_count=1, data=2.
+    service.execute_payload = message_field(
+        2, varint_field(1, 1) + message_field(2, sink.getvalue().to_pybytes()))
+    serializer = CloudPickleSerializer()
+
+    def copies(frame):
+        return [copy.copy(frame), copy.deepcopy(frame), 
serializer.loads(serializer.dumps(frame))]
+
+    df = spark.range(1)
+    assert [repr(copied) for copied in copies(df)] == ["<table/>"] * 3
+    for copied in copies(df):
+        assert copied._repr_html_() == "<table/>"
+    assert repr(df) == "<table/>"
+    assert df._repr_html_() == "<table/>"
+    assert [repr(copied) for copied in copies(df)] == ["DataFrame[id: 
bigint]"] * 3
+    assert [repr(copied) for copied in copies(copy.deepcopy(df))] == 
["DataFrame[id: bigint]"] * 3
+
+
+def 
test_an_unpickled_dataframe_sets_copies_of_the_observations_as_pyspark(mock_connect):
+    # As PySpark's unpickled plan, which has copies of the Observations of the 
pickled one: the
+    # actions of an unpickled DataFrame, or of an unpickled deep copy, set the 
copies and not the
+    # Observations of the DataFrame, before and after its own actions, which 
still set them; and
+    # they raise for a metric that PySpark does not convert, as the copies are 
of their plan.
+    import copy
+
+    from pyspark.errors import PySparkTypeError
+    from pyspark.serializers import CloudPickleSerializer
+    from pyspark.sql import Observation
+    from pyspark.sql import functions as F
+
+    spark, service = mock_connect
+    serializer = CloudPickleSerializer()
+    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)
+    # Literal.long=7, year_month_interval=20.
+    for unpickled in (serializer.loads(serializer.dumps(df)),
+                      serializer.loads(serializer.dumps(copy.deepcopy(df)))):
+        service.execute_payload = batch + observed("o", varint_field(7, 3), 
"c")
+        assert unpickled.count() == 3 and observation.get == {}
+        service.execute_payload = batch + observed("o", varint_field(20, 14), 
"c")
+        with pytest.raises(PySparkTypeError, match="UNSUPPORTED_LITERAL"):
+            unpickled.count()
+    service.execute_payload = batch + observed("o", varint_field(7, 4), "c")
+    assert df.count() == 3 and observation.get == {"c": 4}
+    unpickled = serializer.loads(serializer.dumps(df))
+    service.execute_payload = batch + observed("o", varint_field(7, 5), "c")
+    assert unpickled.count() == 3 and observation.get == {"c": 4}
+
+
 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


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

Reply via email to