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 19eec4d5 [SPARK-61363][CONNECT][PYTHON] Match PySpark's literals,
Observations, caches, nanosecond type names and local iterators in the Python
drop-in
19eec4d5 is described below
commit 19eec4d59cd66ded68758a9971d1fa042c425f5e
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Wed Nov 11 06:50:45 2026 +0900
[SPARK-61363][CONNECT][PYTHON] Match PySpark's literals, Observations,
caches, nanosecond type names and local iterators in the Python drop-in
### What changes were proposed in this pull request?
[SPARK-61363](https://issues.apache.org/jira/browse/SPARK-61363):
low-priority findings of a review of the Python drop-in, each checked against
official PySpark 4.3.0 with the same probe on both clients.
- **Literals** (`crates/pyspark-rs/src/functions.rs`):
- `lit()`, `isin`, `when` and sql args take an int or a float by its
type, not by `__index__` or `__float__`. An object of only `__index__` (or only
`__float__`, or a `Fraction`) raises `UNSUPPORTED_DATA_TYPE` with its class
name, as PySpark does. int and float subclasses, `IntEnum` and NumPy scalars
work as before.
- A str that UTF-8 cannot encode (a lone surrogate) raises protobuf's
`ValueError` ("... isn't a valid unicode string and can't be encoded in
UTF-8."), as PySpark's serializer does.
- A pandas `Timestamp` literal of nanoseconds drops them silently, of the
same value, for TIMESTAMP and TIMESTAMP_NTZ literals. Before, pandas warned
"Discarding nonzero nanoseconds in conversion" (also `session.rs`).
- **`DataFrame.transform`** asserts that the function returned a DataFrame:
`AssertionError: Func returned an instance of type [<class 'int'>], should have
been DataFrame.`
- **Observations** (`observation.rs`, `interrupt.rs`):
- An action whose execution sends a metric that PySpark's
`LiteralExpression._to_value` does not convert (a year-month interval, a
nanosecond timestamp), for an Observation of the session, raises
`PySparkTypeError` `UNSUPPORTED_LITERAL` with the literal's protobuf text, as
PySpark does.
- That Observation, and those after it in the server's order, then give
`{}` from `get`.
- `toLocalIterator` checks at the end of its stream.
- **Nanosecond type names** (`types.rs`, `python/pyspark/sql/types.py`):
- The JSON-name parsers (`_parse_datatype_json_value`,
`_parse_datatype_json_string`, and the `fromJson` of `StructType`,
`StructField` and `ArrayType`) raise `CANNOT_PARSE_DATATYPE` for
`timestamp_ntz(9)` and `timestamp_ltz(9)`.
- `pyspark.sql.types` no longer has `TimestampNTZNanosType` and
`TimestampLTZNanosType`, which PySpark does not have. They stay internal to
`pyspark._pyspark`.
- **`toLocalIterator`** ignores `prefetchPartitions`, as PySpark Connect
does. A batch is fetched when the iteration reaches it, so the progress
handlers run in `next()`, on the iterating thread.
- **Caches** (`PyDataFrame`): `isStreaming`, `semanticHash`, `isEmpty` and
`inputFiles` are asked once per DataFrame, as PySpark's `cached_property` and
`functools.cache` keep them, also after `stop()`. A failure is not kept.
- **`dev/parity/known-differences.md`**: `toArrow` of invalid UTF-8 raises,
where PySpark returns a table whose `StringArray` holds the invalid bytes,
which is not valid Arrow.
### Why are the changes needed?
Each was a difference from PySpark 4.3.0:
- **Literals and `transform`:** the drop-in took objects that PySpark
rejects. It gave a misleading `UNSUPPORTED_DATA_TYPE "Unsupported DataType
str"` for surrogates, and warned where PySpark is silent. `transform` returned
a function's non-DataFrame result.
- **Observations:** `get` returned an internal marker object, where PySpark
raises from the action.
- **Nanosecond types:** the parsers accepted names that PySpark's do not,
and the module had names that PySpark's does not.
- **`toLocalIterator(prefetchPartitions=True)`:** it called the handlers on
a runtime thread ahead of the consumer. An exception of a handler that the
consumer never reached stayed referenced for good.
- **Caches:** the drop-in asked the server again, so the answers could
change, such as `isStreaming` after a temp view is redefined as streaming. And
after `stop()` it raised where PySpark returns the kept answer.
### Does this PR introduce _any_ user-facing change?
Yes, all of the above, to match PySpark. Two differences remain:
- `toLocalIterator` no longer reads ahead with `prefetchPartitions=True`,
as PySpark Connect does not.
- The check of Observation metrics matches the Observations of a session by
name and reads the session's last execution, so two actions that one session
runs at once from two threads could check each other's execution.
### How was this patch tested?
- Offline (`python/tests/test_dropin_offline.py`, placed before
`test_property_not_method`). Each test fails on master for the reason it tests:
- `test_lit_takes_an_int_or_a_float_by_its_type_as_pyspark`
-
`test_a_str_that_utf8_cannot_encode_is_the_value_error_of_protobuf_as_pyspark`
-
`test_pandas_timestamp_literals_drop_their_nanoseconds_silently_as_pyspark`
-
`test_transform_asserts_that_the_function_returned_a_dataframe_as_pyspark`
-
`test_metrics_that_pyspark_cannot_convert_fail_the_action_of_their_observation_as_pyspark`
- `test_json_names_of_nanosecond_timestamps_are_not_data_types_as_pyspark`
-
`test_local_iterators_call_the_progress_handlers_in_next_whatever_the_prefetch_as_pyspark`
-
`test_is_streaming_is_empty_and_input_files_are_asked_once_per_dataframe_as_pyspark`
- Live (`python/tests/test_dropin_e2e.py`, placed before
`test_sample_split_and_sample_by_without_a_seed_follow_python_random_as_pyspark`):
-
`test_answers_that_pyspark_keeps_are_asked_once_per_dataframe_as_pyspark`, with
`semanticHash`;
-
`test_an_observation_of_a_year_month_interval_fails_the_action_as_pyspark`.
- Changed existing tests:
- `EVERY_TYPE` drops the two nanosecond instances.
- `test_timestamp_nanos_types_are_private_types_of_their_own` replaces
`test_timestamp_nanos_types_roundtrip_and_pickle`.
- `test_is_streaming_asks_the_server_as_pyspark` asks a new DataFrame for
the second answer.
- The reviewers' probes, against a local Spark 4.3.0 server, now give the
same output for official PySpark and ours. Two differences remain: the Column
operators raise `UNSUPPORTED_DATA_TYPE` where official raises an incidental
`AttributeError`, and the nested UTF-8 order, which a separate change fixes.
- Checks:
- the build of all tests, also with `wasm-udf` and `datafusion,polars`,
without warnings;
- the lib tests of both crates (732 passed);
- `cargo fmt --all --check`, and clippy with no diagnostics on the
changed lines;
- the offline Python suites (3040 passed, 8 skipped);
- the live drop-in, Arrow and ML suites against a local Spark 4.3.0
server (267 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 #470 from HyukjinKwon/p3-py.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/dataframe.rs | 176 ++++++++++++++++-----
crates/pyspark-rs/src/functions.rs | 55 ++++---
crates/pyspark-rs/src/interrupt.rs | 10 +-
crates/pyspark-rs/src/observation.rs | 164 ++++++++++++++++++--
crates/pyspark-rs/src/session.rs | 33 ++--
crates/pyspark-rs/src/types.rs | 35 ++---
dev/parity/known-differences.md | 7 +
python/pyspark/sql/types.py | 2 -
python/tests/test_dropin_e2e.py | 45 ++++++
python/tests/test_dropin_offline.py | 292 +++++++++++++++++++++++++++++++++--
10 files changed, 697 insertions(+), 122 deletions(-)
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index 5a0c3107..6cd6f1f3 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -61,6 +61,26 @@ pub struct PyDataFrame {
/// dictionary, which can start a collection, before PyO3 writes the
value. Until then the
/// memory is zeroed, so this flag is false and `__traverse__` reads
nothing else.
gc_ready: std::sync::atomic::AtomicBool,
+ /// The answers that PySpark keeps for each DataFrame once it has them,
`isStreaming` (a
+ /// `cached_property`), `semanticHash`, `isEmpty` and `inputFiles`
(`functools.cache`): later
+ /// calls do not ask again, also after the session stopped. (`isLocal` is
cached in the core.)
+ is_streaming: std::sync::OnceLock<bool>,
+ semantic_hash: std::sync::OnceLock<i32>,
+ is_empty: std::sync::OnceLock<bool>,
+ input_files: std::sync::OnceLock<Vec<String>>,
+}
+
+/// The answer kept in `cell`, else that of `ask`, which is kept unless it
fails, as
+/// `functools.cache` keeps the result of a call.
+fn cached<T: Clone>(
+ cell: &std::sync::OnceLock<T>,
+ ask: impl FnOnce() -> PyResult<T>,
+) -> PyResult<T> {
+ if let Some(value) = cell.get() {
+ return Ok(value.clone());
+ }
+ let value = ask()?;
+ Ok(cell.get_or_init(|| value).clone())
}
/// The settings of the eager evaluation of `__repr__` and `_repr_html_`.
@@ -216,6 +236,10 @@ impl PyDataFrame {
dataframe,
support_repr_html: std::sync::atomic::AtomicBool::new(false),
gc_ready: std::sync::atomic::AtomicBool::new(true),
+ is_streaming: std::sync::OnceLock::new(),
+ semantic_hash: std::sync::OnceLock::new(),
+ is_empty: std::sync::OnceLock::new(),
+ input_files: std::sync::OnceLock::new(),
}
}
@@ -1488,11 +1512,13 @@ impl PyDataFrame {
.to_pyerr()
}
- /// The server-side hash of this DataFrame's logical plan.
+ /// The server-side hash of this DataFrame's logical plan, asked once, as
PySpark's.
#[pyo3(name = "semanticHash")]
fn semantic_hash(&self, py: Python<'_>) -> PyResult<i32> {
- py.detach(|| self.dataframe.semantic_hash().map_err(Box::new))
- .to_pyerr()
+ cached(&self.semantic_hash, || {
+ py.detach(|| self.dataframe.semantic_hash().map_err(Box::new))
+ .to_pyerr()
+ })
}
/// Sort within each partition.
@@ -1765,18 +1791,8 @@ impl PyDataFrame {
}
}
}
- if let Ok(observation) =
- observation.extract::<PyRef<'_,
crate::observation::PyObservation>>()
- {
- let observation = &observation.inner;
- return py
- .detach(|| {
- self.dataframe
- .observe_with(observation, columns)
- .map_err(Box::new)
- })
- .to_pyerr()
- .map(PyDataFrame::new);
+ if let Ok(observation) =
observation.cast::<crate::observation::PyObservation>() {
+ return crate::observation::observe(py, &self.dataframe,
observation, columns);
}
if observation.is_instance_of::<pyo3::types::PyString>() {
let name: String = observation.extract()?;
@@ -2013,11 +2029,13 @@ impl PyDataFrame {
.collect())
}
- /// The list of files that make up this DataFrame.
+ /// The list of files that make up this DataFrame, asked once, as
PySpark's.
#[pyo3(name = "inputFiles")]
fn input_files(&self, py: Python<'_>) -> PyResult<Vec<String>> {
- py.detach(|| self.dataframe.input_files().map_err(Box::new))
- .to_pyerr()
+ cached(&self.input_files, || {
+ py.detach(|| self.dataframe.input_files().map_err(Box::new))
+ .to_pyerr()
+ })
}
/// Whether the server answers that this DataFrame is local (a local
relation).
@@ -2035,12 +2053,15 @@ impl PyDataFrame {
.to_pyerr()
}
- /// Whether this DataFrame contains one or more sources that continuously
return data.
+ /// Whether this DataFrame contains one or more sources that continuously
return data, asked
+ /// once, as PySpark's.
#[pyo3(name = "isStreaming")]
#[getter]
fn is_streaming(&self, py: Python<'_>) -> PyResult<bool> {
- py.detach(|| self.dataframe.is_streaming().map_err(Box::new))
- .to_pyerr()
+ cached(&self.is_streaming, || {
+ py.detach(|| self.dataframe.is_streaming().map_err(Box::new))
+ .to_pyerr()
+ })
}
/// The storage level currently in use for this DataFrame.
@@ -2135,7 +2156,15 @@ impl PyDataFrame {
call_args.push(a.unbind());
}
let tuple = PyTuple::new(py, call_args)?;
- Ok(func.call(tuple, kwargs)?.unbind())
+ let result = func.call(tuple, kwargs)?;
+ // As PySpark's assert that the function returned a DataFrame.
+ if !result.is_instance_of::<PyDataFrame>() {
+ return Err(pyo3::exceptions::PyAssertionError::new_err(format!(
+ "Func returned an instance of type [{}], should have been
DataFrame.",
+ result.get_type().repr()?
+ )));
+ }
+ Ok(result.unbind())
}
/// Unpivot (wide-to-long), as PySpark's `DataFrame.unpivot`: `ids` and
`values` are each a
@@ -2299,11 +2328,14 @@ impl PyDataFrame {
///
/// Mirrors
`pyspark.sql.DataFrame.toLocalIterator(prefetchPartitions=False)`, a generator:
/// the execution starts with the first row, and its errors are raised by
the iteration.
- /// Yields Row objects lazily as batches are fetched from the server.
+ /// Yields Row objects lazily as batches are fetched from the server. As
PySpark Connect's,
+ /// which ignores `prefetchPartitions`, a batch is fetched when the
iteration reaches it, so
+ /// the progress handlers of the execution are called by `next()`, on the
iterating thread.
#[pyo3(name = "toLocalIterator")]
#[pyo3(signature = (prefetchPartitions=false))]
fn to_local_iterator(&self, prefetchPartitions: bool) ->
PyLocalRowIterator {
- PyLocalRowIterator::new(self.dataframe.clone(), prefetchPartitions)
+ let _ = prefetchPartitions;
+ PyLocalRowIterator::new(self.dataframe.clone())
}
/// Collect the DataFrame into a `pyarrow.Table`.
@@ -2627,10 +2659,12 @@ impl PyDataFrame {
)))
}
- /// Check if the DataFrame is empty.
+ /// Check if the DataFrame is empty, asked once, as PySpark's.
fn isEmpty(&self, py: Python<'_>) -> PyResult<bool> {
- interruptible(py, &self.dataframe.spark_session(), || {
- self.dataframe.is_empty().map_err(Box::new)
+ cached(&self.is_empty, || {
+ interruptible(py, &self.dataframe.spark_session(), || {
+ self.dataframe.is_empty().map_err(Box::new)
+ })
})
}
@@ -4404,7 +4438,9 @@ fn check_arrow_schema(
/// The proto text of the first nanosecond-precision timestamp of `data_type`,
`TIMESTAMP_NTZ(p)`
/// or `TIMESTAMP_LTZ(p)` with p > 6, in the order of PySpark's conversion of
a schema from its
/// proto: the message that PySpark's `proto_schema_to_pyspark_data_type`
names when it fails.
-fn nanosecond_timestamp_text(data_type: &spark_connect::types::DataType) ->
Option<String> {
+pub(crate) fn nanosecond_timestamp_text(
+ data_type: &spark_connect::types::DataType,
+) -> Option<String> {
use spark_connect::types::DataType;
match data_type {
DataType::TimestampNtzNanos { precision } => Some(format!(
@@ -4535,7 +4571,6 @@ fn rows_to_py(
#[pyclass(name = "LocalRowIterator", module = "pyspark.sql.dataframe")]
pub struct PyLocalRowIterator {
dataframe: DataFrame,
- prefetch_partitions: bool,
/// The rows of the execution, which the first row starts, as PySpark's
generator does.
iterator: Option<LocalRowIterator>,
/// Whether the iteration ended, with its last row or an error, as a
generator ends.
@@ -4549,26 +4584,29 @@ 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 {
- pub fn new(dataframe: DataFrame, prefetch_partitions: bool) -> Self {
+ pub fn new(dataframe: DataFrame) -> Self {
PyLocalRowIterator {
dataframe,
- prefetch_partitions,
iterator: None,
finished: false,
converters: None,
binary_as_bytes: None,
fields: None,
nested_fields: NestedFieldNames::default(),
+ observed: None,
}
}
/// The next row, starting the execution for the first.
fn next_row(&mut self) ->
Option<spark_connect_core::error::Result<spark_connect::row::Row>> {
if self.iterator.is_none() {
- match self.dataframe.to_local_iterator(self.prefetch_partitions) {
+ match self.dataframe.to_local_iterator(false) {
Ok(iterator) => self.iterator = Some(iterator),
Err(error) => return Some(Err(error)),
}
@@ -4586,9 +4624,14 @@ impl PyLocalRowIterator {
value
}
};
- let next = interruptible(py, &self.dataframe.spark_session(), || {
+ 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, || {
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.
@@ -4631,7 +4674,12 @@ impl PyLocalRowIterator {
.map(Some)
}
Some(Err(error)) =>
Err(crate::errors::spark_error_to_py_exception(error)),
- None => Ok(None),
+ None => {
+ if let Some(observed) = self.observed.take() {
+ observed.after(py, &session)?;
+ }
+ Ok(None)
+ }
}
}
}
@@ -4852,7 +4900,63 @@ pub(crate) fn literal_to_py(
Some(_) => py
.import("pyspark.sql.connect.client")?
.getattr("_UnsupportedLiteral")?
- .call1((format!("{literal:?}"),))?
+ .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.
+pub(crate) fn unsupported_literal(
+ literal: &spark_connect_proto::expression::Literal,
+) -> Option<&spark_connect_proto::expression::Literal> {
+ use spark_connect_proto::expression::literal::LiteralType;
+ match &literal.literal_type {
+ None
+ | Some(LiteralType::Null(_))
+ | Some(LiteralType::Boolean(_))
+ | Some(LiteralType::Byte(_))
+ | Some(LiteralType::Short(_))
+ | Some(LiteralType::Integer(_))
+ | Some(LiteralType::Long(_))
+ | Some(LiteralType::Float(_))
+ | Some(LiteralType::Double(_))
+ | Some(LiteralType::String(_))
+ | Some(LiteralType::Binary(_))
+ | Some(LiteralType::Decimal(_))
+ | Some(LiteralType::Date(_))
+ | Some(LiteralType::Time(_))
+ | Some(LiteralType::Timestamp(_))
+ | Some(LiteralType::TimestampNtz(_))
+ | Some(LiteralType::DayTimeInterval(_)) => None,
+ Some(LiteralType::Array(array)) =>
array.elements.iter().find_map(unsupported_literal),
+ // A key before its value, as a dict comprehension evaluates them.
+ Some(LiteralType::Map(map)) =>
map.keys.iter().zip(&map.values).find_map(|(key, value)| {
+ unsupported_literal(key).or_else(|| unsupported_literal(value))
+ }),
+ Some(LiteralType::Struct(fields)) =>
fields.elements.iter().find_map(unsupported_literal),
+ Some(_) => Some(literal),
+ }
+}
+
+/// The text of `literal` as PySpark's `str` of its protobuf message gives it,
which its
+/// `UNSUPPORTED_LITERAL` shows; the Rust debug text of the message without
`protobuf`.
+pub(crate) fn literal_text(
+ py: Python<'_>,
+ literal: &spark_connect_proto::expression::Literal,
+) -> String {
+ use prost::Message;
+ let text = || -> PyResult<String> {
+ py.import("pyspark.sql.connect.proto")?
+ .getattr("Expression")?
+ .getattr("Literal")?
+ .call_method1(
+ "FromString",
+ (pyo3::types::PyBytes::new(py, &literal.encode_to_vec()),),
+ )?
+ .str()?
+ .extract()
+ };
+ text().unwrap_or_else(|_| format!("{literal:?}"))
+}
diff --git a/crates/pyspark-rs/src/functions.rs
b/crates/pyspark-rs/src/functions.rs
index d73afd28..c903728d 100644
--- a/crates/pyspark-rs/src/functions.rs
+++ b/crates/pyspark-rs/src/functions.rs
@@ -220,6 +220,20 @@ pub(crate) fn value_not_between(py: Python<'_>) -> PyErr {
)
}
+/// The `ValueError` of protobuf's Python string field for a str that is not
encodable as UTF-8,
+/// with its message, which shows at most 1024 characters of the repr of the
value.
+fn not_utf8_string(obj: &Bound<'_, PyAny>) -> PyErr {
+ let message = pyo3::types::PyString::new(
+ obj.py(),
+ "%.1024r isn't a valid unicode string and can't be encoded in UTF-8.",
+ )
+ .call_method1("__mod__", ((obj,),));
+ match message {
+ Ok(message) =>
pyo3::exceptions::PyValueError::new_err(message.unbind()),
+ Err(error) => error,
+ }
+}
+
/// An int32 literal within its range, otherwise a long, as PySpark's
`_infer_type`.
fn integer_literal(value: i64) -> LiteralExpression {
if let Ok(value) = i32::try_from(value) {
@@ -293,24 +307,31 @@ pub fn to_column(obj: &Bound<'_, PyAny>) ->
PyResult<Column> {
)));
}
- if let Ok(i) = obj.extract::<i64>() {
- return Ok(Column::new(Expression::literal(integer_literal(i))));
- }
- // An int beyond a long is not a double, as PySpark's literal of it: it is
an error.
+ // An int or a float by its type, as PySpark's `_infer_type` takes them:
an object that
+ // only converts to one (`__index__`, `__float__`) is not a literal.
if obj.is_instance_of::<pyo3::types::PyInt>() {
- return Err(value_not_between(obj.py()));
+ return match obj.extract::<i64>() {
+ Ok(i) => Ok(Column::new(Expression::literal(integer_literal(i)))),
+ // An int beyond a long is not a double, as PySpark's literal of
it: it is an error.
+ Err(_) => Err(value_not_between(obj.py())),
+ };
}
- if let Ok(f) = obj.extract::<f64>() {
+ if obj.is_instance_of::<pyo3::types::PyFloat>() {
return Ok(Column::new(Expression::literal(LiteralExpression::double(
- f,
+ obj.extract::<f64>()?,
))));
}
- if let Ok(s) = obj.extract::<String>() {
- return Ok(Column::new(Expression::literal(LiteralExpression::string(
- s,
- ))));
+ if obj.is_instance_of::<pyo3::types::PyString>() {
+ return match obj.extract::<String>() {
+ Ok(s) =>
Ok(Column::new(Expression::literal(LiteralExpression::string(
+ s,
+ )))),
+ // A str that UTF-8 cannot encode (a lone surrogate), as
protobuf's string field
+ // rejects it when PySpark sends the literal.
+ Err(_) => Err(not_utf8_string(obj)),
+ };
}
// As PySpark's literal conversion for a value of another type.
@@ -563,19 +584,15 @@ fn numpy_scalar_literal(obj: &Bound<'_, PyAny>) ->
PyResult<Option<LiteralExpres
/// with `session::py_to_value` so `lit(..)` and `createDataFrame(..)` encode
identically.
/// The microseconds of the wall clock of a datetime, naive or aware, as
PySpark's
/// `TimestampNTZType.toInternal` takes them: `calendar.timegm` of its own
time tuple, whatever
-/// its zone. A pandas Timestamp is taken as the datetime it stands for, as
for a TIMESTAMP.
+/// its zone. A pandas Timestamp's fields are read from it, as PySpark's, so
its nanoseconds are
+/// dropped silently, as for a TIMESTAMP.
fn wall_clock_micros(obj: &Bound<'_, PyAny>) -> PyResult<i64> {
let py = obj.py();
- let normalized = if obj.hasattr("to_pydatetime").unwrap_or(false) {
- obj.call_method0("to_pydatetime")?
- } else {
- obj.clone()
- };
let seconds: i64 = py
.import("calendar")?
- .call_method1("timegm", (normalized.call_method0("timetuple")?,))?
+ .call_method1("timegm", (obj.call_method0("timetuple")?,))?
.extract()?;
- let micros: i64 = normalized.getattr("microsecond")?.extract()?;
+ let micros: i64 = obj.getattr("microsecond")?.extract()?;
Ok(seconds * 1_000_000 + micros)
}
diff --git a/crates/pyspark-rs/src/interrupt.rs
b/crates/pyspark-rs/src/interrupt.rs
index fd34cdf2..2be83c13 100644
--- a/crates/pyspark-rs/src/interrupt.rs
+++ b/crates/pyspark-rs/src/interrupt.rs
@@ -59,12 +59,20 @@ impl SignalWatch {
/// The execution is interrupted only when `f` has started one; a request that
is still waiting
/// for its response (such as an analysis) ends when the response arrives, and
the exception is
/// raised then. A wait of `block_on_abortable` (the release of `stop()`) ends
at once instead.
+///
+/// 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> {
- interruptible_outcome(py, session, f)?.to_pyerr()
+ 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)
}
/// 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 9166847d..43a1b4cc 100644
--- a/crates/pyspark-rs/src/observation.rs
+++ b/crates/pyspark-rs/src/observation.rs
@@ -1,8 +1,15 @@
//! 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};
+use pyo3::types::{PyDict, PyString, PyWeakrefMethods, PyWeakrefReference};
+use spark_connect::dataframe::DataFrame;
+use spark_connect::expression::Expression;
use spark_connect::observation::Observation;
+use spark_connect::SparkSession;
use crate::column::{raise_pyspark, PyColumn};
use crate::dataframe::PyDataFrame;
@@ -17,6 +24,9 @@ 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]
@@ -54,7 +64,10 @@ impl PyObservation {
Observation::new(&name)
}
};
- Ok(PyObservation { inner })
+ Ok(PyObservation {
+ inner,
+ rejected: AtomicBool::new(false),
+ })
}
/// The name of the observation, as PySpark's `_name`: None for an unnamed
observation
@@ -65,11 +78,23 @@ 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.
+ /// 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.
#[getter]
fn get<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
- let metrics = self.inner.get().to_pyerr()?;
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);
+ }
for (name, value) in metrics {
result.set_item(name, crate::dataframe::literal_to_py(py, &value,
None)?)?;
}
@@ -80,8 +105,7 @@ impl PyObservation {
/// `Observation._on`, which `DataFrame.observe` of an Observation calls.
#[pyo3(signature = (df, *exprs))]
fn _on(
- &self,
- py: Python<'_>,
+ slf: &Bound<'_, Self>,
df: PyRef<'_, PyDataFrame>,
exprs: Vec<PyRef<'_, PyColumn>>,
) -> PyResult<PyDataFrame> {
@@ -89,9 +113,129 @@ impl PyObservation {
.iter()
.map(|c| c.column.expression().clone())
.collect();
- let (dataframe, observation) = (df.dataframe.clone(), &self.inner);
- py.detach(|| dataframe.observe_with(observation, exprs))
- .to_pyerr()
- .map(PyDataFrame::new)
+ observe(slf.py(), &df.dataframe, slf, exprs)
+ }
+}
+
+/// 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.
+pub(crate) fn observe(
+ py: Python<'_>,
+ df: &DataFrame,
+ observation: &Bound<'_, PyObservation>,
+ exprs: Vec<Expression>,
+) -> PyResult<PyDataFrame> {
+ let inner = observation.borrow().inner.clone();
+ let observed = py
+ .detach(|| df.observe_with(&inner, exprs).map_err(Box::new))
+ .to_pyerr()?;
+ 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 {
+ 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,
+ });
+ 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 f3bc44e6..c10f8bdb 100644
--- a/crates/pyspark-rs/src/session.rs
+++ b/crates/pyspark-rs/src/session.rs
@@ -3795,11 +3795,9 @@ pub(crate) fn py_to_value(obj: &Bound<'_, PyAny>) ->
PyResult<Value> {
if let Some(dt_mod) = &datetime_mod {
if let Ok(datetime_cls) = dt_mod.getattr("datetime") {
if obj.is_instance(&datetime_cls)? {
- // A naive datetime represents session-local wall-clock;
encode it via the
- // POSIX instant (.timestamp() interprets a naive value in the
local zone).
- // A pandas Timestamp is a datetime subclass but its
.timestamp() treats a
- // naive value as UTC, which disagrees with
datetime/`lit(..)`; normalize it
- // to a pure datetime first so createDataFrame() and lit()
encode identically.
+ // A naive datetime represents session-local wall-clock;
encode it as the
+ // instant of that local time, a pandas Timestamp too (whose
.timestamp() would
+ // take a naive value as UTC), so createDataFrame() and lit()
encode identically.
let micros = datetime_to_micros(obj)?;
return Ok(Value::Timestamp(micros));
}
@@ -3851,39 +3849,30 @@ pub(crate) fn py_to_value(obj: &Bound<'_, PyAny>) ->
PyResult<Value> {
/// Encode a Python `datetime.datetime` as microseconds since the Unix epoch
(UTC),
/// consistently for both plain `datetime` and `pandas.Timestamp`.
///
-/// `datetime.timestamp()` interprets a naive value in the local zone (the
convention Spark
-/// uses for a naive value in a session-local TIMESTAMP, and the one
`functions.lit(..)`
-/// follows). `pandas.Timestamp.timestamp()` instead treats a naive value as
UTC, which would
-/// make `createDataFrame(pandas_df)` disagree with `lit(..)` by the local
offset. To keep the
-/// two paths identical we first downcast a pandas Timestamp to a plain
`datetime` via
-/// `to_pydatetime()`. Timezone-aware values are unaffected (both encode the
same instant).
-///
/// The seconds and the microseconds are integers, as
`TimestampType.toInternal` takes them
/// (`calendar.timegm` of the UTC tuple of an aware value, `time.mktime` of
the local tuple of a
/// naive one): a float of seconds loses the microseconds of the values far
from the epoch, and
-/// `timestamp()` overflows for the latest datetimes of the year 9999.
+/// `timestamp()` overflows for the latest datetimes of the year 9999. A naive
pandas Timestamp
+/// is so in the local zone too, which its own `timestamp()` would take as
UTC. As PySpark's, the
+/// fields are read from the value itself, so the nanoseconds of a pandas
Timestamp are dropped
+/// silently, where its `to_pydatetime()` warns that it discards them.
pub(crate) fn datetime_to_micros(obj: &Bound<'_, PyAny>) -> PyResult<i64> {
let py = obj.py();
- let normalized = if obj.hasattr("to_pydatetime").unwrap_or(false) {
- obj.call_method0("to_pydatetime")?
- } else {
- obj.clone()
- };
- let seconds: i64 = if normalized.getattr("tzinfo")?.is_none() {
+ let seconds: i64 = if obj.getattr("tzinfo")?.is_none() {
// time.mktime returns a float of whole seconds; int() truncates it as
`as` does.
- let local = normalized.call_method0("timetuple")?;
+ let local = obj.call_method0("timetuple")?;
let secs: f64 = py
.import("time")?
.call_method1("mktime", (local,))?
.extract()?;
secs as i64
} else {
- let utc = normalized.call_method0("utctimetuple")?;
+ let utc = obj.call_method0("utctimetuple")?;
py.import("calendar")?
.call_method1("timegm", (utc,))?
.extract()?
};
- let micros: i64 = normalized.getattr("microsecond")?.extract()?;
+ let micros: i64 = obj.getattr("microsecond")?.extract()?;
Ok(seconds * 1_000_000 + micros)
}
diff --git a/crates/pyspark-rs/src/types.rs b/crates/pyspark-rs/src/types.rs
index 0b9609af..f6f51ed1 100644
--- a/crates/pyspark-rs/src/types.rs
+++ b/crates/pyspark-rs/src/types.rs
@@ -2509,22 +2509,6 @@ impl PyStructType {
data_type.clone()
};
let dt = py_to_data_type(&type_object)?;
- // As PySpark's `_parse_datatype_json_value`, a name of a type
that has no JSON name in
- // PySpark (a nanosecond timestamp) is not a data type.
- if data_type.is_instance_of::<pyo3::types::PyString>()
- && matches!(
- dt,
- DataType::TimestampNtzNanos { .. } |
DataType::TimestampLtzNanos { .. }
- )
- {
- let name: String = data_type.extract()?;
- return Err(crate::column::raise_pyspark(
- py,
- "PySparkValueError",
- "CANNOT_PARSE_DATATYPE",
- &[("msg", &name)],
- ));
- }
let md = match metadata {
Some(d) => py_metadata_to_map(py, d)?,
None => BTreeMap::new(),
@@ -2932,8 +2916,9 @@ impl PyTimeType {
/// Spark's `TimestampNTZNanosType(precision)` (precision 7..=9; default 9).
PySpark 4.3.0 has no
/// Python class for the nanosecond timestamp types, but the server reports
them in
-/// schemas, so they materialize as this class instead of being mapped to a
lossy type.
-#[pyclass(name = "TimestampNTZNanosType", module = "pyspark.sql.types",
extends = PyDatetimeType)]
+/// schemas, so they materialize as this class instead of being mapped to a
lossy type. As
+/// PySpark has no such name, it is not one of `pyspark.sql.types`.
+#[pyclass(name = "TimestampNTZNanosType", module = "pyspark._pyspark", extends
= PyDatetimeType)]
pub struct PyTimestampNTZNanosType {
pub precision: i32,
}
@@ -3011,8 +2996,9 @@ impl PyTimestampNTZNanosType {
/// Spark's `TimestampLTZNanosType(precision)` (precision 7..=9; default 9).
PySpark 4.3.0 has no
/// Python class for the nanosecond timestamp types, but the server reports
them in
-/// schemas, so they materialize as this class instead of being mapped to a
lossy type.
-#[pyclass(name = "TimestampLTZNanosType", module = "pyspark.sql.types",
extends = PyDatetimeType)]
+/// schemas, so they materialize as this class instead of being mapped to a
lossy type. As
+/// PySpark has no such name, it is not one of `pyspark.sql.types`.
+#[pyclass(name = "TimestampLTZNanosType", module = "pyspark._pyspark", extends
= PyDatetimeType)]
pub struct PyTimestampLTZNanosType {
pub precision: i32,
}
@@ -3572,11 +3558,18 @@ pub(crate) fn spatial_type_srid(srid: &Bound<'_,
PyAny>, geographic: bool) -> Py
/// `"geography(OGC:CRS84, SPHERICAL)"`, or a nested struct/array/map object)
with the core
/// grammar, into its concrete Python type object.
`pyspark.sql.types._parse_datatype_json_value`
/// delegates its atomic and parameterized string forms here, so the drop-in
keeps one JSON
-/// grammar (the core's) instead of a second parser in Python.
+/// grammar (the core's) instead of a second parser in Python. A nanosecond
timestamp
+/// (`timestamp_ntz(9)`) is not a JSON name of PySpark, whose parser has no
such type: a
+/// `ValueError`, which the shim raises as `CANNOT_PARSE_DATATYPE`.
#[pyfunction]
pub fn parse_datatype_json(py: Python<'_>, json: &str) -> PyResult<Py<PyAny>> {
let dt = DataType::from_json_str(json)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError,
_>(e.to_string()))?;
+ if crate::dataframe::nanosecond_timestamp_text(&dt).is_some() {
+ return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
+ "not a data type of PySpark: {json}"
+ )));
+ }
data_type_to_py(py, &dt)
}
diff --git a/dev/parity/known-differences.md b/dev/parity/known-differences.md
index 4edeac01..c413b6a8 100644
--- a/dev/parity/known-differences.md
+++ b/dev/parity/known-differences.md
@@ -115,6 +115,13 @@ difference is intentional or tracked for a fix.
## `DataFrame`
+- **`toArrow` of a string that is not valid UTF-8** (intentional). PySpark's
`toArrow`
+ returns a table whose string column holds the invalid bytes, which pyarrow's
full
+ validation rejects. This client does not return invalid Arrow data: it
raises the
+ `PySparkRuntimeError` of the Arrow decode, as its `toPandas` does (`collect`
raises
+ PySpark's `UnicodeDecodeError`; the Rust API's `collect` returns
+ `SparkErrorKind::UnicodeDecode`).
+
- **Public base and native MRO.** `pyspark.sql.DataFrame` is implemented as a
Python base/factory, allowing subclasses such as
`pyspark.testing.mlutils.MockDataset` to allocate their own Python state with
diff --git a/python/pyspark/sql/types.py b/python/pyspark/sql/types.py
index d671e80b..0a48318f 100644
--- a/python/pyspark/sql/types.py
+++ b/python/pyspark/sql/types.py
@@ -18,8 +18,6 @@ try:
AnyTimeType, AnsiIntervalType, SpatialType,
GeometryType, GeographyType,
VariantVal, Geometry, Geography,
- # Spark's nanosecond timestamp types (no PySpark 4.3.0 class; not in
__all__).
- TimestampNTZNanosType, TimestampLTZNanosType,
)
# The extension exports the same tuple-backed Row as the public Python
imports.
from pyspark._pyspark import Row
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 5e4e755a..430f1ebc 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -4323,6 +4323,51 @@ def
test_samples_and_splits_take_a_seed_of_the_client_as_pyspark(session):
assert df.withMetadata("id", metadata).schema["id"].metadata == metadata
+def
test_answers_that_pyspark_keeps_are_asked_once_per_dataframe_as_pyspark(session):
+ # As PySpark's isStreaming (a cached_property), semanticHash, isEmpty and
inputFiles
+ # (functools.cache): a DataFrame keeps the server's first answer, so a
redefined view or a
+ # new row does not change it, and the answers stay after the session
stopped.
+ table = f"cached_answers_{os.getpid()}"
+ session.sql(f"DROP TABLE IF EXISTS {table}")
+ session.sql(f"CREATE TABLE {table} (id BIGINT) USING parquet")
+ try:
+ rows = session.table(table)
+ assert rows.isEmpty() is True
+ session.sql(f"INSERT INTO {table} VALUES (1)")
+ assert rows.isEmpty() is True and session.table(table).isEmpty() is
False
+ finally:
+ session.sql(f"DROP TABLE IF EXISTS {table}")
+ session.range(1).createOrReplaceTempView("cached_answers_view")
+ view = session.table("cached_answers_view")
+ is_streaming, semantic_hash, input_files = (
+ view.isStreaming, view.semanticHash(), view.inputFiles())
+
session.readStream.format("rate").load().createOrReplaceTempView("cached_answers_view")
+ assert session.table("cached_answers_view").isStreaming is True
+ assert (view.isStreaming, view.semanticHash(), view.inputFiles()) == (
+ False, semantic_hash, input_files)
+ session.catalog.dropTempView("cached_answers_view")
+ session.stop()
+ assert (view.isStreaming, view.semanticHash(), view.inputFiles()) == (
+ is_streaming, semantic_hash, input_files)
+
+
+def
test_an_observation_of_a_year_month_interval_fails_the_action_as_pyspark(session):
+ # As PySpark's client, which converts the metrics of an Observation of the
plan as they
+ # arrive: a year-month interval, which LiteralExpression._to_value does
not convert, raises
+ # UNSUPPORTED_LITERAL from the action, and the Observation has no metrics.
+ from pyspark.errors import PySparkTypeError
+ from pyspark.sql import Observation
+
+ observation = Observation("year_month_interval_metric")
+ interval = F.make_ym_interval(F.lit(1), F.col("id").cast("int"))
+ df = session.range(3).observe(observation, F.max(interval).alias("m"))
+ with pytest.raises(PySparkTypeError) as error:
+ df.count()
+ assert error.value.getCondition() == "UNSUPPORTED_LITERAL"
+ assert error.value.getMessageParameters() == {"literal":
"year_month_interval: 14\n"}
+ assert observation.get == {}
+
+
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 da3bc94a..92a946c5 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -225,7 +225,7 @@ EVERY_TYPE = [
T.LongType(), T.FloatType(), T.DoubleType(), T.DecimalType(),
T.DecimalType(38, 18),
T.StringType(), T.StringType("UTF8_LCASE"), T.StringType("UNICODE_CI"),
T.CharType(5), T.VarcharType(9), T.BinaryType(), T.DateType(),
T.TimestampType(),
- T.TimestampNTZType(), T.TimestampNTZNanosType(9),
T.TimestampLTZNanosType(7),
+ T.TimestampNTZType(),
T.TimeType(3), T.CalendarIntervalType(), T.YearMonthIntervalType(0, 1),
T.YearMonthIntervalType(1, 1), T.DayTimeIntervalType(0, 3),
T.DayTimeIntervalType(2, 2), T.VariantType(),
@@ -7053,13 +7053,14 @@ def test_struct_field_equality():
def test_is_streaming_asks_the_server_as_pyspark(mock_connect):
- # As PySpark's: isStreaming is the server's answer to an IsStreaming
request of the plan.
+ # As PySpark's: isStreaming is the server's answer to an IsStreaming
request of the plan,
+ # which a DataFrame asks once.
spark, service = mock_connect
df = spark.range(1).select("id")
try:
assert df.isStreaming is False
service.streaming = True
- assert df.isStreaming is True
+ assert spark.range(1).select("id").isStreaming is True
finally:
service.streaming = False
# base.proto: AnalyzePlanRequest.is_streaming=8.
@@ -7973,6 +7974,276 @@ def test_dropin_version_is_spark_version():
assert pyspark.__version__ == "4.3.0"
+def test_lit_takes_an_int_or_a_float_by_its_type_as_pyspark(mock_connect):
+ # As PySpark's LiteralExpression._infer_type, which takes an int or a
float by isinstance: an
+ # object that only converts to one (__index__, __float__) is
UNSUPPORTED_DATA_TYPE, while the
+ # subclasses of int and float, an IntEnum and the NumPy scalars are
literals.
+ import enum
+
+ np = pytest.importorskip("numpy")
+ from pyspark.errors import PySparkTypeError
+ from pyspark.sql import functions as F
+
+ class Index:
+ def __index__(self):
+ return 7
+
+ class Floaty:
+ def __float__(self):
+ return 2.5
+
+ class Both(Index, Floaty):
+ pass
+
+ class MyInt(int):
+ pass
+
+ class MyFloat(float):
+ pass
+
+ class Small(enum.IntEnum):
+ A = 5
+
+ spark, _ = mock_connect
+ for value in (Index(), Floaty(), Both(), Fraction(1, 2)):
+ name = type(value).__name__
+ for build in (lambda v: F.lit(v), lambda v: F.col("id").isin(v),
+ lambda v: F.when(F.col("id") == 0, v)):
+ with pytest.raises(PySparkTypeError) as error:
+ build(value)
+ assert error.value.getCondition() == "UNSUPPORTED_DATA_TYPE"
+ assert error.value.getMessageParameters() == {"data_type": name}
+ for args in ({"x": value}, [value]):
+ with pytest.raises(PySparkTypeError) as error:
+ spark.sql("SELECT :x" if isinstance(args, dict) else "SELECT
?", args=args)
+ assert error.value.getMessageParameters() == {"data_type": name}
+ for value, text in ((MyInt(5), "5"), (MyFloat(1.5), "1.5"), (Small.A, "5"),
+ (np.int64(6), "6"), (np.float64(2.5), "2.5")):
+ assert repr(F.lit(value)) == f"Column<'{text}'>"
+
+
+def
test_a_str_that_utf8_cannot_encode_is_the_value_error_of_protobuf_as_pyspark(mock_connect):
+ # As PySpark's, whose protobuf string field rejects a str with a lone
surrogate: a ValueError
+ # of protobuf's message, of at most 1024 characters of the repr of the
value, for a literal
+ # and the arguments of sql.
+ from pyspark.sql import functions as F
+
+ spark, service = mock_connect
+ value, long_value = "a\ud800b", "x" * 2000 + "\ud800"
+ message = "%.1024r isn't a valid unicode string and can't be encoded in
UTF-8."
+ for build, text in ((lambda: F.lit(value), message % value),
+ (lambda: F.col("id") == value, message % value),
+ (lambda: F.lit([value]), message % value),
+ (lambda: F.lit(long_value), message % long_value),
+ (lambda: spark.sql("SELECT :x", args={"x": value}),
message % value),
+ (lambda: spark.sql("SELECT ?", args=[value]), message
% value)):
+ with pytest.raises(ValueError) as error:
+ build()
+ assert type(error.value) is ValueError and str(error.value) == text
+ assert service.execute_requests == []
+
+
+def
test_pandas_timestamp_literals_drop_their_nanoseconds_silently_as_pyspark(mock_connect):
+ # As PySpark's TimestampType.toInternal and TimestampNTZType.toInternal,
which read the
+ # fields of a pandas Timestamp: its nanoseconds are dropped without the
warning of
+ # Timestamp.to_pydatetime, and the literal is that of the datetime of its
microseconds.
+ import warnings
+
+ pd = pytest.importorskip("pandas")
+ from pyspark.sql import functions as F
+
+ spark, service = mock_connect
+
+ def literal(column):
+ spark.range(1).select(column).collect()
+ # Project.expressions=3; Expression.literal=1; Literal.timestamp=17,
timestamp_ntz=18.
+ plan =
parse_message(parse_message(service.execute_requests[-1])[3][0])[1][0]
+ expression =
parse_message(parse_message(parse_message(plan)[3][0])[3][0])
+ return parse_message(expression[1][0])
+
+ seoul = datetime.timezone(datetime.timedelta(hours=9))
+ for timestamp_type in ("TIMESTAMP_LTZ", "TIMESTAMP_NTZ"):
+ service.confs = {"spark.sql.timestampType": timestamp_type}
+ for value in (pd.Timestamp("2020-01-01 00:00:00.123456789"),
+ pd.Timestamp("2020-01-01 00:00:00.123456789",
tz="Asia/Seoul")):
+ micros = value.to_pydatetime(warn=False)
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ column = F.lit(value)
+ assert literal(column) == literal(F.lit(micros))
+ assert literal(F.lit(pd.Timestamp("2020-01-01 09:00:00.5", tz=seoul))) == {
+ 18: [1577869200500000]}
+
+
+def
test_transform_asserts_that_the_function_returned_a_dataframe_as_pyspark(mock_connect):
+ # As PySpark's DataFrame.transform, which asserts that the function
returned a DataFrame.
+ spark, _ = mock_connect
+ df = spark.range(1)
+ for result in (1, None, [df]):
+ with pytest.raises(AssertionError) as error:
+ df.transform(lambda frame, value=result: value)
+ assert str(error.value) == (
+ f"Func returned an instance of type [{type(result)!r}], should
have been DataFrame.")
+ selected = df.select("id")
+ assert df.transform(lambda frame, other: other, selected) is selected
+
+
+def _collect_metrics_plan_ids(relation):
+ # Relation.common=1 (RelationCommon.plan_id=2), collect_metrics=29
(CollectMetrics.input=1,
+ # name=2): the plan ID of each CollectMetrics of the relation, by its name.
+ fields = parse_message(relation)
+ if 29 not in fields:
+ return {}
+ metrics = parse_message(fields[29][0])
+ ids = _collect_metrics_plan_ids(metrics[1][0])
+ ids[metrics[2][0].decode()] = parse_message(fields[1][0])[2][0]
+ return ids
+
+
+def
test_metrics_that_pyspark_cannot_convert_fail_the_action_of_their_observation_as_pyspark(
+ mock_connect):
+ # As PySpark's client, which converts the metrics of the Observations of a
plan as they
+ # arrive: the first one of a kind that LiteralExpression._to_value does
not convert (a
+ # year-month interval) raises UNSUPPORTED_LITERAL, of the text of its
literal, from the
+ # action, and neither its metrics nor those that come after it are set.
Metrics observed by
+ # a name are not converted by the action.
+ import pyarrow as pa
+
+ 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")))
+ 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])
+
+ def observed(name, literal, key):
+ # ExecutePlanResponse.observed_metrics=6 -> ObservedMetrics name=1,
values=2, keys=3,
+ # plan_id=4.
+ return message_field(6, message_field(1, name) + message_field(2,
literal)
+ + message_field(3, key) + varint_field(4,
ids[name]))
+
+ # Literal.long=7, year_month_interval=20.
+ count, interval = varint_field(7, 3), varint_field(20, 14)
+ # The rows of the result, for count: ExecutePlanResponse.arrow_batch=2
(ArrowBatch.row_count=1,
+ # data=2).
+ 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()))
+ for action in (df.collect, df.count, lambda: list(df.toLocalIterator())):
+ service.execute_payload = (batch + observed("second", interval, "m")
+ + observed("first", count, "c"))
+ with pytest.raises(PySparkTypeError) as error:
+ action()
+ assert error.value.getCondition() == "UNSUPPORTED_LITERAL"
+ assert error.value.getMessageParameters() == {"literal":
"year_month_interval: 14\n"}
+ assert first.get == {} and second.get == {}
+ # The metrics that come before the first that is not converted are set.
+ service.execute_payload = observed("first", count, "c") +
observed("second", interval, "m")
+ with pytest.raises(PySparkTypeError):
+ df.collect()
+ assert first.get == {"c": 3} and second.get == {}
+ service.execute_payload = message_field(6, message_field(1, "named")
+ + message_field(2, interval) +
message_field(3, "m"))
+ named = spark.range(3).observe("named", F.max("id").alias("m"))
+ assert named.collect() == []
+ with pytest.raises(PySparkTypeError):
+ named.executionInfo.flows
+
+
+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.
+ from pyspark.errors import PySparkValueError
+
+ for name in ("timestamp_ntz(9)", "timestamp_ltz(7)"):
+ field = {"name": "t", "type": name, "nullable": True, "metadata": {}}
+ for parse in (lambda: T._parse_datatype_json_value(name),
+ lambda: T._parse_datatype_json_string(json.dumps(name)),
+ lambda: T.StructType.fromJson({"type": "struct",
"fields": [field]}),
+ lambda: T.StructField.fromJson(field),
+ lambda: T.ArrayType.fromJson(
+ {"type": "array", "elementType": name,
"containsNull": True}),
+ lambda: T.StructType().add("t", name)):
+ with pytest.raises(PySparkValueError) as error:
+ parse()
+ assert error.value.getCondition() == "CANNOT_PARSE_DATATYPE"
+ assert error.value.getMessageParameters() == {"msg": name}
+ assert T._parse_datatype_json_value("timestamp_ntz") ==
T.TimestampNTZType()
+ assert not hasattr(T, "TimestampNTZNanosType") and not hasattr(T,
"TimestampLTZNanosType")
+
+
+def
test_local_iterators_call_the_progress_handlers_in_next_whatever_the_prefetch_as_pyspark(
+ mock_connect):
+ # As PySpark Connect's toLocalIterator, which ignores prefetchPartitions:
the progress of
+ # the execution reaches the handlers as next() reads it, on the iterating
thread, so that
+ # the exception of a handler is raised by next().
+ import threading
+
+ spark, service = mock_connect
+ # ExecutePlanResponse.execution_progress=18 -> ExecutionProgress.stages=1
(StageInfo
+ # stage_id=1, num_tasks=2), num_inflight_tasks=2.
+ stage = varint_field(1, 7) + varint_field(2, 4)
+ service.execute_payload = message_field(18, message_field(1, stage) +
varint_field(2, 3))
+ threads = []
+
+ def handler(**kwargs):
+ threads.append((threading.get_ident(), kwargs["done"]))
+
+ spark.registerProgressHandler(handler)
+ for prefetch in (False, True):
+ threads.clear()
+ assert list(spark.range(1).toLocalIterator(prefetch)) == []
+ assert threads == [(threading.get_ident(), False),
(threading.get_ident(), True)]
+ spark.clearProgressHandlers()
+
+ def failing(**kwargs):
+ if not kwargs["done"]:
+ raise ZeroDivisionError("update")
+
+ spark.registerProgressHandler(failing)
+ with pytest.raises(ZeroDivisionError):
+ next(spark.range(1).toLocalIterator(prefetchPartitions=True))
+ spark.clearProgressHandlers()
+
+
+def
test_is_streaming_is_empty_and_input_files_are_asked_once_per_dataframe_as_pyspark(
+ mock_connect):
+ # As PySpark's isStreaming (a cached_property), isEmpty and inputFiles
(functools.cache): a
+ # DataFrame asks the server once, and keeps the answer after the session
stopped.
+ import pyarrow as pa
+
+ spark, service = mock_connect
+ table = pa.table({"count(1)": pa.array([1], pa.int64())})
+ sink = pa.BufferOutputStream()
+ with pa.ipc.new_stream(sink, table.schema) as writer:
+ writer.write_table(table)
+ # ExecutePlanResponse.schema=7, arrow_batch=2 (ArrowBatch.row_count=1,
data=2).
+ service.execute_payload = message_field(7, struct_schema("count(1)")) +
message_field(
+ 2, varint_field(1, 1) + message_field(2, sink.getvalue().to_pybytes()))
+ df = spark.range(1)
+ try:
+ assert df.isStreaming is False
+ service.streaming = True
+ assert df.isStreaming is False
+ finally:
+ service.streaming = False
+ assert df.isEmpty() is False and df.isEmpty() is False
+ assert df.inputFiles() == [] and df.inputFiles() == []
+ # base.proto: AnalyzePlanRequest.is_streaming=8, input_files=9.
+ asked = [field for request in service.analyze_requests for field in
parse_message(request)]
+ assert (asked.count(8), asked.count(9), len(service.execute_requests)) ==
(1, 1, 1)
+ spark.stop()
+ assert df.isStreaming is False and df.isEmpty() is False and
df.inputFiles() == []
+
+
@pytest.mark.parametrize("cls,name,descriptor", [
(_SS, "version", "getset_descriptor"),
(_ConnectDF, "dtypes", "getset_descriptor"),
@@ -14838,23 +15109,22 @@ def
test_functions_are_of_the_builtin_module_and_pickle_by_reference_as_pyspark(
assert CloudPickleSerializer().loads(payload)(None) == (sort, col, udf,
F.abs)
-def test_timestamp_nanos_types_roundtrip_and_pickle():
+def test_timestamp_nanos_types_are_private_types_of_their_own():
# Spark's TimestampNTZNanosType/TimestampLTZNanosType (precision 7..9)
materialize as
- # their own types, not as TimeType / a microsecond TimestampType.
- for cls, name in ((T.TimestampNTZNanosType, "timestamp_ntz"),
- (T.TimestampLTZNanosType, "timestamp_ltz")):
+ # their own types, not as TimeType / a microsecond TimestampType. PySpark
has no such
+ # classes, so they are not names of pyspark.sql.types.
+ from pyspark._pyspark import TimestampLTZNanosType, TimestampNTZNanosType
+
+ for cls, name in ((TimestampNTZNanosType, "timestamp_ntz"),
+ (TimestampLTZNanosType, "timestamp_ltz")):
t = cls(8)
assert t.precision == 8
assert t.simpleString() == t.typeName() == f"{name}(8)"
assert t.json() == f'"{name}(8)"'
assert cls().precision == 9
assert isinstance(t, T.DatetimeType)
- assert repr(pickle.loads(pickle.dumps(t))) == repr(t)
- assert repr(T._parse_datatype_json_string(f'"{name}(7)"')) ==
repr(cls(7))
with pytest.raises(ValueError):
cls(6)
- nested = T.StructType([T.StructField("a",
T.ArrayType(T.TimestampLTZNanosType(9)))])
- assert pickle.loads(pickle.dumps(nested)).simpleString() ==
"struct<a:array<timestamp_ltz(9)>>"
@pytest.mark.parametrize("call,expected", [
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]