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 43158969 [SPARK-61537][CONNECT][PYTHON] Copy the Observations of a
deep copy of a DataFrame in the Python client, as PySpark does
43158969 is described below
commit 43158969aac380a6f5aea5d9161233cc00b35fa9
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 21:38:16 2026 +0900
[SPARK-61537][CONNECT][PYTHON] Copy the Observations of a deep copy of a
DataFrame in the Python client, as PySpark does
### What changes were proposed in this pull request?
`copy.deepcopy` of a DataFrame of the Python client now copies its plan's
Observations, as PySpark's deep copy of its plan does: the actions of the copy
set the copied Observations, which start from the state of the original's at
copy time, and not the original's. `copy.copy` is now a clone that shares the
plan, and so the Observations, as PySpark's copy shares its plan.
- `Observation::detached()` (`crates/spark-connect/src/observation.rs`): a
copy of the name and of the result or error as they are.
- `DataFrame::detached_copy()` (`crates/spark-connect/src/dataframe.rs`):
the same relation and plan ID, with detached copies of its Observations. A deep
copy keeps the plan ID, as PySpark's does, so columns of the original resolve
against it (`copy.deepcopy(df).select(df.id)`).
- `PyDataFrame.__deepcopy__` makes the detached copy, and
`PyDataFrame.__copy__` is a clone, with the `_support_repr_html` that PySpark's
state carries.
- `PlanIds::node_of` (`crates/spark-connect/src/plan.rs`) returns the first
live node that was given a plan ID, not one in hash-map order, as a deep copy
and its original now share an ID.
### Why are the changes needed?
```python
o = Observation("c")
d = spark.range(3).observe(o, F.count(F.lit(1)).alias("c"))
dc = copy.deepcopy(d)
dc.count()
o.get
# before: {'c': 3}
# PySpark 4.3.0 (and after): {}, as the copy's own Observation gets the
metrics
```
PySpark's `DataFrame.__reduce__` returns its plan, which a deep copy copies
with the Observation of its `CollectMetrics`. The drop-in rebuilt the copy from
the relation of the plan and took the original's Observations, which #503
(SPARK-61426) listed as still different from PySpark. This is a follow-up of
SPARK-61426.
### Does this PR introduce _any_ user-facing change?
Yes. After `copy.deepcopy(df)`, an action on the copy no longer sets the
metrics of the original DataFrame's Observation, as in PySpark. `copy.copy`
keeps sharing it.
### How was this patch tested?
- New Rust unit tests: a detached Observation keeps the state and sets only
its own; a detached copy of a DataFrame sets its own Observations; the node of
a plan ID is the first live one that was given it.
- New offline Python tests with the mock server. A deep copy before and
after an action of the original, a shallow copy of the original and of a deep
copy, and a deep copy of a join of two Observations. They fail without the
change.
- A new e2e test against a Spark 4.3.0 server.
- The reference client gives the same results.
- The offline suites (`test_dropin_offline.py`, `test_ml_offline.py`,
`test_arrow_handoff.py`: 3242 passed) under protobuf's default upb backend, the
e2e suites, the Rust library tests and the `raw_relation`/`e2e_dataframe`
suites, the `--no-run` builds (with and without `wasm-udf`), `cargo fmt
--check`, `scripts/audit_no_stubs.sh` and the ruff gates.
### 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 #570 from HyukjinKwon/SPARK-61537-deepcopy-observations.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/dataframe.rs | 21 ++++++
crates/spark-connect/src/dataframe.rs | 122 ++++++++++++++++++++++++++++++++
crates/spark-connect/src/observation.rs | 64 +++++++++++++++++
crates/spark-connect/src/plan.rs | 63 ++++++++++++-----
python/tests/test_dropin_e2e.py | 39 ++++++++++
python/tests/test_dropin_offline.py | 58 +++++++++++++++
6 files changed, 350 insertions(+), 17 deletions(-)
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index 86283fc3..23ff8543 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -695,6 +695,27 @@ impl PyDataFrame {
))
}
+ /// 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.
+ 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))
+ }
+
/// The DataFrame of `relation`, the bytes of a relation of `levels`
levels of `session`, as a
/// pickled DataFrame unpickles.
#[staticmethod]
diff --git a/crates/spark-connect/src/dataframe.rs
b/crates/spark-connect/src/dataframe.rs
index 8d6fc1d0..691cbaeb 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -1308,6 +1308,18 @@ impl DataFrame {
.and_then(|plan_id| session.plan_ids().node_of(plan_id))
.map(|node| node.observations())
.unwrap_or_default();
+ DataFrame::from_sent_relation_with(session, relation, levels,
observations)
+ }
+
+ /// The DataFrame of `relation`, of `levels` levels, which has
`observations`, and keeps the
+ /// plan ID of `relation`.
+ fn from_sent_relation_with(
+ session: SparkSession,
+ relation: proto::Relation,
+ levels: usize,
+ observations: Vec<(String, crate::observation::Observation)>,
+ ) -> DataFrame {
+ let plan_id = relation.common.as_ref().and_then(|common|
common.plan_id);
// The relation is sent as it is, and its clone and drop take the
stack of its levels.
let dataframe = DataFrame::from_raw_relation(session, relation, None,
levels, observations);
if let Some(plan_id) = plan_id {
@@ -1319,6 +1331,27 @@ 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.
+ #[doc(hidden)]
+ pub fn detached_copy(&self) -> 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,
+ ))
+ }
+
/// The levels of the plan of this DataFrame, as a pickled DataFrame
records them for
/// [`DataFrame::from_sent_relation_levels`]. Not a stable API.
#[doc(hidden)]
@@ -5622,6 +5655,95 @@ mod plan_construction_tests {
assert_eq!(error.get_error_class().as_deref(),
Some("SESSION_NOT_SAME"));
}
+ /// 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,
+ /// and those that the actions of the DataFrame observe set its own.
+ #[test]
+ fn a_detached_copy_sets_its_own_observations_as_pyspark_deep_copies() {
+ use crate::observation::Observation;
+ use proto::expression::literal::LiteralType;
+ let spark = session();
+ let literal = |value: i64| proto::expression::Literal {
+ literal_type: Some(LiteralType::Long(value)),
+ ..Default::default()
+ };
+ let count = || {
+ vec![crate::functions::count(crate::column::lit(1))
+ .expression()
+ .clone()]
+ };
+ let observation = Observation::new("c");
+ let df = spark
+ .range(3)
+ .unwrap()
+ .observed_with(&observation, "c".to_string(), count());
+ let value = |obs: &Observation| -> Vec<(String, Option<LiteralType>)> {
+ obs.get()
+ .unwrap()
+ .into_iter()
+ .map(|(key, value)| (key, value.literal_type))
+ .collect()
+ };
+ // Observed by an action of the DataFrame, which sets its own
Observation.
+ let observe = |df: &DataFrame, value: i64| {
+ let mut resp = proto::ExecutePlanResponse {
+ observed_metrics:
vec![proto::execute_plan_response::ObservedMetrics {
+ name: "c".to_string(),
+ values: vec![literal(value)],
+ keys: vec!["c".to_string()],
+ plan_id: spark.plan_ids().id_of(&df.plan),
+ ..Default::default()
+ }],
+ ..Default::default()
+ };
+ let mut info = ExecutionInfo::default();
+ capture_execution(&mut resp, &mut info, &spark,
&df.plan.observations()).unwrap();
+ };
+
+ let copy = df.detached_copy().unwrap();
+ assert_eq!(
+ spark.plan_ids().id_of(©.plan),
+ spark.plan_ids().id_of(&df.plan)
+ );
+ let copied = copy.plan.observations();
+ assert_eq!(copied.len(), 1);
+ assert_eq!(copied[0].0, "c");
+ assert!(!copied[0].1.same(&observation));
+
+ observe(&df, 5);
+ assert_eq!(
+ value(&observation),
+ vec![("c".to_string(), Some(LiteralType::Long(5)))]
+ );
+ // 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();
+ assert_eq!(
+ value(&later.plan.observations()[0].1),
+ vec![("c".to_string(), Some(LiteralType::Long(5)))]
+ );
+
+ observe(©, 3);
+ assert_eq!(
+ value(&copied[0].1),
+ vec![("c".to_string(), Some(LiteralType::Long(3)))]
+ );
+ assert_eq!(
+ value(&observation),
+ vec![("c".to_string(), Some(LiteralType::Long(5)))]
+ );
+
+ // 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));
+ }
+
/// As PySpark's client, which sets the metrics of `observations[name]`,
of the Observations
/// of the executed plan by their names: not those of an Observation of
another plan, of the
/// same name, whatever the plan ID that the server reports.
diff --git a/crates/spark-connect/src/observation.rs
b/crates/spark-connect/src/observation.rs
index 96664bc2..e5ab57d1 100644
--- a/crates/spark-connect/src/observation.rs
+++ b/crates/spark-connect/src/observation.rs
@@ -76,6 +76,19 @@ impl Observation {
Arc::ptr_eq(&self.state, &other.state)
}
+ /// 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 {
+ let state = self.lock();
+ Observation {
+ state: Arc::new(Mutex::new(ObservationState {
+ name: state.name.clone(),
+ result: state.result.clone(),
+ error: state.error.clone(),
+ })),
+ }
+ }
+
/// The name to observe the metrics by, as PySpark's `Observation._on`
before it
/// observes them: `REUSE_OBSERVATION` for an observation used already,
and the name,
/// a random UUID that it keeps for an unnamed observation.
@@ -185,4 +198,55 @@ mod tests {
assert!(obs.get().unwrap_err().message().contains("failed"));
assert!(format!("{obs:?}").contains(&name));
}
+
+ #[test]
+ fn a_detached_observation_keeps_the_state_and_sets_only_its_own() {
+ let obs = Observation::new("d");
+ // A copy of an unused observation is unused too, and is used on its
own.
+ let unused = obs.detached();
+ assert!(!unused.same(&obs));
+ assert_eq!(unused.name().as_deref(), Some("d"));
+ assert!(unused.get().is_err());
+ unused.name_to_observe().unwrap();
+ unused.start();
+ assert!(obs.get().is_err());
+
+ obs.start();
+ obs.update(&["a".to_string()], &[long(1)]);
+ let copy = obs.detached();
+ copy.update(&["a".to_string(), "b".to_string()], &[long(2), long(3)]);
+ obs.update(&["c".to_string()], &[long(4)]);
+ let values = |o: &Observation| -> Vec<(String, Option<LiteralType>)> {
+ o.get()
+ .unwrap()
+ .into_iter()
+ .map(|(name, value)| (name, value.literal_type))
+ .collect()
+ };
+ assert_eq!(
+ values(&obs),
+ vec![
+ ("a".to_string(), Some(LiteralType::Long(1))),
+ ("c".to_string(), Some(LiteralType::Long(4))),
+ ]
+ );
+ assert_eq!(
+ values(©),
+ vec![
+ ("a".to_string(), Some(LiteralType::Long(2))),
+ ("b".to_string(), Some(LiteralType::Long(3))),
+ ]
+ );
+
+ // A failed observation keeps its error in the copy.
+ let failed = Observation::new("f");
+ failed.start();
+ failed.set_error(SparkError::connect_msg("failed"));
+ assert!(failed
+ .detached()
+ .get()
+ .unwrap_err()
+ .message()
+ .contains("failed"));
+ }
}
diff --git a/crates/spark-connect/src/plan.rs b/crates/spark-connect/src/plan.rs
index fe840dbf..1fb6e219 100644
--- a/crates/spark-connect/src/plan.rs
+++ b/crates/spark-connect/src/plan.rs
@@ -634,8 +634,19 @@ pub(crate) struct PlanIds {
/// The state of `PlanIds`, all guarded by its one lock.
#[derive(Debug)]
struct PlanIdNodes {
- ids: HashMap<usize, (Weak<LogicalPlan>, i64)>,
+ /// Each key's node, its plan ID, and the order in which the key got that
ID.
+ ids: HashMap<usize, (Weak<LogicalPlan>, i64, u64)>,
prune_at: usize,
+ /// The order of the next key that gets an ID.
+ next_order: u64,
+}
+
+impl PlanIdNodes {
+ fn insert(&mut self, key: usize, node: &Arc<LogicalPlan>, id: i64) {
+ let order = self.next_order;
+ self.next_order += 1;
+ self.ids.insert(key, (Arc::downgrade(node), id, order));
+ }
}
impl PlanIds {
@@ -646,6 +657,7 @@ impl PlanIds {
nodes: Mutex::new(PlanIdNodes {
ids: HashMap::new(),
prune_at: Self::MIN_PRUNE_AT,
+ next_order: 0,
}),
}
}
@@ -667,15 +679,15 @@ impl PlanIds {
let mut nodes = self.nodes.lock().unwrap_or_else(|e| e.into_inner());
// The entry's `Weak` keeps its allocation from being freed, so a live
node at this
// address is the node the entry was made for.
- if let Some((_, id)) = nodes.ids.get(&key) {
+ if let Some((_, id, _)) = nodes.ids.get(&key) {
return *id;
}
if nodes.ids.len() >= nodes.prune_at {
- nodes.ids.retain(|_, (node, _)| node.strong_count() > 0);
+ nodes.ids.retain(|_, (node, _, _)| node.strong_count() > 0);
nodes.prune_at = (nodes.ids.len() * 2).max(Self::MIN_PRUNE_AT);
}
let id = NEXT_PLAN_ID.fetch_add(1, Ordering::Relaxed);
- nodes.ids.insert(key, (Arc::downgrade(node), id));
+ nodes.insert(key, node, id);
id
}
@@ -684,22 +696,20 @@ impl PlanIds {
pub(crate) fn assign(&self, node: &Arc<LogicalPlan>, id: i64) {
NEXT_PLAN_ID.fetch_max(id.saturating_add(1), Ordering::Relaxed);
let mut nodes = self.nodes.lock().unwrap_or_else(|e| e.into_inner());
- nodes
- .ids
- .insert(Arc::as_ptr(node) as usize, (Arc::downgrade(node), id));
+ nodes.insert(Arc::as_ptr(node) as usize, node, id);
}
- /// A live node of the plan ID `id`, such as that of the DataFrame of a
relation that this
- /// session sent.
+ /// The live node of the plan ID `id` that was first given it, such as the
DataFrame that a
+ /// relation that this session sent is of, when it is alive.
///
/// A plan ID is of one node that this session numbered (`id_of`, or
`root_id_of` for the
/// 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, is a node of its own with the plan
ID of the
- /// DataFrame it was of, which may be alive too. Any one of them is given,
on purpose: they
- /// are all the relation of that plan ID, and each copy took the
Observations of a node of
- /// the ID when it was made (`DataFrame::from_sent_relation`, the one
caller), so they all
- /// have the same ones.
+ /// (`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.
///
/// 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
@@ -709,8 +719,10 @@ impl PlanIds {
nodes
.ids
.values()
- .filter(|(_, node_id)| *node_id == id)
- .find_map(|(node, _)| node.upgrade())
+ .filter(|(_, node_id, _)| *node_id == id)
+ .filter_map(|(node, _, order)| node.upgrade().map(|node| (*order,
node)))
+ .min_by_key(|(order, _)| *order)
+ .map(|(_, node)| node)
}
#[cfg(test)]
@@ -3285,6 +3297,23 @@ mod plan_id_tests {
let later = Arc::new(range(0, 1, 1));
assert_ne!(ids.id_of(&later), id);
}
+
+ /// The node of a plan ID is the first of its nodes that was given the ID
and is alive, so a
+ /// copy that was made later, whose Observations may differ, is taken only
once that is gone.
+ #[test]
+ fn the_node_of_a_plan_id_is_the_first_given_one_that_is_alive() {
+ let ids = PlanIds::new();
+ let numbered = Arc::new(range(0, 3, 1));
+ let id = ids.id_of(&numbered);
+ let (copy, other_copy) = (Arc::new(range(0, 3, 1)), Arc::new(range(0,
3, 1)));
+ ids.assign(©, id);
+ ids.assign(&other_copy, id);
+ assert!(one_of(ids.node_of(id), &[&numbered]));
+ std::mem::drop(numbered);
+ assert!(one_of(ids.node_of(id), &[©]));
+ std::mem::drop(copy);
+ assert!(one_of(ids.node_of(id), &[&other_copy]));
+ }
}
#[cfg(test)]
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 80257024..f67af307 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -3906,6 +3906,45 @@ def
test_observations_receive_the_observed_metrics_as_pyspark(session):
assert error.value.getCondition() == "UNSUPPORTED_OPERATION"
+def
test_a_deep_copy_of_a_dataframe_sets_its_own_observations_as_pyspark(session):
+ # As PySpark's deep copy of a DataFrame, which copies the Observations of
its plan: an
+ # action of the copy sets the copies and not the Observations of the
DataFrame, which keep
+ # their metrics as they were when copied; copy.copy shares them, and so
does a DataFrame
+ # over a shared one.
+ import copy
+ import gc
+
+ from pyspark.sql import Observation
+
+ observation = Observation("deep")
+ df = session.range(3).observe(observation, F.count(F.lit(1)).alias("c"))
+ copied = copy.deepcopy(df)
+ del df
+ gc.collect()
+ assert copied.count() == 3
+ assert observation.get == {}
+
+ shallow = Observation("shallow")
+ df = session.range(4).observe(shallow, F.count(F.lit(1)).alias("c"))
+ assert copy.copy(df).count() == 4 and shallow.get == {"c": 4}
+
+ collected = Observation("collected")
+ df = session.range(2).observe(collected, F.count(F.lit(1)).alias("c"))
+ assert df.collect() == [Row(id=0), Row(id=1)] and collected.get == {"c": 2}
+ late = copy.deepcopy(df)
+ assert late.count() == 2 and collected.get == {"c": 2}
+
+ first, second = Observation("join_first"), Observation("join_second")
+ left = session.range(3).observe(first, F.count(F.lit(1)).alias("c"))
+ right = session.range(5).observe(second, F.count(F.lit(1)).alias("c"))
+ joined = left.join(right, "id")
+ joined_copy = copy.deepcopy(joined)
+ assert joined_copy.count() == 3
+ assert first.get == {} and second.get == {}
+ assert joined.count() == 3
+ assert first.get == {"c": 3} and second.get == {"c": 5}
+
+
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 2ac7e3d4..7cfe1d97 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -10165,6 +10165,64 @@ def
test_only_the_observations_of_the_plan_of_an_action_receive_its_metrics_as_p
assert observation.get == {"c": 4}
+def
test_a_deep_copy_sets_its_own_observations_and_a_shallow_one_shares_them_as_pyspark(
+ mock_connect):
+ # As PySpark's DataFrame.__reduce__, whose deep copy copies the plan, and
so the Observations
+ # of its CollectMetrics: an action of a deep copy sets the copied
Observations, and not those
+ # of the DataFrame, which keep the metrics that they had when it was
copied; copy.copy shares
+ # them, as do the DataFrames over the copied one.
+ import copy
+
+ from pyspark.sql import Observation
+ from pyspark.sql import functions as F
+
+ spark, service = mock_connect
+ 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)
+ # Before the action of the copy: the original keeps its metrics, which are
none.
+ deep = copy.deepcopy(df)
+ service.execute_payload = batch + observed("o", varint_field(7, 3), "c")
+ assert deep.count() == 3 and observation.get == {}
+ # A shallow copy of the deep copy shares the deep copy's Observations, not
the original's.
+ service.execute_payload = batch + observed("o", varint_field(7, 7), "c")
+ assert copy.copy(deep).count() == 3 and observation.get == {}
+ service.execute_payload = batch + observed("o", varint_field(7, 4), "c")
+ assert copy.copy(df).count() == 3 and observation.get == {"c": 4}
+ # After the action of the original: a deep copy has its metrics, and then
its own.
+ service.execute_payload = batch + observed("o", varint_field(7, 5), "c")
+ assert df.count() == 3 and observation.get == {"c": 5}
+ later = copy.deepcopy(df)
+ assert observation.get == {"c": 5}
+ service.execute_payload = batch + observed("o", varint_field(7, 6), "c")
+ assert later.count() == 3 and observation.get == {"c": 5}
+
+
+def
test_a_deep_copy_of_a_join_sets_the_observations_of_its_copy_as_pyspark(mock_connect):
+ # As PySpark's deep copy of a plan, which copies both Observations of a
join: an action of
+ # the copy sets the copies, and an action of the joined DataFrame sets the
two Observations.
+ import copy
+
+ from pyspark.sql import Observation
+ from pyspark.sql import functions as F
+
+ spark, service = mock_connect
+ first, second = Observation("first"), Observation("second")
+ left = spark.range(3).observe(first, F.count(F.lit(1)).alias("c"))
+ right = spark.range(5).observe(second, F.count(F.lit(1)).alias("c"))
+ joined = left.join(right, "id")
+ # The plan IDs of each side, which the join shares with its request.
+ batch, observed = _count_batch_and_observed_metrics(service, left)
+ _, observed_right = _count_batch_and_observed_metrics(service, right)
+ copied = copy.deepcopy(joined)
+ service.execute_payload = (batch + observed("first", varint_field(7, 3),
"c")
+ + observed_right("second", varint_field(7, 5),
"c"))
+ assert copied.count() == 3
+ assert first.get == {} and second.get == {}
+ assert joined.count() == 3
+ assert first.get == {"c": 3} and second.get == {"c": 5}
+
+
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]