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 067202e7 [SPARK-61426][CONNECT][PYTHON] Check the observed metrics of
only the Observations of the executed plan, keep the metrics of earlier
actions, and raise for nested unconvertible metrics, in the Python client as
PySpark does
067202e7 is described below
commit 067202e78778fca059eb791b01a119ae26975797
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 12:19:29 2026 +0900
[SPARK-61426][CONNECT][PYTHON] Check the observed metrics of only the
Observations of the executed plan, keep the metrics of earlier actions, and
raise for nested unconvertible metrics, in the Python client as PySpark does
### What changes were proposed in this pull request?
[SPARK-61426](https://issues.apache.org/jira/browse/SPARK-61426): a
follow-up to SPARK-61363 (#470). It fixes three things about how the Python
client handles Observations.
**1. An execution sets and converts only the Observations of its own plan,
and none for commands.**
- **Core: the Observations of a plan**
(`crates/spark-connect/src/plan.rs`). The new `LogicalPlan::observations`
collects them as PySpark's `LogicalPlan.observations` properties do
(`pyspark/sql/connect/plan.py`):
- It follows the child of each plan, and both sides of joins (`Join`,
`LateralJoin`, `AsOfJoin`, `NearestByJoin`), set operations and `Zip`.
- It does not follow plans that only an expression refers to
(subqueries), the DataFrames of `SparkSession.sql`, the other input of
`CoGroupMap`, or the initial state of `GroupMap`.
- When two Observations share a name, it keeps the outer one, and the one
on the right side, as PySpark's dict merges do.
- It walks the plan without recursion, and visits a shared node once.
- A relation of `pyspark.ml` (`DataFrame::from_relation`, the `Raw` plan)
keeps the Observations of the DataFrame whose placeholder it holds as its
child: the transform input, the model summary dataset, or the `WithRelations`
root. These are the children of PySpark's `TransformerRelation`,
`AttributeRelation` and `WithRelations`.
- A DataFrame of a relation that the session sent (`from_sent_relation`:
`copy.copy`, `copy.deepcopy` and unpickling of a DataFrame) gets the
Observations of the DataFrame it came from, while that DataFrame is alive.
`PlanIds::node_of` is kept for this.
- **Core: which executions pass Observations.**
- These pass the Observations of their plan: `collect`, the Arrow
collects, local iterators, the writes (`DataFrameWriter`, `DataFrameWriterV2`),
temp views, and the source of `MERGE`.
- These pass none, as PySpark's `execute_command` calls do:
`checkpoint`/`localCheckpoint`, SQL statements, and the other commands
(including those of `pyspark.ml`).
- **Core: how metrics are set** (`set_observations`). The metrics now set
`observations[name]` by name, in the server's order, as PySpark's
`_execute_and_fetch_as_iterator` does. Before, any Observation of the session
whose relation had the plan ID that the server reported was set.
- **Core: a new session check.**
`SparkSession::set_observation_metrics_check` sets a check that runs before the
metrics of each Observation are set:
- An error of the check fails the execution. The error carries the
operation ID and goes through the done call of the progress handlers
(`ExecutionStream::fail`, as `Progress.__exit__`).
- The rejected Observation, and those whose metrics come after it, keep
their earlier metrics.
- **Python client** (`crates/pyspark-rs/src/observation.rs`).
- Each session registers a check that raises `PySparkTypeError`
`UNSUPPORTED_LITERAL` for the first literal that `LiteralExpression._to_value`
does not convert, with that literal's text.
- This replaces `ObservedMetricsCheck` from #470, which compared the
session's live Observations by name against the session's last execution. It
also removes the `rejected` flag of `PyObservation` and the per-session
registry of Observations.
- `interruptible` and `toLocalIterator` no longer run that check.
**2. `executionInfo.flows` and `PlanObservedMetrics.to_dict` raise for an
unconvertible literal nested in a metric**
(`crates/pyspark-rs/src/dataframe.rs`, `execution_metrics`). If a metric holds
such a literal inside an array, struct or map, the metric becomes the top-level
`_UnsupportedLiteral` marker of that inner literal. So `pairs` raises
`UNSUPPORTED_LITERAL` naming it, as PySpark does.
**3. No per-session registry is left.** The registry of Observations by
session ID is removed, so a stopped or abandoned session leaves nothing behind.
**4.** This change needed SPARK-61469 (#522, merged), which drives the
future of a blocking call from the heap: with this change on top of #494,
`deep_request_stack_tests` overflowed their 512 KiB thread, as other open
changes did. That fix is no longer part of this PR.
### Why are the changes needed?
**What PySpark does** (4.3.0):
- A DataFrame action passes `self._plan.observations` (`dataframe.py`
`_to_table`, `_to_pandas`, `toLocalIterator`). Writes, temp views and `MERGE`
also pass the observations of their plan.
- `checkpoint`/`localCheckpoint` (`dataframe.py:2400-2420`) and
`SparkSession.sql` (`session.py:835`) call `execute_command` without
observations. The `SQL` plan has no child, so the DataFrame it returns has none
either.
- `_execute_and_fetch_as_iterator` (`client/core.py:1772-1801`) updates
`observations[x.name]._result` with a dict comprehension of
`LiteralExpression._to_value`. The comprehension raises before the update runs,
so the Observation keeps its earlier metrics, and later metrics are not
processed. `_handle_error(error, req.operation_id)` then stamps `_operation_id`
on the exception (`core.py:2342-2344`).
- `PlanObservedMetrics.pairs` (`core.py:664-669`) converts each metric with
`_to_value`, which raises `UNSUPPORTED_LITERAL` for a nested element too
(`expressions.py:433-466`).
**What the client did before.** It set the Observations by the plan ID that
the server reported, and checked the session's Observations by name. So it
raised where PySpark does not, set Observations that PySpark leaves alone, and
dropped earlier metrics.
**Side-by-side probe.** `/tmp/r6/impl-observe/probe_obs_plan.py`, against
Spark 4.3.0 on `sc://localhost:15014`, gives this. "ym" is a `max(INTERVAL '1'
YEAR)` metric and "count" is a `count(1)` metric.
| case | official PySpark | master | this PR |
|---|---|---|---|
| `df.localCheckpoint().count()`, ym metric | `3` | `UNSUPPORTED_LITERAL` |
`3` |
| `get` after `localCheckpoint()`, count metric | `{}` | `{'c': 3}` | `{}` |
| `get` after `localCheckpoint(eager=False)` | `{}` | `{'c': 0}` | `{}` |
| `spark.sql("SELECT * FROM {d}", d=df).count()`, ym | `3` |
`UNSUPPORTED_LITERAL` | `3` |
| `scalar()` / `exists()` subquery of the observed df, ym | rows |
`UNSUPPORTED_LITERAL` | rows |
| `get` after a failing `count()` that followed a successful one | `{'ym':
None, 'c': 0}` | `{}` | `{'ym': None, 'c': 0}` |
| two Observations, the failing one first: both `get`s | `({'c': 0}, {'ym':
None})` | `({}, {})` | `({'c': 0}, {'ym': None})` |
| `_operation_id` on the action's `UNSUPPORTED_LITERAL` | set | missing |
set |
| `observe("n", collect_list(ym))`, then `executionInfo.flows` |
`UNSUPPORTED_LITERAL 'year_month_interval: 12\n'` | a list of
`_UnsupportedLiteral` markers | `UNSUPPORTED_LITERAL 'year_month_interval:
12\n'` |
| the same for `first(struct(ym))` and `first(create_map(..., ym))` |
raises | `Row`/dict of markers | raises |
The output of this PR is identical to official on all 64 lines of the
probe. This includes joins, unions, lateral joins, temp views, writes, and the
server's `DUPLICATED_METRICS_NAME` error for two Observations of one name in
one plan.
**Before, #470 also had these problems:**
- The registry of Observations was pruned only by actions of the same
session.
- Two actions that one session ran at once from two threads could check
each other's execution. The check now belongs to each execution.
### Does this PR introduce _any_ user-facing change?
Yes, to match PySpark 4.3.0.
**Python client:**
- `checkpoint`, `localCheckpoint`, a SQL statement over an observed
DataFrame, and subqueries of one neither raise `UNSUPPORTED_LITERAL` nor set
its Observation.
- After an action fails with `UNSUPPORTED_LITERAL`, `Observation.get` keeps
the metrics of the earlier actions. This holds for that Observation and for
those whose metrics came after it.
- The exception now has the execution's `_operation_id`.
- `executionInfo.flows` raises for an unconvertible literal nested in a
metric.
**Rust API:**
- An `Observation` is set only by the executions of a plan that holds it,
matched by name. A checkpoint or a SQL statement does not set it.
- `SparkSession::set_observation_metrics_check` is new.
**Still different from PySpark:**
- `copy.deepcopy` of an observed DataFrame raises as PySpark does, but sets
the original Observation. PySpark's deep copy holds a copy of the Observation,
so its original stays unset. `copy.copy` matches PySpark, because PySpark's
copy shares the plan. Master behaves the same here.
- A DataFrame unpickled in another process has no Observations. PySpark
pickles them inside the plan.
### How was this patch tested?
**New and changed tests:**
- Rust lib tests, in `crates/spark-connect/src/dataframe.rs`
(`plan_construction_tests`):
-
`observed_metrics_set_the_observations_of_the_executed_plan_by_name_as_pyspark`
replaces `observed_metrics_set_the_observations_of_their_relations`.
- New, right after it:
`the_observations_of_a_plan_are_those_that_pyspark_collects`. It covers the
outer and the right Observation of a name, joins and unions, subqueries, SQL
references, the `pyspark.ml` transform placeholder, and sent relations.
- New, right after it:
`rejected_metrics_fail_the_execution_and_keep_the_earlier_metrics_as_pyspark`.
- Python offline tests, in `python/tests/test_dropin_offline.py`, right
after
`test_metrics_that_pyspark_cannot_convert_fail_the_action_of_their_observation_as_pyspark`
(with a helper `_count_batch_and_observed_metrics`):
-
`test_only_the_observations_of_the_plan_of_an_action_receive_its_metrics_as_pyspark`.
It covers `localCheckpoint`, `checkpoint`, `sql(d=df)`, `scalar()`,
`exists()`, `copy.copy` and `copy.deepcopy`.
-
`test_a_failing_action_keeps_the_metrics_of_the_earlier_actions_as_pyspark`
-
`test_flows_raise_for_a_metric_that_holds_one_pyspark_cannot_convert_as_pyspark`
- Python live test, in `python/tests/test_dropin_e2e.py`, right after
`test_an_observation_of_a_year_month_interval_fails_the_action_as_pyspark`:
-
`test_only_the_observations_of_the_plan_of_an_action_convert_its_metrics_as_pyspark`.
A standalone copy of it passes with official PySpark 4.3.0 on 15014.
**The new tests fail without the fix.** The source change was saved with
`git diff`, reverted with `patch -R`, rebuilt, and the tests were run:
- `test_only_the_observations...` fails with `assert {'c': 3} == {}`.
- `test_a_failing_action...` fails with `assert ({} == {'c': 3} ...)`.
- `test_flows_raise...` fails with `DID NOT RAISE`.
- The live test fails with `UNSUPPORTED_LITERAL` from
`df.localCheckpoint()`.
The patch was then re-applied and the extension rebuilt.
The Rust tests call the new `LogicalPlan::observations`,
`set_observation_metrics_check` and the new `capture_execution` signature, so
they do not build on master. Instead, a temporary mutation of the source was
checked:
- Ignoring the check's error makes `rejected_metrics...` fail.
- Following `WithRelations` references, and dropping the observations of a
`Raw` plan, makes `the_observations_of_a_plan...` fail.
**Probes, official PySpark 4.3.0 against this PR on 15014.** All give
identical output:
- `probe_obs_plan.py` and `probe_obs_ml.py`. The second covers a vendored
`VectorAssembler` transform of an observed DataFrame, which sets and raises as
PySpark does.
- The reviewers' probes `probe_obs_actions.py`, `probe_obs_view.py`,
`probe_obs2.py`, `probe_obs_threads.py` and `p470e.py`.
For `copy.copy` and `copy.deepcopy` (`probe_obs_copy2.py`), the output
equals official except for the `deepcopy` setting of the original noted above.
**Commands run, all green.** These were run on the tree rebased onto
2f83537f (#491, #494):
- `cargo fmt --all --check`
- `cargo test -p apache-spark-connect --release --no-run`, and the same
with `--features wasm-udf`: no warnings.
- `cargo test -p apache-spark-connect --release --lib`: 606 passed. This
includes `deep_request_stack_tests` (with SPARK-61469 on master).
- `cargo test -p apache-spark-connect-core --release --lib -- runtime::`:
17 passed.
- `cargo clippy -p apache-spark-connect-core --release --all-targets`: no
diagnostics.
- Python offline:
- `tests/test_dropin_offline.py` with the same `-k` filter as the
pre-rebase run below: 159 passed.
- `-k "small_stack or deep or recursion or depth"`: 11 passed. This
includes #494's 512 KiB-thread tests of a 256-level plan and a 200-addition
expression.
These were run before the rebase:
- `cargo clippy -p apache-spark-connect --release --all-targets` and `cargo
clippy -p pyspark-rs --release --all-targets`: no diagnostics on the changed
lines.
- `cargo test -p apache-spark-connect --release --lib -- dataframe:: plan::
observation:: progress:: profiler:: readwriter:: merge:: session::`: 198 passed.
- With `SPARK_REMOTE=sc://localhost:15014`:
- `--test raw_relation`: 10 passed.
- `--test e2e_dataframe`: 14 passed.
- `--test e2e_ops_breadth`: 6 passed.
- `--test execute_plan_hook`: 1 passed.
- `--test e2e_new_methods -- checkpoints_and_input_files_local`: 1 passed.
- Python offline:
- `tests/test_dropin_offline.py -k "observ or Observation or
execution_info or executionInfo or checkpoint or interrupt or local_iterator or
flows or metrics or progress or profile or accumulator or unsupported or
literal or sigint or signal or copy or pickle"`: 152 passed.
- `tests/test_ml_offline.py`: 104 passed.
- Python live, on 15014:
- `tests/test_dropin_e2e.py` with the same kind of filter: 15 passed.
This includes the observation, `executionInfo`, checkpoint, local iterator and
SIGINT tests.
- `tests/test_ml_e2e.py -k "vector_assembler or feature_transformers or
transformed_dataframes_keep or summary_keeps_their_transform or
scalers_fit_and_transform"`: 5 passed.
### 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 #503 from HyukjinKwon/SPARK-61426-observations-of-the-plan.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/dataframe.rs | 48 ++--
crates/pyspark-rs/src/interrupt.rs | 10 +-
crates/pyspark-rs/src/observation.rs | 159 ++---------
crates/pyspark-rs/src/session.rs | 2 +
crates/spark-connect/src/dataframe.rs | 388 +++++++++++++++++++++-----
crates/spark-connect/src/merge.rs | 9 +-
crates/spark-connect/src/plan.rs | 116 +++++++-
crates/spark-connect/src/readwriter.rs | 18 +-
crates/spark-connect/src/session.rs | 51 +++-
python/pyspark/sql/connect/client/__init__.py | 3 +-
python/tests/test_dropin_e2e.py | 43 +++
python/tests/test_dropin_offline.py | 136 +++++++++
12 files changed, 740 insertions(+), 243 deletions(-)
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index b8dd7b85..0760f3fb 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -4554,9 +4554,6 @@ pub struct PyLocalRowIterator {
fields: Option<(std::sync::Arc<[String]>, Py<PyList>)>,
/// Nested names belong to schema paths and stay shared across iterator
batches.
nested_fields: NestedFieldNames,
- /// The check of the metrics of Observations of the execution, made once
at its end rather
- /// than by each row, as the metrics come with the end of the result.
- observed: Option<crate::observation::ObservedMetricsCheck>,
}
impl PyLocalRowIterator {
@@ -4569,7 +4566,6 @@ impl PyLocalRowIterator {
binary_as_bytes: None,
fields: None,
nested_fields: NestedFieldNames::default(),
- observed: None,
}
}
@@ -4594,14 +4590,9 @@ impl PyLocalRowIterator {
value
}
};
- let session = self.dataframe.spark_session();
- if self.iterator.is_none() {
- self.observed =
crate::observation::ObservedMetricsCheck::before(py, &session);
- }
- let next = crate::interrupt::interruptible_outcome(py, &session, || {
+ let next = interruptible(py, &self.dataframe.spark_session(), || {
Ok::<_,
Box<spark_connect_core::error::SparkError>>(self.next_row())
- })?
- .to_pyerr()?;
+ })?;
if self.converters.is_none() {
if let Some(schema) =
self.iterator.as_ref().and_then(LocalRowIterator::schema) {
// The result is known once its first message arrives,
possibly with no rows.
@@ -4644,12 +4635,7 @@ impl PyLocalRowIterator {
.map(Some)
}
Some(Err(error)) =>
Err(crate::errors::spark_error_to_py_exception(error)),
- None => {
- if let Some(observed) = self.observed.take() {
- observed.after(py, &session)?;
- }
- Ok(None)
- }
+ None => Ok(None),
}
}
}
@@ -4736,10 +4722,16 @@ fn execution_metrics<'py>(
.getattr("PlanObservedMetrics")?;
let observed = pyo3::types::PyList::empty(py);
for o in &info.observed_metrics {
+ // A metric that holds a literal of a kind that PySpark does not
convert, itself or as an
+ // element, is the marker of that literal, for which `pairs` raises as
PySpark's raises
+ // when it converts the metric.
let values = o
.values
.iter()
- .map(|l| literal_to_py(py, l, None))
+ .map(|l| match unsupported_literal(l) {
+ Some(literal) => unsupported_literal_marker(py, literal),
+ None => literal_to_py(py, l, None),
+ })
.collect::<PyResult<Vec<_>>>()?;
observed.append(observed_cls.call1((&o.name, values,
o.keys.clone()))?)?;
}
@@ -4887,14 +4879,24 @@ pub(crate) fn literal_to_py(
.call1((names, values))?
.unbind()
}
- Some(_) => py
- .import("pyspark.sql.connect.client")?
- .getattr("_UnsupportedLiteral")?
- .call1((literal_text(py, literal),))?
- .unbind(),
+ Some(_) => unsupported_literal_marker(py, literal)?,
})
}
+/// The `_UnsupportedLiteral` marker of `literal`, a literal of a kind that
`literal_to_py` does
+/// not convert, of its text, for which `PlanObservedMetrics.pairs` raises
PySpark's
+/// `UNSUPPORTED_LITERAL`.
+fn unsupported_literal_marker(
+ py: Python<'_>,
+ literal: &spark_connect_proto::expression::Literal,
+) -> PyResult<Py<PyAny>> {
+ Ok(py
+ .import("pyspark.sql.connect.client")?
+ .getattr("_UnsupportedLiteral")?
+ .call1((literal_text(py, literal),))?
+ .unbind())
+}
+
/// The first literal of `literal`, itself or an element, whose kind
`literal_to_py` does not
/// convert, in the order in which PySpark's `LiteralExpression._to_value`
converts them: the
/// literal that PySpark's `UNSUPPORTED_LITERAL` names.
diff --git a/crates/pyspark-rs/src/interrupt.rs
b/crates/pyspark-rs/src/interrupt.rs
index d58da085..cd0964d4 100644
--- a/crates/pyspark-rs/src/interrupt.rs
+++ b/crates/pyspark-rs/src/interrupt.rs
@@ -90,20 +90,12 @@ impl SignalWatch {
/// during an execution, and all of them when no execution is in flight, or
after a second
/// signal. A streaming execution is still read after the first one, until the
server cancels it.
/// A wait of `block_on_abortable` (the release of `stop()`) ends at once as
well.
-///
-/// An execution that `f` ran then raises for the metrics of an Observation
that PySpark does
-/// not convert, as PySpark's does (`ObservedMetricsCheck`).
pub(crate) fn interruptible<T: Send, E: Send + Into<Box<SparkError>>>(
py: Python<'_>,
session: &SparkSession,
f: impl FnOnce() -> Result<T, E> + Send,
) -> PyResult<T> {
- let observed = crate::observation::ObservedMetricsCheck::before(py,
session);
- let output = interruptible_outcome(py, session, f)?.to_pyerr()?;
- if let Some(observed) = observed {
- observed.after(py, session)?;
- }
- Ok(output)
+ interruptible_outcome(py, session, f)?.to_pyerr()
}
/// As [`interruptible`], but a failure of `f` is the inner result, which the
caller handles, as
diff --git a/crates/pyspark-rs/src/observation.rs
b/crates/pyspark-rs/src/observation.rs
index a4a7c5ff..c1cb5c12 100644
--- a/crates/pyspark-rs/src/observation.rs
+++ b/crates/pyspark-rs/src/observation.rs
@@ -1,15 +1,12 @@
//! PyO3 wrapper for `spark_connect::observation::Observation`
(`pyspark.sql.Observation`).
-use std::collections::HashMap;
-use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::{Mutex, OnceLock};
-
use pyo3::prelude::*;
-use pyo3::types::{PyDict, PyString, PyWeakrefMethods, PyWeakrefReference};
+use pyo3::types::{PyDict, PyString};
use spark_connect::dataframe::DataFrame;
use spark_connect::expression::Expression;
use spark_connect::observation::Observation;
use spark_connect::SparkSession;
+use spark_connect_core::error::{SparkError, SparkErrorKind};
use crate::column::{raise_pyspark, PyColumn};
use crate::dataframe::PyDataFrame;
@@ -24,9 +21,6 @@ use crate::errors::ResultExt;
)]
pub struct PyObservation {
pub(crate) inner: Observation,
- /// Whether the last execution that observed the metrics failed before
PySpark's client would
- /// set them, as it raises at the first metric that it does not convert
(`ObservedMetricsCheck`).
- rejected: AtomicBool,
}
#[pymethods]
@@ -64,10 +58,7 @@ impl PyObservation {
Observation::new(&name)
}
};
- Ok(PyObservation {
- inner,
- rejected: AtomicBool::new(false),
- })
+ Ok(PyObservation { inner })
}
/// The name of the observation, as PySpark's `_name`: None for an unnamed
observation
@@ -79,22 +70,12 @@ impl PyObservation {
/// The observed metrics, as PySpark's `Observation.get`: a dict of the
metrics that the
/// actions run so far observed, by their names, and empty before an
action runs. The metrics
- /// of an execution that failed before PySpark's client would set them
(`ObservedMetricsCheck`),
- /// and the metrics of a kind that it does not convert, are not given:
PySpark's are those of
- /// the executions before, here none of them.
+ /// 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.
#[getter]
fn get<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
- let result = PyDict::new(py);
- if self.rejected.load(Ordering::SeqCst) {
- return Ok(result);
- }
let metrics = self.inner.get().to_pyerr()?;
- if metrics
- .iter()
- .any(|(_, value)|
crate::dataframe::unsupported_literal(value).is_some())
- {
- return Ok(result);
- }
+ let result = PyDict::new(py);
for (name, value) in metrics {
result.set_item(name, crate::dataframe::literal_to_py(py, &value,
None)?)?;
}
@@ -117,17 +98,9 @@ impl PyObservation {
}
}
-/// The Observations that the DataFrames of each session observe metrics with,
by session ID, and
-/// their names: held weakly, by their Python objects, so that this keeps none
of them alive.
-type Observations = HashMap<String, Vec<(String, Py<PyWeakrefReference>)>>;
-
-fn observations() -> &'static Mutex<Observations> {
- static OBSERVATIONS: OnceLock<Mutex<Observations>> = OnceLock::new();
- OBSERVATIONS.get_or_init(Default::default)
-}
-
/// `df` observing the metrics `exprs` with `observation`, as PySpark's
`Observation._on`, which
-/// `DataFrame.observe` calls. The observation is kept for the actions of the
session.
+/// `DataFrame.observe` calls. The actions of the DataFrames of it set the
metrics, as those of
+/// an Observation of their plans.
pub(crate) fn observe(
py: Python<'_>,
df: &DataFrame,
@@ -138,104 +111,32 @@ pub(crate) fn observe(
let observed = crate::interrupt::interruptible(py, &df.spark_session(), ||
{
df.observe_with(&inner, exprs)
})?;
- if let Some(name) = inner.name() {
- let weak = PyWeakrefReference::new(observation)?.unbind();
- let mut sessions = observations().lock().unwrap_or_else(|e|
e.into_inner());
- let kept = sessions
- .entry(df.spark_session().session_id().to_string())
- .or_default();
- kept.push((name, weak));
- }
Ok(PyDataFrame::new(observed))
}
-/// The check of an action, after it ran, that PySpark's client makes when it
converts the metrics
-/// of the Observations of the plan as the execution sends them:
`UNSUPPORTED_LITERAL`, raised from
-/// the action, for the first metric of a kind that PySpark's
`LiteralExpression._to_value` does
-/// not convert (a year-month interval, a nanosecond timestamp). PySpark's
client then sets neither
-/// those metrics nor the ones that come after them. The metrics are those of
the session's last
-/// execution, if it is not the one before the action, whose names are those
of the session's
-/// Observations; the other observed metrics are not converted, as in PySpark.
-pub(crate) struct ObservedMetricsCheck {
- before: Option<String>,
-}
-
-impl ObservedMetricsCheck {
- /// The check of an action of `session`, which has one only if it has
Observations.
- pub(crate) fn before(py: Python<'_>, session: &SparkSession) ->
Option<Self> {
- live_observations(py, session).as_ref()?;
- Some(ObservedMetricsCheck {
- before: session
- .last_execution_info()
- .and_then(|info| info.operation_id),
- })
- }
-
- pub(crate) fn after(self, py: Python<'_>, session: &SparkSession) ->
PyResult<()> {
- let Some(info) = session.last_execution_info() else {
- return Ok(());
- };
- if info.operation_id.is_none() || info.operation_id == self.before {
- return Ok(());
- }
- let Some(kept) = live_observations(py, session) else {
+/// Have the executions of `session` convert the metrics of the Observations
of their plans as
+/// PySpark's client converts them when it sets them
(`LiteralExpression._to_value`): the first
+/// metric of a kind that it does not convert (a year-month interval, a
nanosecond timestamp),
+/// itself or an element of it, raises `UNSUPPORTED_LITERAL` from the action,
of the text of its
+/// literal. The core then sets neither the metrics of that Observation nor
those that come after
+/// them in the server's order, which keep the metrics of the executions
before, as PySpark's.
+/// The metrics of a DataFrame observed by a name are not converted by the
action, as PySpark's;
+/// `executionInfo` raises for them when they are read.
+#[allow(clippy::result_large_err)] // The check of the core returns its
Result, of a SparkError.
+pub(crate) fn check_observed_metrics(session: &SparkSession) {
+ session.set_observation_metrics_check(|metrics| {
+ let Some(literal) = metrics
+ .values
+ .iter()
+ .find_map(crate::dataframe::unsupported_literal)
+ else {
return Ok(());
};
- let mut error = None;
- for metrics in &info.observed_metrics {
- let observed: Vec<_> = kept
- .iter()
- .filter(|(name, _)| *name == metrics.name)
- .collect();
- if observed.is_empty() {
- continue;
- }
- // The metrics of an error of the server are not converted.
- if error.is_none() && metrics.root_error_idx.is_none() {
- error = metrics
- .values
- .iter()
- .find_map(crate::dataframe::unsupported_literal)
- .map(|literal| crate::dataframe::literal_text(py,
literal));
- }
- for (_, observation) in observed {
- observation
- .borrow()
- .rejected
- .store(error.is_some(), Ordering::SeqCst);
- }
- }
- match error {
- Some(literal) => Err(raise_pyspark(
- py,
- "PySparkTypeError",
- "UNSUPPORTED_LITERAL",
- &[("literal", &literal)],
- )),
- None => Ok(()),
- }
- }
-}
-
-/// The Observations of `session` that are alive, by their names, if any; the
others are forgotten.
-fn live_observations<'py>(
- py: Python<'py>,
- session: &SparkSession,
-) -> Option<Vec<(String, Bound<'py, PyObservation>)>> {
- let mut sessions = observations().lock().unwrap_or_else(|e|
e.into_inner());
- let kept = sessions.get_mut(session.session_id())?;
- let mut live = Vec::new();
- kept.retain(|(name, weak)| match weak.bind(py).upgrade() {
- Some(observation) => {
- if let Ok(observation) = observation.cast_into() {
- live.push((name.clone(), observation));
- }
- true
- }
- None => false,
+ let text = Python::attach(|py| crate::dataframe::literal_text(py,
literal));
+ Err(SparkError::classed(
+ SparkErrorKind::TypeError,
+ "UNSUPPORTED_LITERAL",
+ &[("literal", &text)],
+ ))
});
- if kept.is_empty() {
- sessions.remove(session.session_id());
- }
- (!live.is_empty()).then_some(live)
}
diff --git a/crates/pyspark-rs/src/session.rs b/crates/pyspark-rs/src/session.rs
index dd8fa238..7c1f15ca 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -879,6 +879,8 @@ impl PySparkSession {
error.write_unraisable(py, None);
}
});
+ // The metrics of the Observations of its executions, which PySpark's
client converts.
+ crate::observation::check_observed_metrics(&session);
PySparkSession {
session,
streams: std::sync::OnceLock::new(),
diff --git a/crates/spark-connect/src/dataframe.rs
b/crates/spark-connect/src/dataframe.rs
index fb52a150..8672bcb0 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -139,6 +139,8 @@ enum RowSource {
stream: Box<ExecutionStream>,
execution_info: ExecutionInfo,
execution_recorded: bool,
+ /// The Observations of the plan, which the observed metrics set.
+ observations: Vec<(String, crate::observation::Observation)>,
},
/// Batches are fetched by a background task that keeps one batch buffered
/// ahead, so the next server fetch overlaps with the caller consuming the
@@ -154,17 +156,19 @@ enum RowSource {
}
impl LocalRowIterator {
- /// Create a new `LocalRowIterator` over an already-issued ExecutePlan
stream.
+ /// Create a new `LocalRowIterator` over an already-issued ExecutePlan
stream, of a plan of
+ /// the Observations `observations`.
pub(crate) fn new(
session: SparkSession,
stream: ExecutionStream,
prefetch_partitions: bool,
+ observations: Vec<(String, crate::observation::Observation)>,
) -> Self {
let schema = SchemaSlot::default();
let source = if prefetch_partitions {
{
let wait = stream.inflight_handle();
- let (rx, task) = spawn_prefetch(session, stream,
Arc::clone(&schema));
+ let (rx, task) = spawn_prefetch(session, stream,
Arc::clone(&schema), observations);
RowSource::Prefetch {
rx,
task: Some(task),
@@ -177,6 +181,7 @@ impl LocalRowIterator {
stream: Box::new(stream),
execution_info: ExecutionInfo::default(),
execution_recorded: false,
+ observations,
}
};
LocalRowIterator {
@@ -208,10 +213,19 @@ impl LocalRowIterator {
stream,
execution_info,
execution_recorded,
+ observations,
} => loop {
- match stream.next_message() {
+ let message = match stream.next_message() {
+ Ok(Some(mut resp)) => {
+ match capture_execution(&mut resp, execution_info,
session, observations) {
+ Ok(()) => Ok(Some(resp)),
+ Err(error) => Err(stream.fail(error)),
+ }
+ }
+ other => other,
+ };
+ match message {
Ok(Some(mut resp)) => {
- capture_execution(&mut resp, execution_info, session);
if let Err(e) = keep_schema(&mut resp, &self.schema) {
return Some(Err(stream.fail(e)));
}
@@ -305,11 +319,13 @@ impl Iterator for LocalRowIterator {
/// (capacity-1) channel, keeping one batch buffered ahead of the consumer.
/// Closing the receiver stops the task even while it awaits a response;
dropping
/// the stream releases the execution. Metrics received so far are recorded on
the
-/// session when the task stops. Backs `to_local_iterator(prefetch_partitions
= true)`.
+/// session when the task stops, and the observed ones set `observations`, the
Observations of
+/// the plan. Backs `to_local_iterator(prefetch_partitions = true)`.
fn spawn_prefetch(
session: SparkSession,
mut stream: ExecutionStream,
schema: SchemaSlot,
+ observations: Vec<(String, crate::observation::Observation)>,
) -> (
tokio::sync::mpsc::Receiver<Result<Vec<Row>>>,
tokio::task::JoinHandle<()>,
@@ -326,7 +342,12 @@ fn spawn_prefetch(
};
match response {
Ok(Some(mut resp)) => {
- capture_execution(&mut resp, &mut execution_info,
&session);
+ let captured =
+ capture_execution(&mut resp, &mut execution_info,
&session, &observations);
+ if let Err(e) = captured {
+ let _ = tx.send(Err(stream.fail(e))).await;
+ break;
+ }
if let Err(e) = keep_schema(&mut resp, &schema) {
let _ = tx.send(Err(e)).await;
break;
@@ -947,6 +968,7 @@ impl DataFrame {
/// Unlike the Arrow schema of the rows, it has the user-defined types of
the columns.
pub fn collect_with_schema(&self) -> Result<(Vec<Row>, Option<DataType>)> {
let request = self.build_execute_request()?;
+ let observations = self.plan.observations();
let mut stream = self.session.execute_plan(request)?;
let mut rows = vec![];
@@ -958,7 +980,8 @@ impl DataFrame {
let Some(mut resp) = resp else {
break;
};
- capture_execution(&mut resp, &mut info, &self.session);
+ capture_execution(&mut resp, &mut info, &self.session,
&observations)
+ .map_err(|error| stream.fail(error))?;
if let Some(data_type) = resp.schema.take() {
schema = Some(DataType::from_proto(&data_type).map_err(|e|
stream.fail(e))?);
}
@@ -1002,11 +1025,13 @@ impl DataFrame {
/// fetched on demand only once the previous batch is exhausted.
pub fn to_local_iterator(&self, prefetch_partitions: bool) ->
Result<LocalRowIterator> {
let request = self.build_execute_request()?;
+ let observations = self.plan.observations();
let stream = self.session.execute_plan(request)?;
Ok(LocalRowIterator::new(
self.session.clone(),
stream,
prefetch_partitions,
+ observations,
))
}
@@ -1039,6 +1064,7 @@ impl DataFrame {
&self,
) -> Result<(Vec<arrow::record_batch::RecordBatch>, Option<DataType>)> {
let request = self.build_execute_request()?;
+ let observations = self.plan.observations();
let mut stream = self.session.execute_plan(request)?;
let mut batches = vec![];
@@ -1049,7 +1075,8 @@ impl DataFrame {
let Some(mut resp) = resp else {
break;
};
- capture_execution(&mut resp, &mut info, &self.session);
+ capture_execution(&mut resp, &mut info, &self.session,
&observations)
+ .map_err(|error| stream.fail(error))?;
if let Some(data_type) = resp.schema.take() {
schema = Some(DataType::from_proto(&data_type).map_err(|e|
stream.fail(e))?);
}
@@ -1150,16 +1177,23 @@ impl DataFrame {
/// `pyspark.ml`, which the core sends as it is, keeping `owner`, if any,
alive while any
/// DataFrame of it is. The placeholders of `relation`, which stand for
the DataFrames that
/// the plans of `pyspark.ml` take as input (see `placeholder_relation`),
are replaced by
- /// the relations of those DataFrames. Not a stable API.
+ /// the relations of those DataFrames. The Observations of the DataFrame
that it holds as its
+ /// child are those of its plan, as PySpark's plans of `pyspark.ml`
collect them. Not a stable
+ /// API.
#[doc(hidden)]
pub fn from_relation(
session: SparkSession,
mut relation: proto::Relation,
owner: Option<Arc<dyn std::any::Any + Send + Sync>>,
) -> Result<DataFrame> {
+ let observations = crate::plan::child_observations(&relation);
let depth = crate::plan::resolve_relation_levels(&mut relation)?;
Ok(DataFrame::from_raw_relation(
- session, relation, owner, depth,
+ session,
+ relation,
+ owner,
+ depth,
+ observations,
))
}
@@ -1210,12 +1244,13 @@ impl DataFrame {
}
/// The DataFrame of `relation`, as `from_relation`, of a relation without
placeholders, of
- /// `depth` levels.
+ /// `depth` levels, and of the Observations of its child.
fn from_raw_relation(
session: SparkSession,
relation: proto::Relation,
owner: Option<Arc<dyn std::any::Any + Send + Sync>>,
depth: usize,
+ observations: Vec<(String, crate::observation::Observation)>,
) -> DataFrame {
DataFrame::new(
session,
@@ -1223,6 +1258,7 @@ impl DataFrame {
relation: Box::new(relation),
owner: owner.map(crate::plan::RelationOwner),
depth,
+ observations,
},
)
}
@@ -1230,12 +1266,18 @@ 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. Not a stable API.
+ /// 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.
#[doc(hidden)]
pub fn from_sent_relation(session: SparkSession, relation:
proto::Relation) -> 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())
+ .unwrap_or_default();
// A relation decoded from bytes is shallow: prost decodes at most 100
nested messages.
- let dataframe = DataFrame::from_raw_relation(session, relation, None,
1);
+ let dataframe = DataFrame::from_raw_relation(session, relation, None,
1, observations);
if let Some(plan_id) = plan_id {
dataframe
.session
@@ -1520,7 +1562,9 @@ impl DataFrame {
/// Execute a `CheckpointCommand` and return a DataFrame referencing the
resulting
/// cached remote relation. Mirrors
`DataFrame.checkpoint`/`localCheckpoint`, which
- /// materialize server-side and return a handle to the checkpointed data.
+ /// materialize server-side and return a handle to the checkpointed data.
As PySpark's, which
+ /// runs the command without the Observations of the plan, the metrics
that it observes set
+ /// none of them.
fn checkpoint_impl(
&self,
local: bool,
@@ -1535,6 +1579,7 @@ impl DataFrame {
let (responses, info) = execute_command_with_info(
&self.session,
proto::command::CommandType::CheckpointCommand(cmd),
+ &[],
)?;
self.record_execution(info);
for resp in &responses {
@@ -1582,7 +1627,8 @@ impl DataFrame {
}
/// Build + execute a real `CreateDataFrameViewCommand` (was previously a
- /// silent no-op that passed the query relation through and never created
a view).
+ /// silent no-op that passed the query relation through and never created
a view), with the
+ /// Observations of the plan, as PySpark's.
fn create_view(&self, name: &str, replace: bool, global: bool) ->
Result<()> {
let input = self.relation()?;
let mut cmd = proto::CreateDataFrameViewCommand::default();
@@ -1593,6 +1639,7 @@ impl DataFrame {
let (_, info) = execute_command_with_info(
&self.session,
proto::command::CommandType::CreateDataframeView(cmd),
+ &self.plan.observations(),
)?;
self.record_execution(info);
Ok(())
@@ -2701,7 +2748,7 @@ pub(crate) fn execute_command_collect(
session: &SparkSession,
command_type: proto::command::CommandType,
) -> Result<Vec<proto::ExecutePlanResponse>> {
- execute_command_with_info(session, command_type).map(|(responses, _)|
responses)
+ execute_command_with_info(session, command_type, &[]).map(|(responses, _)|
responses)
}
/// Like `execute_command_collect`, for a command that PySpark runs without a
`Progress` (its
@@ -2711,24 +2758,29 @@ pub(crate) fn execute_command_unreported(
session: &SparkSession,
command_type: proto::command::CommandType,
) -> Result<()> {
- execute_command_reporting(session, command_type, false).map(|_| ())
+ execute_command_reporting(session, command_type, false, &[]).map(|_| ())
}
/// Like `execute_command_collect`, and also returns the information of the
execution, which
-/// it records as the session's most recent one, for a DataFrame that keeps
its own.
+/// it records as the session's most recent one, for a DataFrame that keeps
its own. The metrics
+/// that it observes set `observations`, the Observations of the plan of the
DataFrame that the
+/// command writes, as PySpark's `execute_command(command, observations)` sets
them: none for a
+/// command that PySpark runs without them, such as a checkpoint or a SQL
statement.
pub(crate) fn execute_command_with_info(
session: &SparkSession,
command_type: proto::command::CommandType,
+ observations: &[(String, crate::observation::Observation)],
) -> Result<(Vec<proto::ExecutePlanResponse>, ExecutionInfo)> {
- execute_command_reporting(session, command_type, true)
+ execute_command_reporting(session, command_type, true, observations)
}
/// The command `command_type`, executed with its progress for the progress
handlers when
-/// `reported`.
+/// `reported`, whose observed metrics set `observations`.
fn execute_command_reporting(
session: &SparkSession,
command_type: proto::command::CommandType,
reported: bool,
+ observations: &[(String, crate::observation::Observation)],
) -> Result<(Vec<proto::ExecutePlanResponse>, ExecutionInfo)> {
let mut command = proto::Command::default();
command.command_type = Some(command_type);
@@ -2752,7 +2804,8 @@ fn execute_command_reporting(
let mut info = ExecutionInfo::default();
let mut responses = Vec::new();
while let Some(mut resp) = stream.next_message()? {
- capture_execution(&mut resp, &mut info, session);
+ capture_execution(&mut resp, &mut info, session, observations)
+ .map_err(|error| stream.fail(error))?;
responses.push(resp);
}
session.record_execution(info.clone());
@@ -2762,12 +2815,14 @@ fn execute_command_reporting(
/// Pull execution metrics/observed-metrics off a response; the
`ExecutionStream` of the
/// response updates the progress of the execution.
`metrics`/`observed_metrics` are top-level
/// fields (not part of the `response_type` oneof), so this must run before
`response_type` is
-/// consumed.
+/// consumed. The observed metrics set `observations`, the Observations of the
executed plan
+/// (see [`set_observations`]), whose error, of the check of the session,
fails the execution.
fn capture_execution(
resp: &mut proto::ExecutePlanResponse,
info: &mut ExecutionInfo,
session: &SparkSession,
-) {
+ observations: &[(String, crate::observation::Observation)],
+) -> Result<()> {
if info.operation_id.is_none() && !resp.operation_id.is_empty() {
info.operation_id = Some(resp.operation_id.clone());
}
@@ -2776,43 +2831,59 @@ fn capture_execution(
}
if !resp.observed_metrics.is_empty() {
let metrics = std::mem::take(&mut resp.observed_metrics);
- set_observations(session, &metrics);
- // The updates of the Python accumulators, such as the results of the
UDF profilers.
- session.python_accumulators().accumulate(&metrics);
+ let set = set_observations(session, observations, &metrics);
info.observed_metrics.extend(metrics);
+ // As PySpark's client raises an error of the execution with its
operation ID.
+ set.map_err(|error| match &info.operation_id {
+ Some(operation_id) =>
error.with_operation_id(operation_id.as_str()),
+ None => error,
+ })?;
}
+ Ok(())
}
-/// Set the metrics that the server observed in the Observations of their
relations, as
-/// PySpark's client sets them in the Observations of the plan: those of each
relation, which
-/// the server reports by its plan ID, or the error of collecting them.
+/// Set the observed metrics `metrics` of an execution, in their order, as
PySpark's client sets
+/// them in `observations`, the Observations of the executed plan
(`LogicalPlan.observations`),
+/// by their names: the metrics of the Observation of their name, or the error
of collecting
+/// them, which the server reported. The updates of the Python accumulators,
such as the results
+/// of the UDF profilers, go to the handler of the session. The check of the
session
+/// ([`SparkSession::set_observation_metrics_check`]) checks the metrics of an
Observation before
+/// they are set: its error is returned, and neither those metrics nor the
ones after them are
+/// set, as PySpark's client raises when it converts them.
fn set_observations(
session: &SparkSession,
+ observations: &[(String, crate::observation::Observation)],
metrics: &[proto::execute_plan_response::ObservedMetrics],
-) {
+) -> Result<()> {
+ let check = session.observation_metrics_check();
for observed in metrics {
- let Some(node) = session.plan_ids().node_of(observed.plan_id) else {
- continue;
- };
- let LogicalPlan::Observe {
- name,
- observation: Some(observation),
- ..
- } = node.as_ref()
- else {
- continue;
- };
- if *name != observed.name {
- continue;
- }
+ let observation = observations
+ .iter()
+ .find(|(name, _)| *name == observed.name)
+ .map(|(_, observation)| observation);
match observed.root_error_idx {
- Some(root_error_idx) =>
observation.set_error(SparkError::from_observation_errors(
- root_error_idx,
- observed.errors.clone(),
- )),
- None => observation.update(&observed.keys, &observed.values),
+ Some(root_error_idx) => {
+ if let Some(observation) = observation {
+ observation.set_error(SparkError::from_observation_errors(
+ root_error_idx,
+ observed.errors.clone(),
+ ));
+ }
+ }
+ None if observed.name ==
crate::profiler::PYTHON_ACCUMULATOR_METRICS => session
+ .python_accumulators()
+ .accumulate(std::slice::from_ref(observed)),
+ None => {
+ if let Some(observation) = observation {
+ if let Some(check) = &check {
+ check(observed)?;
+ }
+ observation.update(&observed.keys, &observed.values);
+ }
+ }
}
}
+ Ok(())
}
/// Whether `value` is a fill of PySpark's `fillna`: a bool, an integer, a
float or a string. Any
@@ -5018,12 +5089,12 @@ mod plan_construction_tests {
let mut info = ExecutionInfo::default();
let mut resp = proto::ExecutePlanResponse::default();
// An empty operation id (e.g. a synthetic response) is not recorded.
- capture_execution(&mut resp, &mut info, &spark);
+ capture_execution(&mut resp, &mut info, &spark, &[]).unwrap();
assert_eq!(info.operation_id, None);
resp.operation_id = "op-1".to_string();
- capture_execution(&mut resp, &mut info, &spark);
+ capture_execution(&mut resp, &mut info, &spark, &[]).unwrap();
resp.operation_id = "op-2".to_string();
- capture_execution(&mut resp, &mut info, &spark);
+ capture_execution(&mut resp, &mut info, &spark, &[]).unwrap();
assert_eq!(info.operation_id.as_deref(), Some("op-1"));
}
@@ -5510,8 +5581,11 @@ mod plan_construction_tests {
assert_eq!(error.get_error_class().as_deref(),
Some("SESSION_NOT_SAME"));
}
+ /// 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.
#[test]
- fn observed_metrics_set_the_observations_of_their_relations() {
+ fn
observed_metrics_set_the_observations_of_the_executed_plan_by_name_as_pyspark()
{
use crate::observation::Observation;
use proto::expression::literal::LiteralType;
let spark = session();
@@ -5536,19 +5610,20 @@ mod plan_construction_tests {
let err = df1.observe_with(&first, count()).err().unwrap();
assert_eq!(err.get_condition().as_deref(), Some("REUSE_OBSERVATION"));
- let observed = |df: &DataFrame, value: i64|
proto::execute_plan_response::ObservedMetrics {
+ // Of the plan ID of the relation of the other DataFrame.
+ let observed = |value: i64|
proto::execute_plan_response::ObservedMetrics {
name: "m".to_string(),
values: vec![literal(value)],
keys: vec!["c".to_string()],
- plan_id: spark.plan_ids().id_of(&df.plan),
+ plan_id: spark.plan_ids().id_of(&df2.plan),
..Default::default()
};
let mut resp = proto::ExecutePlanResponse {
- observed_metrics: vec![observed(&df1, 3)],
+ observed_metrics: vec![observed(3)],
..Default::default()
};
let mut info = ExecutionInfo::default();
- capture_execution(&mut resp, &mut info, &spark);
+ capture_execution(&mut resp, &mut info, &spark,
&df1.plan.observations()).unwrap();
let value = |obs: &Observation| -> Vec<(String, Option<LiteralType>)> {
obs.get()
.unwrap()
@@ -5561,19 +5636,20 @@ mod plan_construction_tests {
vec![("c".to_string(), Some(LiteralType::Long(3)))]
);
assert!(value(&second).is_empty());
- // The metrics of a relation by another name, or of no relation, set
nothing.
- let mut other = observed(&df2, 5);
+ // The metrics of another name, or of an execution without
Observations, as a checkpoint
+ // runs, set nothing.
+ let mut other = observed(5);
other.name = "other".to_string();
- let mut unknown = observed(&df2, 5);
- unknown.plan_id = -1;
- resp.observed_metrics = vec![other, unknown];
- capture_execution(&mut resp, &mut info, &spark);
+ resp.observed_metrics = vec![other];
+ capture_execution(&mut resp, &mut info, &spark,
&df2.plan.observations()).unwrap();
+ resp.observed_metrics = vec![observed(5)];
+ capture_execution(&mut resp, &mut info, &spark, &[]).unwrap();
assert!(value(&second).is_empty());
// An error of collecting the metrics is what get returns.
- let mut failed = observed(&df2, 5);
+ let mut failed = observed(5);
failed.root_error_idx = Some(0);
resp.observed_metrics = vec![failed];
- capture_execution(&mut resp, &mut info, &spark);
+ capture_execution(&mut resp, &mut info, &spark,
&df2.plan.observations()).unwrap();
assert_eq!(
second.get().unwrap_err().message(),
"Observation error: invalid root_error_idx"
@@ -5582,6 +5658,188 @@ mod plan_construction_tests {
// check.
}
+ /// As PySpark's `LogicalPlan.observations`: the Observations along the
children of a plan,
+ /// both sides of a join and of a union, and the child of a relation of
`pyspark.ml`, the
+ /// outer one and the right one of a name; not those of a subquery or of
the DataFrames of a
+ /// SQL statement.
+ #[test]
+ fn the_observations_of_a_plan_are_those_that_pyspark_collects() {
+ use crate::functions::col;
+ use crate::observation::Observation;
+ let spark = session();
+ let count = || {
+ vec![crate::functions::count(crate::column::lit(1))
+ .expression()
+ .clone()]
+ };
+ let observe = |df: &DataFrame, observation: &Observation| {
+ df.observed_with(observation,
observation.name_to_observe().unwrap(), count())
+ };
+ let assert_observations = |df: &DataFrame, expected: &[(&str,
&Observation)]| {
+ let mut observations = df.plan.observations();
+ observations.sort_by(|(left, _), (right, _)| left.cmp(right));
+ assert_eq!(observations.len(), expected.len(), "{observations:?}");
+ for ((name, observation), (expected_name, expected)) in
+ observations.iter().zip(expected)
+ {
+ assert_eq!(name, expected_name);
+ assert!(observation.same(expected), "{name}");
+ }
+ };
+ let base = spark.range(3).unwrap();
+ let (inner, a, outer) = (
+ Observation::new("x"),
+ Observation::new("a"),
+ Observation::new("x"),
+ );
+ let chained = observe(
+ &observe(&observe(&base, &inner).select([col("id")]), &a),
+ &outer,
+ );
+ assert_observations(&chained, &[("a", &a), ("x", &outer)]);
+ assert_observations(&base, &[]);
+
+ let (left, right) = (Observation::new("x"), Observation::new("x"));
+ let (left, right) = (observe(&base, &left), observe(&base, &right));
+ let side = |df: &DataFrame| match df.plan.as_ref() {
+ LogicalPlan::Observe {
+ observation: Some(observation),
+ ..
+ } => observation.clone(),
+ _ => unreachable!(),
+ };
+ let joined = left.join(&right, None, JoinType::Inner);
+ assert_observations(&joined, &[("x", &side(&right))]);
+ assert_observations(&right.union(&left), &[("x", &side(&left))]);
+ assert_observations(&left.union(&left).limit(1), &[("x",
&side(&left))]);
+
+ let in_subquery = observe(&base, &Observation::new("s"));
+ assert_observations(&base.select([in_subquery.scalar()]), &[]);
+ assert_observations(&base.filter(in_subquery.exists()), &[]);
+ let sql = spark.sql_without_running(
+ "SELECT * FROM v",
+ Vec::new(),
+ HashMap::new(),
+ vec![(in_subquery.clone(), "v".to_string())],
+ );
+ assert_observations(&sql, &[]);
+
+ // A transform of pyspark.ml, over the placeholder of its input.
+ let model_input = Observation::new("m");
+ let input = observe(&base, &model_input);
+ let transform = proto::Relation {
+ common: None,
+ rel_type: Some(proto::relation::RelType::MlRelation(Box::new(
+ proto::MlRelation {
+ model_summary_dataset: None,
+ ml_type:
Some(proto::ml_relation::MlType::Transform(Box::new(
+ proto::ml_relation::Transform {
+ input:
Some(Box::new(input.placeholder_relation())),
+ params: None,
+ operator: None,
+ },
+ ))),
+ },
+ ))),
+ };
+ 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.
+ let copied = DataFrame::from_sent_relation(spark.clone(),
input.to_relation().unwrap());
+ assert_observations(&copied.limit(1), &[("m", &model_input)]);
+ let sent = spark.range(1).unwrap().to_relation().unwrap();
+ assert_observations(&DataFrame::from_sent_relation(spark.clone(),
sent), &[]);
+ }
+
+ /// As PySpark's client, which converts the metrics of the Observations of
the plan as they
+ /// arrive: metrics that the check of the session rejects fail the
execution, of its
+ /// operation ID, and neither they nor the metrics after them are set, so
that their
+ /// Observations keep the metrics of the executions before; those before
them are set.
+ #[test]
+ fn
rejected_metrics_fail_the_execution_and_keep_the_earlier_metrics_as_pyspark() {
+ use crate::observation::Observation;
+ use proto::expression::literal::LiteralType;
+ let spark = session();
+ spark.set_observation_metrics_check(|metrics| {
+ let rejected = |value: &proto::expression::Literal| {
+ value.literal_type == Some(LiteralType::Long(-1))
+ };
+ if metrics.values.iter().any(rejected) {
+ return Err(SparkError::classed(
+ SparkErrorKind::TypeError,
+ "UNSUPPORTED_LITERAL",
+ &[("literal", "-1")],
+ ));
+ }
+ Ok(())
+ });
+ assert!(spark.clone().observation_metrics_check().is_some());
+ assert!(spark.new_session().observation_metrics_check().is_none());
+ let count = || {
+ vec![crate::functions::count(crate::column::lit(1))
+ .expression()
+ .clone()]
+ };
+ let observe = |df: &DataFrame, observation: &Observation| {
+ df.observed_with(observation,
observation.name_to_observe().unwrap(), count())
+ };
+ let (a, b, c) = (
+ Observation::new("a"),
+ Observation::new("b"),
+ Observation::new("c"),
+ );
+ let df = observe(&observe(&observe(&spark.range(3).unwrap(), &a), &b),
&c);
+ let observations = df.plan.observations();
+ let observed = |name: &str, value: i64|
proto::execute_plan_response::ObservedMetrics {
+ name: name.to_string(),
+ values: vec![proto::expression::Literal {
+ literal_type: Some(LiteralType::Long(value)),
+ ..Default::default()
+ }],
+ keys: vec!["v".to_string()],
+ ..Default::default()
+ };
+ let value = |observation: &Observation| -> Vec<Option<LiteralType>> {
+ let metrics = observation.get().unwrap().into_iter();
+ metrics.map(|(_, value)| value.literal_type).collect()
+ };
+ let response = |metrics, operation_id: &str|
proto::ExecutePlanResponse {
+ observed_metrics: metrics,
+ operation_id: operation_id.to_string(),
+ ..Default::default()
+ };
+ let mut resp = response(
+ vec![observed("a", 1), observed("b", 1), observed("c", 1)],
+ "op-1",
+ );
+ let mut info = ExecutionInfo::default();
+ capture_execution(&mut resp, &mut info, &spark,
&observations).unwrap();
+
+ let mut resp = response(
+ vec![observed("a", 2), observed("b", -1), observed("c", 2)],
+ "op-2",
+ );
+ let mut info = ExecutionInfo::default();
+ let error = capture_execution(&mut resp, &mut info, &spark,
&observations).unwrap_err();
+ assert_eq!(
+ error.get_condition().as_deref(),
+ Some("UNSUPPORTED_LITERAL")
+ );
+ assert_eq!(error.operation_id.as_deref(), Some("op-2"));
+ assert_eq!(value(&a), vec![Some(LiteralType::Long(2))]);
+ assert_eq!(value(&b), vec![Some(LiteralType::Long(1))]);
+ assert_eq!(value(&c), vec![Some(LiteralType::Long(1))]);
+ assert_eq!(info.observed_metrics.len(), 3);
+
+ // Neither the metrics of a name of no Observation of the plan nor
those of an error are
+ // checked.
+ let mut failed = observed("b", -1);
+ failed.root_error_idx = Some(0);
+ let mut resp = response(vec![observed("other", -1), failed], "op-3");
+ capture_execution(&mut resp, &mut info, &spark,
&observations).unwrap();
+ assert!(b.get().is_err());
+ }
+
#[test]
fn derived_dataframes_keep_the_plan_ids_of_their_inputs() {
use crate::column::lit;
diff --git a/crates/spark-connect/src/merge.rs
b/crates/spark-connect/src/merge.rs
index cc4b76c7..ee7d9d66 100644
--- a/crates/spark-connect/src/merge.rs
+++ b/crates/spark-connect/src/merge.rs
@@ -112,9 +112,14 @@ impl MergeIntoWriter {
self
}
- /// Run the command of the merge, keeping its execution as its DataFrame's
last one.
+ /// Run the command of the merge, keeping its execution as its DataFrame's
last one, with the
+ /// Observations of the source, as PySpark's MergeIntoWriter runs it.
fn run(&self, command_type: proto::command::CommandType) -> Result<()> {
- let (_, info) =
crate::dataframe::execute_command_with_info(&self.session, command_type)?;
+ let (_, info) = crate::dataframe::execute_command_with_info(
+ &self.session,
+ command_type,
+ &self.source_plan.observations(),
+ )?;
if let Some(execution) = &self.execution {
*execution.lock().unwrap() = Some(info);
}
diff --git a/crates/spark-connect/src/plan.rs b/crates/spark-connect/src/plan.rs
index 6478d9e4..fdbf8c48 100644
--- a/crates/spark-connect/src/plan.rs
+++ b/crates/spark-connect/src/plan.rs
@@ -133,11 +133,14 @@ pub enum LogicalPlan {
/// (`pyspark.ml.connect.proto.TransformerRelation`), sent as it is, with
the plan ID of the
/// core, and the owner of the relation, if any, which the plan keeps
alive. `depth` is the
/// number of levels of the relation as a plan, with those of the plans of
DataFrames that it
- /// holds (1 for a relation without them), which count for
[`MAX_PLAN_DEPTH`].
+ /// holds (1 for a relation without them), which count for
[`MAX_PLAN_DEPTH`]. `observations`
+ /// are those of the DataFrames that the relation holds as its child, as
PySpark's plans of
+ /// `pyspark.ml` collect them (see [`LogicalPlan::observations`]).
Raw {
relation: Box<proto::Relation>,
owner: Option<RelationOwner>,
depth: usize,
+ observations: Vec<(String, crate::observation::Observation)>,
},
/// Deduplicate: `df.distinct()` or `df.dropDuplicates()`.
Deduplicate {
@@ -593,14 +596,15 @@ impl PlanIds {
.insert(Arc::as_ptr(node) as usize, (Arc::downgrade(node), id));
}
- /// The live node of the plan ID `id`, as the server reports a relation by
its plan ID.
+ /// A live node of the plan ID `id`, such as that of the DataFrame of a
relation that this
+ /// session sent.
pub(crate) fn node_of(&self, id: i64) -> Option<Arc<LogicalPlan>> {
let nodes = self.nodes.lock().unwrap_or_else(|e| e.into_inner());
nodes
.ids
.values()
- .find(|(_, node_id)| *node_id == id)
- .and_then(|(node, _)| node.upgrade())
+ .filter(|(_, node_id)| *node_id == id)
+ .find_map(|(node, _)| node.upgrade())
}
#[cfg(test)]
@@ -687,6 +691,44 @@ pub(crate) fn placeholder_relation(node:
&Arc<LogicalPlan>, ids: &Arc<PlanIds>)
}
}
+/// The Observations of the DataFrame whose placeholder `relation`, a relation
of `pyspark.ml`,
+/// holds as its child: the relation itself, or the input of a transform, the
dataset of a model
+/// summary or the root of a `WithRelations`, and so on down, as PySpark's
`TransformerRelation`,
+/// `AttributeRelation` and `WithRelations` collect the `observations` of
their child (see
+/// [`LogicalPlan::observations`]). Taken before the placeholders are
replaced, which then no
+/// longer name their DataFrames.
+pub(crate) fn child_observations(
+ relation: &proto::Relation,
+) -> Vec<(String, crate::observation::Observation)> {
+ let mut relation = relation;
+ loop {
+ let child = match &relation.rel_type {
+ Some(proto::relation::RelType::Extension(any))
+ if any.type_url == PLACEHOLDER_TYPE_URL =>
+ {
+ let target = <[u8; 8]>::try_from(any.value.as_slice())
+ .ok()
+ .and_then(|marker|
placeholder_target(i64::from_le_bytes(marker)));
+ return target
+ .map(|(node, _)| node.observations())
+ .unwrap_or_default();
+ }
+ Some(proto::relation::RelType::MlRelation(ml)) => match
&ml.ml_type {
+ Some(proto::ml_relation::MlType::Transform(transform)) => {
+ transform.input.as_deref()
+ }
+ _ => ml.model_summary_dataset.as_deref(),
+ },
+ Some(proto::relation::RelType::WithRelations(with)) =>
with.root.as_deref(),
+ _ => None,
+ };
+ match child {
+ Some(child) => relation = child,
+ None => return Vec::new(),
+ }
+ }
+}
+
/// Replace the placeholders of `relation` by the relations of their
DataFrames, and of the
/// relations that the plans of `pyspark.ml` take as input (their
`ml_relation`, `with_relations`
/// and fetched arguments). Each replacement is the relation of a DataFrame of
the core, which has
@@ -1162,6 +1204,71 @@ impl LogicalPlan {
inputs_of!(self)
}
+ /// The Observations of this plan by their names, as PySpark's
`LogicalPlan.observations`
+ /// collects those whose metrics an action of the plan sets: of each
`Observe` node of an
+ /// [`Observation`](crate::observation::Observation) on the inputs that
PySpark's plans hold
+ /// as their child, both sides of a join, a set operation and a zip, and
the DataFrames that
+ /// a relation of `pyspark.ml` holds as its child. Not of the plans that
an expression refers
+ /// to (a subquery), the DataFrames of `SparkSession.sql`, the other input
of a `CoGroupMap`
+ /// or the initial state of a `GroupMap`, which PySpark's plans hold apart
from their child.
+ /// Of two Observations of one name, the one that PySpark's dict keeps:
the outer one, and
+ /// that of the right side.
+ pub(crate) fn observations(&self) -> Vec<(String,
crate::observation::Observation)> {
+ // PySpark merges `{**child, **own}` and `{**left, **right}`, so the
last Observation of
+ // a name in the post-order of the plan is kept. This walks the
reverse of that order (a
+ // node, then its right side, then its left side) and keeps the first
one of a name,
+ // without recursing, as a plan may be deep. A node that several
inputs share is walked
+ // once: the Observations under it come after those of its first walk.
+ let mut observations: Vec<(String, crate::observation::Observation)> =
Vec::new();
+ let mut keep = |name: &String, observation:
&crate::observation::Observation| {
+ if !observations.iter().any(|(kept, _)| kept == name) {
+ observations.push((name.clone(), observation.clone()));
+ }
+ };
+ let mut walked: std::collections::HashSet<*const LogicalPlan> =
Default::default();
+ let mut pending: Vec<&LogicalPlan> = vec![self];
+ while let Some(plan) = pending.pop() {
+ let key: *const LogicalPlan = plan;
+ if !walked.insert(key) {
+ continue;
+ }
+ match plan {
+ LogicalPlan::Observe {
+ name,
+ observation: Some(observation),
+ ..
+ } => keep(name, observation),
+ LogicalPlan::Raw {
+ observations: held, ..
+ } => {
+ for (name, observation) in held {
+ keep(name, observation);
+ }
+ }
+ _ => {}
+ }
+ match plan {
+ // The right side is walked first, as it is popped first.
+ LogicalPlan::Join { left, right, .. }
+ | LogicalPlan::LateralJoin { left, right, .. }
+ | LogicalPlan::SetOperation { left, right, .. }
+ | LogicalPlan::Zip { left, right, .. }
+ | LogicalPlan::AsOfJoin { left, right, .. }
+ | LogicalPlan::NearestByJoin { left, right, .. } => {
+ pending.push(left);
+ pending.push(right);
+ }
+ LogicalPlan::CoGroupMap { input, .. } | LogicalPlan::GroupMap
{ input, .. } => {
+ pending.push(input)
+ }
+ LogicalPlan::WithRelations { root, .. } => pending.push(root),
+ // The other plans hold their input as PySpark's hold their
child.
+ _ => pending.extend(plan.inputs().into_iter().map(|input|
input.as_ref())),
+ }
+ }
+ observations
+ }
+
/// The levels of this node itself, under which its inputs are: one, or
those of the relation
/// of a [`LogicalPlan::Raw`], which holds the plans of its inputs.
fn own_levels(&self) -> usize {
@@ -3583,6 +3690,7 @@ mod deep_plan_tests {
relation: Box::new(relation),
owner: None,
depth,
+ observations: Vec::new(),
})
}
diff --git a/crates/spark-connect/src/readwriter.rs
b/crates/spark-connect/src/readwriter.rs
index cff16e54..43ccbfef 100644
--- a/crates/spark-connect/src/readwriter.rs
+++ b/crates/spark-connect/src/readwriter.rs
@@ -336,9 +336,14 @@ impl DataFrameWriter {
self
}
- /// Run the command of the write, keeping its execution as its DataFrame's
last one.
+ /// Run the command of the write, keeping its execution as its DataFrame's
last one, with the
+ /// Observations of its DataFrame, as PySpark's writer runs it.
fn run(&self, command_type: proto::command::CommandType) -> Result<()> {
- let (_, info) =
crate::dataframe::execute_command_with_info(&self.session, command_type)?;
+ let (_, info) = crate::dataframe::execute_command_with_info(
+ &self.session,
+ command_type,
+ &self.input_plan.observations(),
+ )?;
if let Some(execution) = &self.execution {
*execution.lock().unwrap() = Some(info);
}
@@ -557,9 +562,14 @@ impl DataFrameWriterV2 {
self
}
- /// Run the command of the write, keeping its execution as its DataFrame's
last one.
+ /// Run the command of the write, keeping its execution as its DataFrame's
last one, with the
+ /// Observations of its DataFrame, as PySpark's writer runs it.
fn run(&self, command_type: proto::command::CommandType) -> Result<()> {
- let (_, info) =
crate::dataframe::execute_command_with_info(&self.session, command_type)?;
+ let (_, info) = crate::dataframe::execute_command_with_info(
+ &self.session,
+ command_type,
+ &self.input_plan.observations(),
+ )?;
if let Some(execution) = &self.execution {
*execution.lock().unwrap() = Some(info);
}
diff --git a/crates/spark-connect/src/session.rs
b/crates/spark-connect/src/session.rs
index 1f62a87e..ecd0c93e 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -31,6 +31,11 @@ pub(crate) type FallibleProgressHandler = Arc<dyn
Fn(&ProgressUpdate) -> Result<
/// The shared registry of progress handlers and their ids, without retaining
a session.
pub(crate) type ProgressHandlers = Arc<Mutex<Vec<(u64,
FallibleProgressHandler)>>>;
+/// A check of the metrics that an execution observed for an Observation of
its plan, made before
+/// they are set, as [`SparkSession::set_observation_metrics_check`] sets it.
+pub type ObservationMetricsCheck =
+ Arc<dyn Fn(&proto::execute_plan_response::ObservedMetrics) -> Result<()> +
Send + Sync>;
+
/// Metrics captured from the last executed query. Mirrors the data behind
/// `pyspark.sql.DataFrame.executionInfo` / `client.core.ExecutionInfo`.
#[derive(Debug, Clone, Default)]
@@ -152,6 +157,8 @@ pub struct SparkSession {
progress_handler_id: Arc<AtomicU64>,
/// The handler of the updates of the Python accumulators of its
executions.
python_accumulators: PythonAccumulators,
+ /// The check of the metrics of the Observations of its executions (shared
across clones).
+ observation_metrics_check: Arc<Mutex<Option<ObservationMetricsCheck>>>,
/// Whether `stop()` has been called on this session (shared across
clones).
/// Backs `is_stopped`.
stopped: Arc<AtomicBool>,
@@ -174,6 +181,7 @@ impl SparkSession {
progress_handlers: Arc::new(Mutex::new(Vec::new())),
progress_handler_id: Arc::new(AtomicU64::new(0)),
python_accumulators: PythonAccumulators::default(),
+ observation_metrics_check: Arc::default(),
stopped: Arc::new(AtomicBool::new(false)),
server_version: Arc::new(Mutex::new(None)),
listener_bus: Arc::default(),
@@ -388,6 +396,7 @@ impl SparkSession {
progress_handlers: Arc::new(Mutex::new(Vec::new())),
progress_handler_id: Arc::new(AtomicU64::new(0)),
python_accumulators: PythonAccumulators::default(),
+ observation_metrics_check: Arc::default(),
stopped: Arc::new(AtomicBool::new(false)),
server_version: Arc::new(Mutex::new(None)),
listener_bus: Arc::default(),
@@ -553,9 +562,10 @@ impl SparkSession {
references: Vec<(DataFrame, String)>,
) -> Result<DataFrame> {
let plan = Self::sql_plan(query, pos_args, named_args, references);
- // As pyspark, run the statement as a command now. The server executes
a command and
- // returns a relation of its result; for a query it returns the
query's relation, which
- // then runs at an action.
+ // As pyspark, run the statement as a command now, without the
Observations of its
+ // DataFrames, which the DataFrame of its result does not have either.
The server executes
+ // a command and returns a relation of its result; for a query it
returns the query's
+ // relation, which then runs at an action.
let command = proto::SqlCommand {
input: Some(crate::dataframe::build_input_relation(&plan, self)?),
..Default::default()
@@ -851,8 +861,9 @@ impl SparkSession {
/// Execute `command`, a command built outside the core, such as the ML
commands of
/// `pyspark.ml`, and return the responses of the server, as the Python
client's
- /// `execute_command` reads them. The placeholders of its relations are
replaced, as
- /// `DataFrame::from_relation` does. Not a stable API.
+ /// `execute_command` reads them, without Observations, as `pyspark.ml`
runs them. The
+ /// placeholders of its relations are replaced, as
`DataFrame::from_relation` does. Not a
+ /// stable API.
#[doc(hidden)]
pub fn execute_command_proto(
&self,
@@ -862,7 +873,7 @@ impl SparkSession {
let Some(command_type) = command.command_type else {
return Err(SparkError::value_msg("a command of no command type"));
};
- let (responses, _) = crate::dataframe::execute_command_with_info(self,
command_type)?;
+ let (responses, _) = crate::dataframe::execute_command_with_info(self,
command_type, &[])?;
Ok(responses)
}
@@ -1274,6 +1285,33 @@ impl SparkSession {
&self.python_accumulators
}
+ /// Set the check of the metrics that the executions of this session, and
of its clones,
+ /// observe for the Observations of their plans, made before the metrics
of each are set: an
+ /// error of the check is the error of the execution, and that Observation
keeps the metrics
+ /// that it had, as do those whose metrics come after it, as PySpark's
client raises from an
+ /// execution at the first metric that it does not convert. Used by the
Python client to raise
+ /// PySpark's `UNSUPPORTED_LITERAL` for a metric of a kind that PySpark
does not convert.
+ pub fn set_observation_metrics_check(
+ &self,
+ check: impl Fn(&proto::execute_plan_response::ObservedMetrics) ->
Result<()>
+ + Send
+ + Sync
+ + 'static,
+ ) {
+ *self
+ .observation_metrics_check
+ .lock()
+ .unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(check));
+ }
+
+ /// The check of the metrics of the Observations of the executions, if one
is set.
+ pub(crate) fn observation_metrics_check(&self) ->
Option<ObservationMetricsCheck> {
+ self.observation_metrics_check
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .clone()
+ }
+
/// Stop this Spark session.
///
/// Idempotent, mirroring pyspark: the session is marked stopped even if
releasing it
@@ -1363,6 +1401,7 @@ impl Clone for SparkSession {
progress_handlers: Arc::clone(&self.progress_handlers),
progress_handler_id: Arc::clone(&self.progress_handler_id),
python_accumulators: self.python_accumulators.clone(),
+ observation_metrics_check:
Arc::clone(&self.observation_metrics_check),
stopped: Arc::clone(&self.stopped),
server_version: Arc::clone(&self.server_version),
listener_bus: Arc::clone(&self.listener_bus),
diff --git a/python/pyspark/sql/connect/client/__init__.py
b/python/pyspark/sql/connect/client/__init__.py
index dbde2166..e0f4158a 100644
--- a/python/pyspark/sql/connect/client/__init__.py
+++ b/python/pyspark/sql/connect/client/__init__.py
@@ -325,7 +325,8 @@ class DefaultChannelBuilder(ChannelBuilder):
class _UnsupportedLiteral:
"""An observed-metric literal of a kind ``LiteralExpression._to_value``
rejects. The
Rust transport decodes eagerly, so it leaves this marker and ``pairs``
raises the
- reference's ``UNSUPPORTED_LITERAL`` when read, as the reference does."""
+ reference's ``UNSUPPORTED_LITERAL`` when read, as the reference does. A
metric that holds
+ such a literal as an element is the marker of that literal, which the
reference names."""
def __init__(self, literal: str):
self.literal = literal
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 7fabf624..e666d1be 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -4551,6 +4551,49 @@ def
test_an_observation_of_a_year_month_interval_fails_the_action_as_pyspark(ses
assert observation.get == {}
+def
test_only_the_observations_of_the_plan_of_an_action_convert_its_metrics_as_pyspark(session):
+ # As PySpark's client, which converts and sets the metrics of the
Observations of the plan of
+ # an action, and runs localCheckpoint and a SQL statement without them: a
year-month interval
+ # metric fails neither those nor a subquery of the observed DataFrame, an
Observation keeps
+ # the metrics of the earlier actions when an action fails, and a metric of
a name that holds
+ # an interval as an element raises when executionInfo reads it.
+ from pyspark.errors import PySparkTypeError
+ from pyspark.sql import Observation
+
+ interval = F.expr("INTERVAL '1' YEAR")
+ observation = Observation("unset_by_commands_and_subqueries")
+ df = session.range(3).observe(observation, F.max(interval).alias("ym"))
+ assert df.localCheckpoint().count() == 3
+ assert session.sql("SELECT * FROM {d}", d=df).count() == 3
+ assert
session.range(2).select(df.select(F.max("id")).scalar().alias("m")).collect()
== [
+ Row(m=2), Row(m=2)]
+ assert observation.get == {}
+
+ table = f"observation_kept_metrics_{os.getpid()}"
+ session.sql(f"DROP TABLE IF EXISTS {table}")
+ session.sql(f"CREATE TABLE {table} (x INT) USING parquet")
+ try:
+ kept = Observation("kept_after_a_failing_action")
+ observed = session.table(table).observe(
+ kept, F.max(F.when(F.col("x") > 0, interval)).alias("ym"),
+ F.count(F.lit(1)).alias("c"))
+ assert observed.count() == 0 and kept.get == {"ym": None, "c": 0}
+ session.sql(f"INSERT INTO {table} VALUES (1)")
+ with pytest.raises(PySparkTypeError) as error:
+ observed.count()
+ assert error.value.getCondition() == "UNSUPPORTED_LITERAL"
+ assert error.value._operation_id is not None
+ assert kept.get == {"ym": None, "c": 0}
+ finally:
+ session.sql(f"DROP TABLE IF EXISTS {table}")
+
+ named = session.range(2).observe("holds_an_interval",
F.collect_list(interval).alias("m"))
+ assert named.collect() == [Row(id=0), Row(id=1)]
+ with pytest.raises(PySparkTypeError) as error:
+ named.executionInfo.flows
+ assert error.value.getMessageParameters() == {"literal":
"year_month_interval: 12\n"}
+
+
def
test_sample_split_and_sample_by_without_a_seed_follow_python_random_as_pyspark(
session, tmp_path):
# As PySpark's: without a seed, sample, randomSplit and sampleBy draw one
from Python's
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 24e0283a..863e5692 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -9179,6 +9179,142 @@ def
test_metrics_that_pyspark_cannot_convert_fail_the_action_of_their_observatio
named.executionInfo.flows
+def _count_batch_and_observed_metrics(service, df):
+ # The response of the row of a count() of 3
(ExecutePlanResponse.arrow_batch=2: row_count=1,
+ # data=2), and a function of the response of the observed metrics of a
name, of one literal
+ # of a key, reported by the plan ID of the CollectMetrics of that name in
the plan of `df`
+ # (ExecutePlanResponse.observed_metrics=6: name=1, values=2, keys=3,
plan_id=4).
+ import pyarrow as pa
+
+ df.collect()
+ # ExecutePlanRequest.plan=3 -> Plan.root=1.
+ ids = _collect_metrics_plan_ids(
+ parse_message(parse_message(service.execute_requests[-1])[3][0])[1][0])
+ table = pa.table({"count(1)": pa.array([3], pa.int64())})
+ sink = pa.BufferOutputStream()
+ with pa.ipc.new_stream(sink, table.schema) as writer:
+ writer.write_table(table)
+ batch = message_field(2, varint_field(1, 1) + message_field(2,
sink.getvalue().to_pybytes()))
+
+ def observed(name, literal, key):
+ return message_field(6, message_field(1, name) + message_field(2,
literal)
+ + message_field(3, key) + varint_field(4,
ids[name]))
+
+ return batch, observed
+
+
+def
test_only_the_observations_of_the_plan_of_an_action_receive_its_metrics_as_pyspark(
+ mock_connect):
+ # As PySpark's client, which converts and sets the metrics of the
Observations of the plan of
+ # an action (LogicalPlan.observations, of its children), and runs
checkpoint, localCheckpoint
+ # and a SQL statement without them: the metrics of an Observation of a
DataFrame that only a
+ # checkpoint, a SQL statement or a subquery runs set nothing, and a metric
that PySpark does
+ # not convert raises nothing there.
+ import copy
+
+ from pyspark.errors import PySparkTypeError
+ 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)
+ # Literal.long=7, year_month_interval=20;
ExecutePlanResponse.checkpoint_command_result=19
+ # (CheckpointCommandResult.relation=1, CachedRemoteRelation.relation_id=1).
+ count = observed("o", varint_field(7, 3), "c")
+ interval = observed("o", varint_field(20, 14), "c")
+ checkpointed = message_field(19, message_field(1, message_field(1, "r1")))
+ for metrics in (count, interval):
+ service.execute_payload = checkpointed + metrics
+ df.localCheckpoint()
+ df.checkpoint()
+ service.execute_payload = metrics
+ statement = spark.sql("SELECT * FROM {d}", d=df)
+ service.execute_payload = batch + metrics
+ assert statement.count() == 3
+ assert spark.range(1).select(df.select(F.max("id")).scalar()).count()
== 3
+ assert spark.range(1).where(df.exists()).count() == 3
+ assert observation.get == {}
+ # An action of a plan of the Observation sets its metrics, as does one of
a copy of the
+ # DataFrame, whose plan PySpark copies with the Observation, and both
raise for a metric that
+ # PySpark does not convert.
+ service.execute_payload = batch + count
+ assert df.where("id > 0").count() == 3 and observation.get == {"c": 3}
+ service.execute_payload = batch + observed("o", varint_field(7, 4), "c")
+ assert copy.copy(df).count() == 3 and observation.get == {"c": 4}
+ service.execute_payload = batch + interval
+ for frame in (df.union(spark.range(1)), copy.copy(df), copy.deepcopy(df)):
+ with pytest.raises(PySparkTypeError):
+ frame.count()
+ assert observation.get == {"c": 4}
+
+
+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
+ # whose metrics come after it, keep the metrics of the earlier actions,
and the exception has
+ # the operation ID of the execution, as PySpark's _handle_error stamps it.
+ from pyspark.errors import PySparkTypeError
+ from pyspark.sql import Observation
+ from pyspark.sql import functions as F
+
+ spark, service = mock_connect
+ first, second = Observation("first"), Observation("second")
+ df = (spark.range(3).observe(first, F.count(F.lit(1)).alias("c"))
+ .observe(second, F.max("id").alias("m")))
+ _, observed = _count_batch_and_observed_metrics(service, df)
+ # Literal.long=7, year_month_interval=20.
+ interval = varint_field(20, 14)
+ service.execute_payload = (observed("first", varint_field(7, 3), "c")
+ + observed("second", varint_field(7, 2), "m"))
+ df.collect()
+ assert first.get == {"c": 3} and second.get == {"m": 2}
+ for payload, kept in [
+ (observed("second", interval, "m") + observed("first", varint_field(7,
4), "c"),
+ {"c": 3}),
+ (observed("first", varint_field(7, 5), "c") + observed("second",
interval, "m"),
+ {"c": 5}),
+ ]:
+ service.execute_payload = payload
+ with pytest.raises(PySparkTypeError) as error:
+ df.collect()
+ assert error.value.getCondition() == "UNSUPPORTED_LITERAL"
+ assert first.get == kept and second.get == {"m": 2}
+ assert error.value._operation_id ==
_request_operation_id(service.execute_requests[-1])
+
+
+def
test_flows_raise_for_a_metric_that_holds_one_pyspark_cannot_convert_as_pyspark(mock_connect):
+ # As PySpark's PlanObservedMetrics.pairs, which converts each metric with
+ # LiteralExpression._to_value: a metric of a name that holds a year-month
interval as an
+ # element, of an array, a struct or a map, raises UNSUPPORTED_LITERAL of
that element.
+ from pyspark.errors import PySparkTypeError
+ from pyspark.sql import functions as F
+
+ spark, service = mock_connect
+ # Literal.string=13, year_month_interval=20, array=22 (Array.elements=2),
map=23 (Map.keys=3,
+ # values=4), struct=24 (Struct.elements=2).
+ first, later = varint_field(20, 12), varint_field(20, 13)
+ holders = [
+ message_field(22, message_field(2, first) + message_field(2, later)),
+ message_field(24, message_field(2, first)),
+ message_field(23, message_field(3, message_field(13, "k")) +
message_field(4, first)),
+ message_field(22, message_field(2, message_field(24, message_field(2,
first)))),
+ ]
+ named = spark.range(3).observe("named", F.max("id").alias("m"))
+ for holder in holders:
+ service.execute_payload = message_field(
+ 6, message_field(1, "named") + message_field(2, holder) +
message_field(3, "m"))
+ assert named.collect() == []
+ info = named.executionInfo
+ with pytest.raises(PySparkTypeError) as error:
+ info.flows
+ assert error.value.getCondition() == "UNSUPPORTED_LITERAL"
+ assert error.value.getMessageParameters() == {"literal":
"year_month_interval: 12\n"}
+ with pytest.raises(PySparkTypeError):
+ [metrics.to_dict() for metrics in info._observations]
+
+
def test_json_names_of_nanosecond_timestamps_are_not_data_types_as_pyspark():
# As PySpark's, which has no nanosecond timestamp types: their JSON names
do not parse
# (CANNOT_PARSE_DATATYPE), and pyspark.sql.types has no names of them.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]