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 91d3ca42 [SPARK-61590][CONNECT][PYTHON] Raise PySpark's errors for
bools and out-of-range ints in bucketBy counts, window frame bounds and
StorageLevel, in the Python client
91d3ca42 is described below
commit 91d3ca4242a9ac96cf26bb06b35217064c862c29
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 08:51:11 2026 +0900
[SPARK-61590][CONNECT][PYTHON] Raise PySpark's errors for bools and
out-of-range ints in bucketBy counts, window frame bounds and StorageLevel, in
the Python client
### What changes were proposed in this pull request?
A follow-up of #571 (SPARK-61542), for the counts and values that it left:
`bucketBy`, the bounds of `Window.rowsBetween`/`rangeBetween`, and
`StorageLevel`. PySpark 4.3.0 stores these as given, and protobuf's default upb
backend converts them when the plan is built. On protobuf 7.34+, which a fresh
install of `pyspark-client` 4.3.0 gets, a bool in an int field raises
`TypeError: Field spark.connect.<Msg>.<field>: Expected an int, got a
boolean.`, and an int out of the field's range r [...]
**`DataFrameWriter.bucketBy`.** PySpark checks only that `numBuckets` is an
int (a bool included) at the call. Its `WriteOperation` sends the bucketing at
the write only for a count above 0. Now:
- `bucketBy(True, ...)` raises the `TypeError` of `BucketBy.num_buckets` at
the write, before any request. It used to send 1 bucket.
- `2**40` raises `Value out of range: 1099511627776` at the write. It used
to raise PyO3's `OverflowError` at `bucketBy`.
- A count of 0 or less (`False` included) sends no bucketing, and the last
`bucketBy` wins. It used to send `BucketBy{0}`.
- Every write raises these errors: `save`, `saveAsTable`, `insertInto`,
`jdbc` and the format writers, each time.
- The core gets `DataFrameWriter::clear_bucket_by`.
**Window frame bounds.** These follow PySpark's order. The comparisons with
`Window._PRECEDING_THRESHOLD` and `_FOLLOWING_THRESHOLD` come first, so an
incomparable type raises Python's `TypeError`, such as `'<=' not supported
between instances of 'str' and 'int'`. Then come the `isinstance(int)`
assertions of `WindowFrame`, a bare `AssertionError` for `np.int64`, a float or
a `Decimal`. Then the proto conversion:
- A row frame's `True` raises the `TypeError` of `Literal.integer`, and a
range frame's that of `Literal.long`. Both used to be taken as 1.
- `False` is the current row.
- A range bound beyond a long raises `Value out of range`.
- These used to raise "frame bound must be an int or FrameBound", or
`OverflowError`.
- `rangeBetween(..., Window.unboundedPreceding)` sends the long -2**63 as
PySpark does. It used to send -2**63+1.
As before, these errors are raised at the call, where PySpark raises the
conversion's errors when it builds the plan.
**`StorageLevel`.** As PySpark's, it stores its five values as given, with
no checks (`StorageLevel(1.5, 'x', None, 0, 2**40)`). They are plain
attributes, its `repr`, `str` and `==` are PySpark's, and it pickles as
PySpark's does. `persist`, `localCheckpoint` and `cacheTable` convert it as
PySpark's `storage_level_to_proto`:
- a non-`StorageLevel` raises `AssertionError`;
- a flag goes through upb's bool conversion, and a `None` flag or
replication is left unset;
- a bool replication raises `Field spark.connect.StorageLevel.replication:
Expected an int, got a boolean.`
- `cacheTable` sends no level for a false one, as PySpark's `if
self._storage_level:`.
It used to raise PyO3's errors at construction.
**`sampleBy`'s seed** now uses the shared `proto_int`, with no change in
behavior except one corner: an out-of-range seed of an int subclass with its
own `__str__` shows its value, as PySpark's does.
### Why are the changes needed?
To match PySpark 4.3.0 with protobuf 7. Probes of these cases against
official `pyspark-client` 4.3.0 on protobuf 7.36.2 (upb) now match line for
line: about 230 lines for the window bounds and about 165 for `StorageLevel`.
The remaining differences come from PyO3, such as type names in messages and
pickle protocols 0 and 1.
### Does this PR introduce _any_ user-facing change?
Yes, in the Python client. `bucketBy`, the window frame bounds and
`StorageLevel` take and refuse the values that PySpark takes and refuses, with
PySpark's errors at the same points. In the Rust API,
`DataFrameWriter::clear_bucket_by` is added.
### How was this patch tested?
- New tests, which fail without the change:
- `test_writer_bucket_counts_are_set_at_the_write_as_pyspark`
-
`test_window_frame_bounds_are_compared_asserted_and_converted_as_pyspark`
- `test_storage_levels_keep_their_values_as_pyspark`
- `test_storage_levels_are_converted_as_pyspark`
-
`test_sample_by_seeds_of_int_subclasses_are_set_as_protobuf_does_as_pyspark`
- `v1_write_clear_bucket_by_sends_no_bucketing` (Rust)
- The lib tests of both crates (857 passed), the Rust integration tests
against a local Spark 4.3.0 server (998 passed, 26 ignored), the build of all
tests with `wasm-udf`, the offline Python suites (3269 passed, 8 skipped), and
the live drop-in, Arrow and ML suites (310 and 51 passed), on master with
SPARK-61590 and SPARK-61591 applied. `cargo fmt --all --check` and the no-stub
audit pass.
### 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 #582 from HyukjinKwon/SPARK-61590-int-bool.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/catalog.rs | 13 +-
crates/pyspark-rs/src/dataframe.rs | 74 +++++++-
crates/pyspark-rs/src/readwriter.rs | 45 ++++-
crates/pyspark-rs/src/stat.rs | 17 +-
crates/pyspark-rs/src/storagelevel.rs | 306 ++++++++++++++++++++++-----------
crates/pyspark-rs/src/streaming.rs | 51 +++---
crates/pyspark-rs/src/window.rs | 197 ++++++++++++++-------
crates/spark-connect/src/readwriter.rs | 39 +++++
docs/compatibility.md | 4 +
python/tests/test_dropin_offline.py | 277 +++++++++++++++++++++++++++++
10 files changed, 804 insertions(+), 219 deletions(-)
diff --git a/crates/pyspark-rs/src/catalog.rs b/crates/pyspark-rs/src/catalog.rs
index b1819950..f4c629e9 100644
--- a/crates/pyspark-rs/src/catalog.rs
+++ b/crates/pyspark-rs/src/catalog.rs
@@ -323,7 +323,9 @@ impl PyCatalog {
///
/// A supplied pyspark `StorageLevel` is mapped onto the `spark.connect`
/// `CacheTable.storage_level` field (the same field layout
`DataFrame.persist` uses);
- /// `None` leaves it unset so the server default applies.
+ /// `None` leaves it unset so the server default applies. As PySpark's
`CacheTable`, which
+ /// converts a storage level that is true (`if self._storage_level:`), any
false value, such
+ /// as 0, leaves it unset too, and another true value fails the assertion
of the conversion.
#[pyo3(signature = (tableName, storageLevel=None))]
fn cacheTable(
&self,
@@ -331,9 +333,12 @@ impl PyCatalog {
tableName: &str,
storageLevel: Option<&Bound<'_, PyAny>>,
) -> PyResult<()> {
- let level = storageLevel
- .map(crate::storagelevel::storage_level_proto)
- .transpose()?;
+ let level = match storageLevel {
+ Some(level) if level.is_truthy()? => {
+ Some(crate::storagelevel::storage_level_proto(level)?)
+ }
+ _ => None,
+ };
self.detached(py, |catalog| {
{ catalog.cache_table_with_storage_level(tableName, level)
}.map_err(Box::new)
})
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index 23ff8543..8da79f26 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -2754,9 +2754,7 @@ impl PyDataFrame {
/// The V1 writer interface (`df.write`).
#[getter]
fn write(&self) -> PyDataFrameWriter {
- PyDataFrameWriter {
- inner: WriterState::new(self.dataframe.write()),
- }
+ PyDataFrameWriter::new(self.dataframe.write())
}
/// The V2 writer interface (`df.writeTo("table")`).
@@ -3561,9 +3559,42 @@ impl PyWhenNotMatchedBySource {
)]
pub struct PyDataFrameWriter {
inner: WriterState<spark_connect::readwriter::DataFrameWriter>,
+ /// The `numBuckets` of the last `bucketBy` when it is a positive count
that the proto
+ /// refuses, which PySpark keeps and fails each write with, as its
`WriteOperation.command`
+ /// sets it in the proto; the core writer then has no bucketing.
+ refused_bucket_count: std::sync::Mutex<Option<Py<PyAny>>>,
}
-impl PyDataFrameWriter {}
+impl PyDataFrameWriter {
+ pub(crate) fn new(writer: spark_connect::readwriter::DataFrameWriter) ->
Self {
+ PyDataFrameWriter {
+ inner: WriterState::new(writer),
+ refused_bucket_count: std::sync::Mutex::new(None),
+ }
+ }
+
+ fn refused_bucket_count(&self) -> std::sync::MutexGuard<'_,
Option<Py<PyAny>>> {
+ self.refused_bucket_count
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ }
+
+ /// Fail a write of a bucket count that the proto refuses, as PySpark's
+ /// `WriteOperation.command`, which sets the count after the input plan
and before the path,
+ /// the table name and the save mode, so before any request; each write
fails again.
+ fn check_bucket_count(&self, py: Python<'_>) -> PyResult<()> {
+ let refused = self
+ .refused_bucket_count()
+ .as_ref()
+ .map(|n| n.clone_ref(py));
+ match refused {
+ Some(num_buckets) => {
+
crate::readwriter::check_refused_bucket_count(num_buckets.bind(py))
+ }
+ None => Ok(()),
+ }
+ }
+}
/// Apply the shared `format` / `mode` / `partitionBy` / `**options` arguments
that
/// reference `DataFrameWriter.save` and `.saveAsTable` accept inline,
mirroring
@@ -3673,11 +3704,28 @@ impl PyDataFrameWriter {
col: &Bound<'_, PyAny>,
cols: Vec<Bound<'_, PyAny>>,
) -> PyResult<Bound<'py, Self>> {
+ use crate::readwriter::BucketCount;
+
let num_buckets = crate::readwriter::bucket_count(numBuckets)?;
let columns = crate::readwriter::writer_columns(col, &cols)?;
- slf.borrow()
- .inner
- .update(|w| w.bucket_by(num_buckets, columns));
+ // As PySpark's, the last call wins: a count that is not positive, or
one that the
+ // proto refuses, leaves no bucketing of an earlier call on the writer.
+ let writer = slf.borrow();
+ let refused = match num_buckets {
+ BucketCount::Count(count) => {
+ writer.inner.update(|w| w.bucket_by(count, columns));
+ None
+ }
+ BucketCount::Unsent => {
+ writer.inner.update(|w| w.clear_bucket_by());
+ None
+ }
+ BucketCount::Refused(count) => {
+ writer.inner.update(|w| w.clear_bucket_by());
+ Some(count.unbind())
+ }
+ };
+ *writer.refused_bucket_count() = refused;
Ok(slf.clone())
}
@@ -3752,6 +3800,7 @@ impl PyDataFrameWriter {
}
w = w.option("url", url).option("dbtable", table);
self.inner.set(w.clone());
+ self.check_bucket_count(py)?;
interruptible(py, &w.spark_session(), ||
w.save(None).map_err(Box::new))
}
@@ -3768,8 +3817,9 @@ impl PyDataFrameWriter {
) -> PyResult<()> {
let w = apply_write_common(self.inner.get(), format, mode,
partitionBy, options)?;
// PySpark sets the inline format/mode/partitionBy/options on the
writer itself, before
- // it checks the path.
+ // its command sets the bucket count and then the path.
self.inner.set(w.clone());
+ self.check_bucket_count(py)?;
let path = path.map(crate::readwriter::writer_path).transpose()?;
interruptible(py, &w.spark_session(), || {
w.save(path.as_deref()).map_err(Box::new)
@@ -3789,6 +3839,7 @@ impl PyDataFrameWriter {
) -> PyResult<()> {
let w = apply_write_common(self.inner.get(), format, mode,
partitionBy, options)?;
self.inner.set(w.clone());
+ self.check_bucket_count(py)?;
interruptible(py, &w.spark_session(), || {
w.save_as_table(name).map_err(Box::new)
})
@@ -3809,6 +3860,7 @@ impl PyDataFrameWriter {
}
// PySpark sets the overwrite/append mode on the writer itself.
self.inner.set(w.clone());
+ self.check_bucket_count(py)?;
interruptible(py, &w.spark_session(), || {
w.insert_into(tableName).map_err(Box::new)
})
@@ -3841,6 +3893,7 @@ impl PyDataFrameWriter {
w = set_option_skip_none(w, "compression", compression)?;
// PySpark sets the mode/options/format on the writer itself, then
saves.
self.inner.set(w.clone().format("parquet"));
+ self.check_bucket_count(py)?;
let path = crate::readwriter::writer_path(path)?;
interruptible(py, &w.spark_session(), || {
w.parquet(&path).map_err(Box::new)
@@ -3880,6 +3933,7 @@ impl PyDataFrameWriter {
)?;
// PySpark sets the mode/options/format on the writer itself, then
saves.
self.inner.set(w.clone().format("json"));
+ self.check_bucket_count(py)?;
let path = crate::readwriter::writer_path(path)?;
interruptible(py, &w.spark_session(), ||
w.json(&path).map_err(Box::new))
}
@@ -3937,6 +3991,7 @@ impl PyDataFrameWriter {
)?;
// PySpark sets the mode/options/format on the writer itself, then
saves.
self.inner.set(w.clone().format("csv"));
+ self.check_bucket_count(py)?;
let path = crate::readwriter::writer_path(path)?;
interruptible(py, &w.spark_session(), ||
w.csv(&path).map_err(Box::new))
}
@@ -3968,6 +4023,7 @@ impl PyDataFrameWriter {
w = set_option_skip_none(w, "compression", compression)?;
// PySpark sets the mode/options/format on the writer itself, then
saves.
self.inner.set(w.clone().format("orc"));
+ self.check_bucket_count(py)?;
let path = crate::readwriter::writer_path(path)?;
interruptible(py, &w.spark_session(), ||
w.orc(&path).map_err(Box::new))
}
@@ -3987,6 +4043,7 @@ impl PyDataFrameWriter {
w = set_options_skip_none(w, &[("compression", compression),
("lineSep", lineSep)])?;
// PySpark sets the mode/options/format on the writer itself, then
saves.
self.inner.set(w.clone().format("text"));
+ self.check_bucket_count(py)?;
let path = crate::readwriter::writer_path(path)?;
interruptible(py, &w.spark_session(), ||
w.text(&path).map_err(Box::new))
}
@@ -4036,6 +4093,7 @@ impl PyDataFrameWriter {
)?;
// PySpark sets the mode/options/format on the writer itself, then
saves.
self.inner.set(w.clone().format("xml"));
+ self.check_bucket_count(py)?;
let path = crate::readwriter::writer_path(path)?;
interruptible(py, &w.spark_session(), ||
w.xml(&path).map_err(Box::new))
}
diff --git a/crates/pyspark-rs/src/readwriter.rs
b/crates/pyspark-rs/src/readwriter.rs
index a66a2618..a6727b18 100644
--- a/crates/pyspark-rs/src/readwriter.rs
+++ b/crates/pyspark-rs/src/readwriter.rs
@@ -156,13 +156,44 @@ pub(crate) fn writer_columns(
.collect()
}
-/// The number of buckets of `df.write.bucketBy`, an int, as PySpark's.
-pub(crate) fn bucket_count(num_buckets: &Bound<'_, PyAny>) -> PyResult<i32> {
- if num_buckets.is_instance_of::<pyo3::types::PyInt>() {
- num_buckets.extract()
- } else {
- Err(not_expected_type(num_buckets, "numBuckets", "int"))
- }
+/// The int32 field of the number of buckets, which PySpark sets at the write.
+const BUCKET_COUNT_FIELD: &str =
"spark.connect.WriteOperation.BucketBy.num_buckets";
+
+/// The number of buckets of `df.write.bucketBy`, as PySpark's: `bucketBy`
checks that it is an
+/// int, a bool included, and keeps it, and the `WriteOperation` of each write
sends the bucketing
+/// only of a count above 0, which it then sets in the int32 field.
+pub(crate) enum BucketCount<'py> {
+ /// A count that is not positive: no bucketing is sent.
+ Unsent,
+ /// The count of the buckets.
+ Count(i32),
+ /// A positive count that the int32 field refuses, a bool or an int beyond
its range, with
+ /// which each write fails, as [`check_refused_bucket_count`] raises.
+ Refused(Bound<'py, PyAny>),
+}
+
+/// The [`BucketCount`] of `num_buckets`, else `NOT_EXPECTED_TYPE` of an
argument that is not an
+/// int, as PySpark's `bucketBy` raises at the call.
+pub(crate) fn bucket_count<'py>(num_buckets: &Bound<'py, PyAny>) ->
PyResult<BucketCount<'py>> {
+ if !num_buckets.is_instance_of::<pyo3::types::PyInt>() {
+ return Err(not_expected_type(num_buckets, "numBuckets", "int"));
+ }
+ if !num_buckets.gt(0)? {
+ return Ok(BucketCount::Unsent);
+ }
+ Ok(
+ match crate::stat_arguments::proto_int::<i32>(num_buckets,
BUCKET_COUNT_FIELD) {
+ Ok(count) => BucketCount::Count(count),
+ Err(_) => BucketCount::Refused(num_buckets.clone()),
+ },
+ )
+}
+
+/// Set a count of [`BucketCount::Refused`] in the int32 field again, as
PySpark's
+/// `WriteOperation.command` does at each write, which fails with the error of
protobuf's default
+/// (upb) backend: the `TypeError` of a bool and the `ValueError` of an int
out of the range.
+pub(crate) fn check_refused_bucket_count(num_buckets: &Bound<'_, PyAny>) ->
PyResult<()> {
+ crate::stat_arguments::proto_int::<i32>(num_buckets,
BUCKET_COUNT_FIELD).map(|_| ())
}
/// A reader `schema` as pyspark's `DataFrameReader.schema` and
`DataStreamReader.schema`
diff --git a/crates/pyspark-rs/src/stat.rs b/crates/pyspark-rs/src/stat.rs
index 9a34c5dc..01692559 100644
--- a/crates/pyspark-rs/src/stat.rs
+++ b/crates/pyspark-rs/src/stat.rs
@@ -5,7 +5,6 @@ use spark_connect::group::StatFunctions;
use crate::dataframe::{python_random_seed, PyDataFrame};
use crate::errors::ResultExt;
-use crate::session::value_out_of_range;
/// Python wrapper for DataFrame statistical functions.
#[pyclass(
@@ -181,21 +180,15 @@ pub(crate) fn sample_by_arguments(
}
/// The seed of `sampleBy`, drawn from Python's `random` when there is none.
As PySpark's
-/// `StatSampleBy` asserts an int, any other type is a bare `AssertionError`.
A bool, which is an
-/// int, is refused by the proto, and an int out of the range of a long is a
`ValueError`.
+/// `StatSampleBy` asserts an int, any other type is a bare `AssertionError`.
The int is then set
+/// in the long field of the proto, which refuses a bool, which is an int, and
an int out of the
+/// range of a long, as [`crate::stat_arguments::proto_int`] converts it.
pub(crate) fn sample_by_seed(py: Python<'_>, seed: Option<&Bound<'_, PyAny>>)
-> PyResult<i64> {
- use pyo3::types::{PyBool, PyInt};
-
let Some(seed) = seed else {
return python_random_seed(py);
};
- if !seed.is_instance_of::<PyInt>() {
+ if !seed.is_instance_of::<pyo3::types::PyInt>() {
return Err(pyo3::exceptions::PyAssertionError::new_err(()));
}
- if seed.is_instance_of::<PyBool>() {
- return Err(crate::stat_arguments::bool_not_proto_int(
- "spark.connect.StatSampleBy.seed",
- ));
- }
- seed.extract::<i64>().map_err(|_| value_out_of_range(seed))
+ crate::stat_arguments::proto_int(seed, "spark.connect.StatSampleBy.seed")
}
diff --git a/crates/pyspark-rs/src/storagelevel.rs
b/crates/pyspark-rs/src/storagelevel.rs
index 4157dce4..494f6a72 100644
--- a/crates/pyspark-rs/src/storagelevel.rs
+++ b/crates/pyspark-rs/src/storagelevel.rs
@@ -1,167 +1,277 @@
//! `pyspark.storagelevel.StorageLevel` — Rust-backed flags for DataFrame/RDD
storage.
+use pyo3::basic::CompareOp;
use pyo3::prelude::*;
+use pyo3::types::{PyBool, PyDict, PyString, PyTuple};
+
+/// The int32 field of the replication of the proto, which PySpark sets at the
conversion.
+const REPLICATION_FIELD: &str = "spark.connect.StorageLevel.replication";
/// Flags controlling storage of a persisted DataFrame (disk/memory/off-heap,
-/// (de)serialized, replication). Mirrors `pyspark.storagelevel.StorageLevel`.
+/// (de)serialized, replication). Mirrors `pyspark.storagelevel.StorageLevel`,
a plain Python
+/// class: its constructor keeps the five values as they are, unchecked, as
plain attributes of
+/// the instance, which may be set and deleted, a subclass may override
`__init__`, and an
+/// instance copies, and pickles of protocol 2 or more (those of `copy`,
`pickle` and
+/// cloudpickle), as an instance of that class does, by its attributes. As
PySpark's, it is
+/// unhashable, as it defines `__eq__`.
#[pyclass(
name = "StorageLevel",
module = "pyspark.storagelevel",
- get_all,
- from_py_object
+ dict,
+ subclass,
+ weakref
)]
-#[derive(Clone)]
-pub struct PyStorageLevel {
- pub useDisk: bool,
- pub useMemory: bool,
- pub useOffHeap: bool,
- pub deserialized: bool,
- pub replication: i32,
+pub struct PyStorageLevel {}
+
+/// The `replication` argument of the constructor, where PySpark tells an
omitted replication,
+/// which is 1, apart from a given one, which it keeps as it is, None included.
+pub enum Replication {
+ Omitted,
+ Given(Py<PyAny>),
}
-impl PyStorageLevel {
- fn mk(
- use_disk: bool,
- use_memory: bool,
- use_off_heap: bool,
- deserialized: bool,
- replication: i32,
- ) -> Self {
- PyStorageLevel {
- useDisk: use_disk,
- useMemory: use_memory,
- useOffHeap: use_off_heap,
- deserialized,
- replication,
- }
+impl<'a, 'py> FromPyObject<'a, 'py> for Replication {
+ type Error = PyErr;
+
+ fn extract(obj: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
+ Ok(Replication::Given(obj.to_owned().unbind()))
+ }
+}
+
+/// Set the attributes of a StorageLevel to `values`, in the order of the
constructor, as
+/// PySpark's `__init__` assigns them.
+fn set_attributes<'py>(level: &Bound<'py, PyAny>, values: [Bound<'py, PyAny>;
5]) -> PyResult<()> {
+ let names = [
+ "useDisk",
+ "useMemory",
+ "useOffHeap",
+ "deserialized",
+ "replication",
+ ];
+ for (name, value) in names.into_iter().zip(values) {
+ level.setattr(name, value)?;
}
+ Ok(())
}
-/// The proto of a pyspark `StorageLevel`, of its flags, as PySpark's
`storage_level_to_proto`
-/// reads them: of `DataFrame.persist`, `localCheckpoint` and
`Catalog.cacheTable`.
+/// A class constant of PySpark's StorageLevel, of these flags and replication.
+fn constant(
+ py: Python<'_>,
+ use_disk: bool,
+ use_memory: bool,
+ use_off_heap: bool,
+ deserialized: bool,
+ replication: i32,
+) -> PyResult<Py<PyStorageLevel>> {
+ let level = Bound::new(py, PyStorageLevel {})?;
+ let flag = |value: bool| PyBool::new(py, value).to_owned().into_any();
+ set_attributes(
+ level.as_any(),
+ [
+ flag(use_disk),
+ flag(use_memory),
+ flag(use_off_heap),
+ flag(deserialized),
+ replication.into_pyobject(py)?.into_any(),
+ ],
+ )?;
+ Ok(level.unbind())
+}
+
+/// The value of a bool field of `pb2.StorageLevel(...)`, as protobuf's
default (upb) backend
+/// converts a keyword argument: None leaves the field unset, and any other
value is converted
+/// as [`crate::streaming::proto_bool`] does.
+fn flag_field(value: &Bound<'_, PyAny>) -> PyResult<bool> {
+ if value.is_none() {
+ Ok(false)
+ } else {
+ crate::streaming::proto_bool(value)
+ }
+}
+
+/// The proto of a pyspark `StorageLevel`, as PySpark's
`storage_level_to_proto` builds it, of
+/// `DataFrame.persist`, `localCheckpoint` and `Catalog.cacheTable`: it
asserts a StorageLevel,
+/// a bare `AssertionError` of anything else, reads the five attributes, and
passes them to
+/// `pb2.StorageLevel(use_disk=..., use_memory=..., use_off_heap=...,
deserialized=...,
+/// replication=...)`, which converts them in that order. A replication of
None is unset, and
+/// another is the int32 that [`crate::stat_arguments::proto_int`] converts.
pub(crate) fn storage_level_proto(
level: &Bound<'_, PyAny>,
) -> PyResult<spark_connect_proto::StorageLevel> {
+ if !level.is_instance_of::<PyStorageLevel>() {
+ return Err(pyo3::exceptions::PyAssertionError::new_err(()));
+ }
+ let use_disk = level.getattr("useDisk")?;
+ let use_memory = level.getattr("useMemory")?;
+ let use_off_heap = level.getattr("useOffHeap")?;
+ let deserialized = level.getattr("deserialized")?;
+ let replication = level.getattr("replication")?;
Ok(spark_connect_proto::StorageLevel {
- use_disk: level.getattr("useDisk")?.extract()?,
- use_memory: level.getattr("useMemory")?.extract()?,
- use_off_heap: level.getattr("useOffHeap")?.extract()?,
- deserialized: level.getattr("deserialized")?.extract()?,
- replication: level.getattr("replication")?.extract()?,
+ use_disk: flag_field(&use_disk)?,
+ use_memory: flag_field(&use_memory)?,
+ use_off_heap: flag_field(&use_off_heap)?,
+ deserialized: flag_field(&deserialized)?,
+ replication: if replication.is_none() {
+ 0
+ } else {
+ crate::stat_arguments::proto_int(&replication, REPLICATION_FIELD)?
+ },
})
}
#[pymethods]
impl PyStorageLevel {
+ /// As the `object.__new__` of PySpark's plain class: of any arguments,
which `__init__`
+ /// takes, so that a subclass of another `__init__` is built as it is in
PySpark. The class
+ /// shows the signature of `__init__`, as `inspect.signature` of PySpark's
class does.
#[new]
- #[pyo3(signature = (useDisk, useMemory, useOffHeap, deserialized,
replication=1))]
+ #[pyo3(
+ signature = (*_args, **_kwargs),
+ text_signature = "(useDisk, useMemory, useOffHeap, deserialized,
replication=1)"
+ )]
+ fn new(_args: &Bound<'_, PyTuple>, _kwargs: Option<&Bound<'_, PyDict>>) ->
Self {
+ PyStorageLevel {}
+ }
+
+ /// As PySpark's `__init__`, which keeps the values as they are, of any
type.
+ #[pyo3(signature = (useDisk, useMemory, useOffHeap, deserialized,
replication=Replication::Omitted))]
#[allow(non_snake_case)]
- fn new(
- useDisk: bool,
- useMemory: bool,
- useOffHeap: bool,
- deserialized: bool,
- replication: i32,
- ) -> Self {
- PyStorageLevel::mk(useDisk, useMemory, useOffHeap, deserialized,
replication)
- }
-
- fn __repr__(&self) -> String {
- format!(
- "StorageLevel({}, {}, {}, {}, {})",
- py_bool(self.useDisk),
- py_bool(self.useMemory),
- py_bool(self.useOffHeap),
- py_bool(self.deserialized),
- self.replication
+ fn __init__<'py>(
+ slf: &Bound<'py, Self>,
+ useDisk: Bound<'py, PyAny>,
+ useMemory: Bound<'py, PyAny>,
+ useOffHeap: Bound<'py, PyAny>,
+ deserialized: Bound<'py, PyAny>,
+ replication: Replication,
+ ) -> PyResult<()> {
+ let py = slf.py();
+ let replication = match replication {
+ Replication::Omitted => 1i32.into_pyobject(py)?.into_any(),
+ Replication::Given(replication) => replication.into_bound(py),
+ };
+ set_attributes(
+ slf.as_any(),
+ [useDisk, useMemory, useOffHeap, deserialized, replication],
)
}
- fn __str__(&self) -> String {
- let mut r = String::new();
- if self.useDisk {
- r.push_str("Disk ");
- }
- if self.useMemory {
- r.push_str("Memory ");
- }
- if self.useOffHeap {
- r.push_str("OffHeap ");
+ /// As PySpark's `"StorageLevel(%s, %s, %s, %s, %s)" % (...)` of the five
attributes.
+ fn __repr__<'py>(slf: &Bound<'py, Self>) -> PyResult<Bound<'py, PyAny>> {
+ let py = slf.py();
+ let values = PyTuple::new(
+ py,
+ [
+ slf.getattr("useDisk")?,
+ slf.getattr("useMemory")?,
+ slf.getattr("useOffHeap")?,
+ slf.getattr("deserialized")?,
+ slf.getattr("replication")?,
+ ],
+ )?;
+ PyString::new(py, "StorageLevel(%s, %s, %s, %s, %s)").rem(values)
+ }
+
+ /// As PySpark's: the names of the flags that are true, and `"%sx
Replicated" %` the
+ /// replication.
+ fn __str__<'py>(slf: &Bound<'py, Self>) -> PyResult<Bound<'py, PyAny>> {
+ let py = slf.py();
+ let mut result = String::new();
+ for (name, shown) in [
+ ("useDisk", "Disk "),
+ ("useMemory", "Memory "),
+ ("useOffHeap", "OffHeap "),
+ ] {
+ if slf.getattr(name)?.is_truthy()? {
+ result.push_str(shown);
+ }
}
- r.push_str(if self.deserialized {
+ result.push_str(if slf.getattr("deserialized")?.is_truthy()? {
"Deserialized "
} else {
"Serialized "
});
- r.push_str(&format!("{}x Replicated", self.replication));
- r
+ let replicated = PyString::new(py, "%sx
Replicated").rem(slf.getattr("replication")?)?;
+ PyString::new(py, &result).add(replicated)
}
- fn __eq__(&self, other: &PyStorageLevel) -> bool {
- self.useDisk == other.useDisk
- && self.useMemory == other.useMemory
- && self.useOffHeap == other.useOffHeap
- && self.deserialized == other.deserialized
- && self.replication == other.replication
+ /// As PySpark's: False of another object, else `self.useMemory ==
other.useMemory and
+ /// self.useDisk == other.useDisk and ...`, whose `and` gives the first
comparison that is
+ /// not true, or else the last one, as they are.
+ fn __eq__<'py>(
+ slf: &Bound<'py, Self>,
+ other: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, PyAny>> {
+ if !other.is_instance_of::<PyStorageLevel>() {
+ return Ok(PyBool::new(slf.py(), false).to_owned().into_any());
+ }
+ let compare = |name: &str| {
+ slf.getattr(name)?
+ .rich_compare(other.getattr(name)?, CompareOp::Eq)
+ };
+ for name in ["useMemory", "useDisk", "useOffHeap", "deserialized"] {
+ let equal = compare(name)?;
+ if !equal.is_truthy()? {
+ return Ok(equal);
+ }
+ }
+ compare("replication")
+ }
+
+ /// The arguments of `copyreg.__newobj__`, none, so that an instance
pickles and copies as
+ /// one of PySpark's plain class does: the class, and its attributes as
its state.
+ fn __getnewargs__<'py>(&self, py: Python<'py>) -> Bound<'py, PyTuple> {
+ PyTuple::empty(py)
}
// Preset levels (class attributes), matching pyspark.
#[classattr]
#[allow(non_snake_case)]
- fn NONE() -> PyStorageLevel {
- PyStorageLevel::mk(false, false, false, false, 1)
+ fn NONE(py: Python<'_>) -> PyResult<Py<PyStorageLevel>> {
+ constant(py, false, false, false, false, 1)
}
#[classattr]
#[allow(non_snake_case)]
- fn DISK_ONLY() -> PyStorageLevel {
- PyStorageLevel::mk(true, false, false, false, 1)
+ fn DISK_ONLY(py: Python<'_>) -> PyResult<Py<PyStorageLevel>> {
+ constant(py, true, false, false, false, 1)
}
#[classattr]
#[allow(non_snake_case)]
- fn DISK_ONLY_2() -> PyStorageLevel {
- PyStorageLevel::mk(true, false, false, false, 2)
+ fn DISK_ONLY_2(py: Python<'_>) -> PyResult<Py<PyStorageLevel>> {
+ constant(py, true, false, false, false, 2)
}
#[classattr]
#[allow(non_snake_case)]
- fn DISK_ONLY_3() -> PyStorageLevel {
- PyStorageLevel::mk(true, false, false, false, 3)
+ fn DISK_ONLY_3(py: Python<'_>) -> PyResult<Py<PyStorageLevel>> {
+ constant(py, true, false, false, false, 3)
}
#[classattr]
#[allow(non_snake_case)]
- fn MEMORY_ONLY() -> PyStorageLevel {
- PyStorageLevel::mk(false, true, false, false, 1)
+ fn MEMORY_ONLY(py: Python<'_>) -> PyResult<Py<PyStorageLevel>> {
+ constant(py, false, true, false, false, 1)
}
#[classattr]
#[allow(non_snake_case)]
- fn MEMORY_ONLY_2() -> PyStorageLevel {
- PyStorageLevel::mk(false, true, false, false, 2)
+ fn MEMORY_ONLY_2(py: Python<'_>) -> PyResult<Py<PyStorageLevel>> {
+ constant(py, false, true, false, false, 2)
}
#[classattr]
#[allow(non_snake_case)]
- fn MEMORY_AND_DISK() -> PyStorageLevel {
- PyStorageLevel::mk(true, true, false, false, 1)
+ fn MEMORY_AND_DISK(py: Python<'_>) -> PyResult<Py<PyStorageLevel>> {
+ constant(py, true, true, false, false, 1)
}
#[classattr]
#[allow(non_snake_case)]
- fn MEMORY_AND_DISK_2() -> PyStorageLevel {
- PyStorageLevel::mk(true, true, false, false, 2)
+ fn MEMORY_AND_DISK_2(py: Python<'_>) -> PyResult<Py<PyStorageLevel>> {
+ constant(py, true, true, false, false, 2)
}
#[classattr]
#[allow(non_snake_case)]
- fn OFF_HEAP() -> PyStorageLevel {
- PyStorageLevel::mk(true, true, true, false, 1)
+ fn OFF_HEAP(py: Python<'_>) -> PyResult<Py<PyStorageLevel>> {
+ constant(py, true, true, true, false, 1)
}
#[classattr]
#[allow(non_snake_case)]
- fn MEMORY_AND_DISK_DESER() -> PyStorageLevel {
- PyStorageLevel::mk(true, true, false, true, 1)
- }
-}
-
-fn py_bool(b: bool) -> &'static str {
- if b {
- "True"
- } else {
- "False"
+ fn MEMORY_AND_DISK_DESER(py: Python<'_>) -> PyResult<Py<PyStorageLevel>> {
+ constant(py, true, true, false, true, 1)
}
}
diff --git a/crates/pyspark-rs/src/streaming.rs
b/crates/pyspark-rs/src/streaming.rs
index f29ca539..5bbf5774 100644
--- a/crates/pyspark-rs/src/streaming.rs
+++ b/crates/pyspark-rs/src/streaming.rs
@@ -1135,33 +1135,36 @@ impl<'a, 'py> FromPyObject<'a, 'py> for ProtoBool {
}
impl ProtoBool {
- /// The bool of the argument, false when it is omitted, as protobuf's
default (upb) backend
- /// converts it for a bool field: a NumPy bool by its truth, a NumPy array
is protobuf's
- /// `TypeError`, and any other object is read as a C long, true when it is
not 0, which raises
- /// the `TypeError` of an object that is not an int, and the
`OverflowError` of an int that a
- /// C long cannot hold.
+ /// The bool of the argument, false when it is omitted, as [`proto_bool`]
converts it.
pub(crate) fn value(&self, py: Python<'_>) -> PyResult<bool> {
- let Some(obj) = &self.0 else {
- return Ok(false);
- };
- let obj = obj.bind(py);
- let typ = obj.get_type();
- let module = typ.module().ok();
- if module.is_some_and(|module| module.to_cow().is_ok_and(|module|
module == "numpy")) {
- let name = typ.name()?;
- let name = name.to_cow()?;
- if name == "ndarray" {
- return Err(pyo3::exceptions::PyTypeError::new_err(format!(
- "{} has type ndarray, but expected one of: bool",
- obj.str()?
- )));
- }
- if name == "bool" {
- return obj.is_truthy();
- }
+ match &self.0 {
+ Some(obj) => proto_bool(obj.bind(py)),
+ None => Ok(false),
+ }
+ }
+}
+
+/// The bool of `obj`, as protobuf's default (upb) backend converts it for a
bool field: a NumPy
+/// bool by its truth, a NumPy array is protobuf's `TypeError`, and any other
object is read as a
+/// C long, true when it is not 0, which raises the `TypeError` of an object
that is not an int,
+/// and the `OverflowError` of an int that a C long cannot hold.
+pub(crate) fn proto_bool(obj: &Bound<'_, PyAny>) -> PyResult<bool> {
+ let typ = obj.get_type();
+ let module = typ.module().ok();
+ if module.is_some_and(|module| module.to_cow().is_ok_and(|module| module
== "numpy")) {
+ let name = typ.name()?;
+ let name = name.to_cow()?;
+ if name == "ndarray" {
+ return Err(pyo3::exceptions::PyTypeError::new_err(format!(
+ "{} has type ndarray, but expected one of: bool",
+ obj.str()?
+ )));
+ }
+ if name == "bool" {
+ return obj.is_truthy();
}
- Ok(obj.extract::<std::os::raw::c_long>()? != 0)
}
+ Ok(obj.extract::<std::os::raw::c_long>()? != 0)
}
/// The command of the function of `foreach` or `foreachBatch`, as PySpark's:
of
diff --git a/crates/pyspark-rs/src/window.rs b/crates/pyspark-rs/src/window.rs
index 6e0dbe37..fc90f4c2 100644
--- a/crates/pyspark-rs/src/window.rs
+++ b/crates/pyspark-rs/src/window.rs
@@ -87,76 +87,137 @@ impl PyFrameBound {
const UNBOUNDED_PRECEDING: i64 = i64::MIN;
const UNBOUNDED_FOLLOWING: i64 = i64::MAX;
-/// Resolve a frame-bound argument, the `start` of a frame if `start`, else
its end: a plain
-/// int (negative=preceding/positive=following) or a `FrameBound`. As PySpark's
-/// `rowsBetween` and `rangeBetween`, a start of `-sys.maxsize` or less is
unbounded preceding
-/// and an end of `sys.maxsize` or more unbounded following, also of a float,
such as
-/// `float("-inf")` and `float("inf")`, while a start of
`Window.unboundedFollowing` or an end of
+/// The literal fields of the boundary of a value, which PySpark's
`WindowExpression` sets: an
+/// int32 in a row frame, and a long in a range frame.
+const ROW_BOUNDARY_FIELD: &str = "spark.connect.Expression.Literal.integer";
+const RANGE_BOUNDARY_FIELD: &str = "spark.connect.Expression.Literal.long";
+
+/// A frame-bound argument once compared with the threshold of its side: a
`FrameBound` as it
+/// is, the unbounded bound of its side past the threshold, or else the value
of the argument.
+enum FrameArgument<'a, 'py> {
+ Bound(FrameBound),
+ Value(&'a Bound<'py, PyAny>),
+}
+
+/// The frame-bound argument `v`, the start of a frame if `start`, else its
end, compared as
+/// PySpark's `rowsBetween` and `rangeBetween` compare it, with Python's `<=`
and `>=`: a start of
+/// `Window._PRECEDING_THRESHOLD` (`-sys.maxsize`) or less is unbounded
preceding and an end of
+/// `Window._FOLLOWING_THRESHOLD` (`sys.maxsize`) or more unbounded following,
of any type, so
+/// also of a float such as `float("inf")`, and a type that does not compare
with an int raises
+/// the `TypeError` of the comparison. A start of `Window.unboundedFollowing`
or an end of
/// `Window.unboundedPreceding` is a value.
-fn to_frame_bound(v: &Bound<'_, PyAny>, start: bool) -> PyResult<FrameBound> {
+fn compared_frame_argument<'a, 'py>(
+ v: &'a Bound<'py, PyAny>,
+ start: bool,
+) -> PyResult<FrameArgument<'a, 'py>> {
if let Ok(fb) = v.extract::<PyFrameBound>() {
- return Ok(fb.bound);
+ return Ok(FrameArgument::Bound(fb.bound));
}
- if !v.is_instance_of::<pyo3::types::PyInt>() {
- if v.is_instance_of::<pyo3::types::PyFloat>() {
- // As PySpark's: a bound past the threshold of its side is
unbounded, and
- // WindowFrame asserts that another is an int.
- if start && v.le(-i64::MAX)? {
- return Ok(FrameBound::UnboundedPreceding);
- }
- if !start && v.ge(i64::MAX)? {
- return Ok(FrameBound::UnboundedFollowing);
+ if start && v.le(-i64::MAX)? {
+ return Ok(FrameArgument::Bound(FrameBound::UnboundedPreceding));
+ }
+ if !start && v.ge(i64::MAX)? {
+ return Ok(FrameArgument::Bound(FrameBound::UnboundedFollowing));
+ }
+ Ok(FrameArgument::Value(v))
+}
+
+/// The bound of the offset `n`: a negative one is preceding, and a positive
one following. The
+/// offset of `Window.unboundedPreceding`, as the end of a range frame, is a
following one, as
+/// the count of the rows that it precedes is beyond a long.
+fn frame_bound_of(n: i64) -> FrameBound {
+ match n {
+ 0 => FrameBound::CurrentRow,
+ n if n > 0 => FrameBound::Following(n),
+ n => n
+ .checked_neg()
+ .map_or(FrameBound::Following(n), FrameBound::Preceding),
+ }
+}
+
+/// PySpark's `VALUE_NOT_BETWEEN` of the boundary `name` of a row frame beyond
an int32.
+fn boundary_not_between(py: Python<'_>, name: &str) -> PyErr {
+ crate::column::raise_pyspark(
+ py,
+ "PySparkValueError",
+ "VALUE_NOT_BETWEEN",
+ &[
+ ("arg_name", name),
+ ("min", &i32::MIN.to_string()),
+ ("max", &i32::MAX.to_string()),
+ ],
+ )
+}
+
+/// The bound `name` of a frame argument, as the plan of PySpark's
`WindowExpression` converts
+/// it, in a row frame if `rows`, else in a range frame: an int of 0 (False
too) is the current
+/// row; a row frame sets any other int of an int32 in the int32 literal,
which protobuf's default
+/// (upb) backend refuses of a bool, and raises `VALUE_NOT_BETWEEN` of an int
beyond an int32;
+/// and a range frame sets it in the long literal, which refuses a bool and an
int beyond a long,
+/// as [`crate::stat_arguments::proto_int`] does. A `FrameBound` of a row
frame is checked as
+/// such an int.
+fn converted_frame_bound(
+ py: Python<'_>,
+ argument: FrameArgument<'_, '_>,
+ name: &str,
+ rows: bool,
+) -> PyResult<FrameBound> {
+ let value = match argument {
+ FrameArgument::Bound(bound) => {
+ let offset = match &bound {
+ FrameBound::Preceding(n) => Some(n.saturating_neg()),
+ FrameBound::Following(n) => Some(*n),
+ _ => None,
+ };
+ if rows && offset.is_some_and(|n| i32::try_from(n).is_err()) {
+ return Err(boundary_not_between(py, name));
}
- return Err(pyo3::exceptions::PyAssertionError::new_err(()));
+ return Ok(bound);
}
- return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(
- "frame bound must be an int or FrameBound",
- ));
- }
- let n: i64 = match v.extract() {
- Ok(n) => n,
- // An int beyond a long is past the thresholds of its side, or else
out of range.
- Err(_) if start && v.lt(0)? => return
Ok(FrameBound::UnboundedPreceding),
- Err(_) if !start && v.gt(0)? => return
Ok(FrameBound::UnboundedFollowing),
- Err(err) => return Err(err),
+ FrameArgument::Value(value) => value,
};
- Ok(match n {
- n if start && n <= -i64::MAX => FrameBound::UnboundedPreceding,
- n if !start && n == i64::MAX => FrameBound::UnboundedFollowing,
- 0 => FrameBound::CurrentRow,
- n if n < 0 =>
FrameBound::Preceding(n.checked_neg().unwrap_or(i64::MAX)),
- n => FrameBound::Following(n),
- })
+ let long = value.extract::<i64>().ok();
+ if long == Some(0) {
+ return Ok(FrameBound::CurrentRow);
+ }
+ if !rows {
+ return crate::stat_arguments::proto_int::<i64>(value,
RANGE_BOUNDARY_FIELD)
+ .map(frame_bound_of);
+ }
+ match long.and_then(|n| i32::try_from(n).ok()) {
+ Some(_) if value.is_instance_of::<pyo3::types::PyBool>() => Err(
+ crate::stat_arguments::bool_not_proto_int(ROW_BOUNDARY_FIELD),
+ ),
+ Some(n) => Ok(frame_bound_of(n.into())),
+ None => Err(boundary_not_between(py, name)),
+ }
}
-/// The bounds of a row frame, as PySpark's, whose plan raises
`VALUE_NOT_BETWEEN` for a
-/// boundary of a value that is not an int.
-fn row_frame_bounds(
+/// The bounds of `rowsBetween(start, end)` if `rows`, else of
`rangeBetween(start, end)`, a
+/// plain int (negative is preceding, positive following) or a `FrameBound`
each, as PySpark's:
+/// it compares the start and then the end with the thresholds of their sides,
and WindowFrame
+/// then asserts that the start and then the end that is not past its
threshold is an int (a
+/// bool included), a bare `AssertionError` of a NumPy int, a float or a
Decimal. The errors of
+/// the plan, which converts the start and then the end, are raised here,
after those.
+fn frame_bounds(
py: Python<'_>,
start: &Bound<'_, PyAny>,
end: &Bound<'_, PyAny>,
+ rows: bool,
) -> PyResult<(FrameBound, FrameBound)> {
- let bounds = (to_frame_bound(start, true)?, to_frame_bound(end, false)?);
- for (name, bound) in [("start", &bounds.0), ("end", &bounds.1)] {
- let value = match bound {
- FrameBound::Preceding(n) => n.saturating_neg(),
- FrameBound::Following(n) => *n,
- _ => continue,
- };
- if i32::try_from(value).is_err() {
- return Err(crate::column::raise_pyspark(
- py,
- "PySparkValueError",
- "VALUE_NOT_BETWEEN",
- &[
- ("arg_name", name),
- ("min", &i32::MIN.to_string()),
- ("max", &i32::MAX.to_string()),
- ],
- ));
+ let start = compared_frame_argument(start, true)?;
+ let end = compared_frame_argument(end, false)?;
+ for argument in [&start, &end] {
+ if let FrameArgument::Value(value) = argument {
+ if !value.is_instance_of::<pyo3::types::PyInt>() {
+ return Err(pyo3::exceptions::PyAssertionError::new_err(()));
+ }
}
}
- Ok(bounds)
+ Ok((
+ converted_frame_bound(py, start, "start", rows)?,
+ converted_frame_bound(py, end, "end", rows)?,
+ ))
}
#[pymethods]
@@ -214,7 +275,7 @@ impl PyWindowSpec {
start: &Bound<'_, PyAny>,
end: &Bound<'_, PyAny>,
) -> PyResult<PyWindowSpec> {
- let (start, end) = row_frame_bounds(py, start, end)?;
+ let (start, end) = frame_bounds(py, start, end, true)?;
let new_spec = self.spec.clone().rows_between(start, end);
Ok(PyWindowSpec::new(new_spec))
}
@@ -222,13 +283,12 @@ impl PyWindowSpec {
/// Define a RANGE frame between start and end bounds (ints or
FrameBounds).
fn rangeBetween(
&self,
+ py: Python<'_>,
start: &Bound<'_, PyAny>,
end: &Bound<'_, PyAny>,
) -> PyResult<PyWindowSpec> {
- let new_spec = self
- .spec
- .clone()
- .range_between(to_frame_bound(start, true)?, to_frame_bound(end,
false)?);
+ let (start, end) = frame_bounds(py, start, end, false)?;
+ let new_spec = self.spec.clone().range_between(start, end);
Ok(PyWindowSpec::new(new_spec))
}
@@ -335,7 +395,7 @@ impl PyWindow {
start: &Bound<'_, PyAny>,
end: &Bound<'_, PyAny>,
) -> PyResult<PyWindowSpec> {
- let (start, end) = row_frame_bounds(py, start, end)?;
+ let (start, end) = frame_bounds(py, start, end, true)?;
Ok(PyWindowSpec::new(
WindowSpec::new().rows_between(start, end),
))
@@ -343,10 +403,15 @@ impl PyWindow {
/// Create a WindowSpec with a RANGE frame between the given bounds.
#[staticmethod]
- fn rangeBetween(start: &Bound<'_, PyAny>, end: &Bound<'_, PyAny>) ->
PyResult<PyWindowSpec> {
- let spec = WindowSpec::new()
- .range_between(to_frame_bound(start, true)?, to_frame_bound(end,
false)?);
- Ok(PyWindowSpec::new(spec))
+ fn rangeBetween(
+ py: Python<'_>,
+ start: &Bound<'_, PyAny>,
+ end: &Bound<'_, PyAny>,
+ ) -> PyResult<PyWindowSpec> {
+ let (start, end) = frame_bounds(py, start, end, false)?;
+ Ok(PyWindowSpec::new(
+ WindowSpec::new().range_between(start, end),
+ ))
}
fn __repr__(&self) -> String {
diff --git a/crates/spark-connect/src/readwriter.rs
b/crates/spark-connect/src/readwriter.rs
index 43ccbfef..22e05ce3 100644
--- a/crates/spark-connect/src/readwriter.rs
+++ b/crates/spark-connect/src/readwriter.rs
@@ -412,6 +412,15 @@ impl DataFrameWriter {
self
}
+ /// Unset the bucketing specification, so that the write sends none, as
PySpark's
+ /// `bucketBy` of a count that is not positive does: its `WriteOperation`
sends the
+ /// bucketing only of a count above 0, and the last `bucketBy` wins.
+ pub fn clear_bucket_by(mut self) -> Self {
+ self.num_buckets = None;
+ self.bucket_cols.clear();
+ self
+ }
+
/// Set the sort columns.
pub fn sort_by<S: Into<String>>(mut self, cols: impl IntoIterator<Item =
S>) -> Self {
self.sort_cols = cols.into_iter().map(Into::into).collect();
@@ -964,6 +973,36 @@ mod tests {
assert_eq!(bucket_by.bucket_column_names, vec!["col1"]);
}
+ #[test]
+ fn v1_write_clear_bucket_by_sends_no_bucketing() {
+ // As PySpark's `bucketBy` of a count that is not positive after
another: the last call
+ // wins, and the write sends no bucketing, while the sort columns stay.
+ let spark = session();
+ let df = spark.range(3).unwrap();
+ let path = || {
+ Some(proto::write_operation::SaveType::Path(
+ "/tmp/out".to_string(),
+ ))
+ };
+ let writer = df
+ .write()
+ .bucket_by(4, vec!["col1"])
+ .sort_by(vec!["col1"])
+ .clear_bucket_by();
+ let op = writer.build_write_operation(path()).unwrap();
+ assert_eq!(op.bucket_by, None);
+ assert_eq!(op.sort_column_names, vec!["col1"]);
+ let op = writer
+ .bucket_by(2, vec!["col2"])
+ .build_write_operation(path())
+ .unwrap();
+ let bucket_by = op.bucket_by.unwrap();
+ assert_eq!(
+ (bucket_by.num_buckets, bucket_by.bucket_column_names),
+ (2, vec!["col2".to_string()])
+ );
+ }
+
#[test]
fn v1_write_sort_by() {
let spark = session();
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 1c33c9ce..bd6a8910 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -158,6 +158,10 @@ two runs, were equal. For reproducible values, use the
`_with_seed` variants
(`rand_with_seed(42)`, `uuid_with_seed(lit(42))`, ...). `random` and
`random_with_seed` are added as the aliases of `rand` that PySpark has.
+`DataFrameWriter::clear_bucket_by` is added: it unsets the bucketing of a
writer, so that
+its write sends none, as PySpark's `bucketBy` of a count that is not positive,
the last
+`bucketBy` winning. `bucket_by` is unchanged and sends the count it is given.
+
## Native LogisticRegression
The native `spark_connect::ml::LogisticRegression` fits Spark's JVM
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 83e6e9ba..8fe1936c 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -842,6 +842,57 @@ def test_storage_level():
assert StorageLevel.DISK_ONLY != StorageLevel.MEMORY_ONLY
+def test_storage_levels_keep_their_values_as_pyspark():
+ # As PySpark's StorageLevel, a plain Python class: its constructor keeps
the values as they
+ # are, unchecked, in attributes that may be set; repr shows the str() of
each, str the names
+ # of the flags that are true, and == compares the values with those of
another
+ # StorageLevel, and is False of anything else; it is unhashable, a
subclass may override
+ # __init__, and an instance pickles and copies by its attributes. The
class shows the
+ # signature of its __init__.
+ import copy
+ import inspect
+
+ from pyspark.storagelevel import StorageLevel
+
+ level = StorageLevel(1.5, "x", None, 0, 2**40)
+ assert vars(level) == {"useDisk": 1.5, "useMemory": "x", "useOffHeap":
None,
+ "deserialized": 0, "replication": 2**40}
+ assert repr(level) == "StorageLevel(1.5, x, None, 0, 1099511627776)"
+ assert str(level) == "Disk Memory Serialized 1099511627776x Replicated"
+ level.useMemory, level.replication = 0, "2"
+ assert (repr(level), str(level)) == ("StorageLevel(1.5, 0, None, 0, 2)",
+ "Disk Serialized 2x Replicated")
+ assert StorageLevel(useDisk=1, useMemory=0, useOffHeap=0,
deserialized=0).replication == 1
+ assert StorageLevel(1, 0, 0, 0) == StorageLevel.DISK_ONLY
+ assert StorageLevel(1, 0, 0, 0, 2.0) == StorageLevel.DISK_ONLY_2
+ assert StorageLevel(1, 0, 0, 0, 3) != StorageLevel.DISK_ONLY_2
+ assert (StorageLevel.DISK_ONLY == (True, False, False, False, 1)) is False
+ assert StorageLevel.DISK_ONLY != 1
+ assert StorageLevel.OFF_HEAP is StorageLevel.OFF_HEAP
+ assert repr(StorageLevel.MEMORY_AND_DISK_DESER) == "StorageLevel(True,
True, False, True, 1)"
+ assert str(StorageLevel.OFF_HEAP) == "Disk Memory OffHeap Serialized 1x
Replicated"
+ with pytest.raises(TypeError, match="unhashable type"):
+ hash(StorageLevel.DISK_ONLY)
+ with pytest.raises(TypeError, match=r"__init__\(\) missing 1 required
positional argument: "
+ r"'deserialized'$"):
+ StorageLevel(True, True, True)
+ parameters = inspect.signature(StorageLevel).parameters
+ assert list(parameters) == ["useDisk", "useMemory", "useOffHeap",
"deserialized",
+ "replication"]
+ assert parameters["replication"].default == 1
+
+ class Replicated(StorageLevel):
+ def __init__(self, replication):
+ super().__init__(True, False, False, False, replication)
+
+ assert Replicated(2) == StorageLevel.DISK_ONLY_2 and
isinstance(Replicated(2), StorageLevel)
+ for copied in (pickle.loads(pickle.dumps(level)), copy.copy(level),
copy.deepcopy(level)):
+ assert type(copied) is StorageLevel and copied is not level
+ assert vars(copied) == vars(level)
+ copied = copy.copy(Replicated(3))
+ assert type(copied) is Replicated and copied == StorageLevel.DISK_ONLY_3
+
+
def test_dataframe_plot_is_the_plot_accessor_of_pyspark():
# As PySpark's DataFrame.plot: the PySparkPlotAccessor of
pyspark.sql.plot, of the
# DataFrame itself.
@@ -916,6 +967,69 @@ def
test_persist_cache_and_unpersist_return_the_dataframe_itself_as_pyspark(mock
assert df.unpersist(blocking=True) is df
+def test_storage_levels_are_converted_as_pyspark(mock_connect):
+ # As PySpark's storage_level_to_proto, of persist, localCheckpoint and
cacheTable: it asserts
+ # a StorageLevel, a bare AssertionError of anything else, reads its
attributes, and passes
+ # them to pb2.StorageLevel(...), whose default (upb) backend converts them
in their order:
+ # None is unset, a flag is the truth of an int, of a NumPy bool too, and
the int32
+ # replication refuses a bool and an int beyond its range, before any
request. cacheTable
+ # converts a storage level that is true, so another false value is unset,
as None is.
+ from pyspark.storagelevel import StorageLevel
+
+ spark, service = mock_connect
+ df = spark.range(1)
+
+ def sent_level():
+ # AnalyzePlanRequest.persist=14 -> Persist.storage_level=2:
use_disk=1, use_memory=2,
+ # use_off_heap=3, deserialized=4 and replication=5, where false and 0
are not sent.
+ persist =
parse_message(parse_message(service.analyze_requests[-1])[14][0])
+ return parse_message(persist[2][0])
+
+ df.persist(StorageLevel(2, np.int64(1), None, np.bool_(False),
np.int32(3)))
+ assert sent_level() == {1: [1], 2: [1], 5: [3]}
+ df.persist(StorageLevel(-1, 0, 2**62, True, None))
+ assert sent_level() == {1: [1], 3: [1], 4: [1]}
+
+ class Level:
+ useDisk, useMemory, useOffHeap, deserialized, replication = True,
False, False, False, 1
+
+ # The attributes are read before any of them is converted.
+ unread = StorageLevel(1.5, True, True, True)
+ del unread.replication
+ boolean = "Field spark.connect.StorageLevel.replication: Expected an int,
got a boolean."
+ requests = (len(service.analyze_requests), len(service.execute_requests))
+ for level, error, message in [
+ (Level(), AssertionError, "^$"),
+ ((True, False, False, False, 1), AssertionError, "^$"),
+ (unread, AttributeError, "object has no attribute 'replication'$"),
+ (StorageLevel(1.5, True, True, True), TypeError,
+ "^'float' object cannot be interpreted as an integer$"),
+ (StorageLevel(True, "x", True, True, True), TypeError,
+ "^'str' object cannot be interpreted as an integer$"),
+ (StorageLevel(True, True, 2**63, True), OverflowError,
+ "^Python int too large to convert to C long$"),
+ (StorageLevel(True, True, True, np.array([1])), TypeError,
+ r"^\[1\] has type ndarray, but expected one of: bool$"),
+ (StorageLevel(True, True, None, True, False), TypeError,
f"^{re.escape(boolean)}$"),
+ (StorageLevel(True, True, True, True, 2**31), ValueError,
+ "^Value out of range: 2147483648$"),
+ (StorageLevel(True, True, True, True, 1.0), TypeError,
+ "^'float' object cannot be interpreted as an integer$")]:
+ for call in (lambda: df.persist(level),
+ lambda: df.localCheckpoint(storageLevel=level),
+ lambda: spark.catalog.cacheTable("t", level)):
+ with pytest.raises(error, match=message) as e:
+ call()
+ assert type(e.value) is error
+ assert (len(service.analyze_requests), len(service.execute_requests)) ==
requests
+ for level in (None, 0, "", False):
+ spark.catalog.cacheTable("t", level)
+ # Relation.catalog=200 -> Catalog.cache_table=19: table_name=1 and
storage_level=2.
+ assert _sent_catalog(service.execute_requests[-1], 19) == {1: [b"t"]}
+ spark.catalog.cacheTable("t", StorageLevel(0, 1, 0, 0))
+ assert parse_message(_sent_catalog(service.execute_requests[-1],
19)[2][0]) == {2: [1], 5: [1]}
+
+
# ---------------------------------------------------------------------------
session builder
def test_session_builder_chaining_offline():
@@ -11941,6 +12055,31 @@ def
test_seeds_that_pyspark_cannot_send_are_refused_as_pyspark(mock_connect):
assert df.sampleBy("id", {0: 1.0}, -(2**63)) is not None
+def
test_sample_by_seeds_of_int_subclasses_are_set_as_protobuf_does_as_pyspark(mock_connect):
+ # As PySpark's StatSampleBy, which sets its seed, an int, in the long
field of the proto:
+ # protobuf's default (upb) backend takes the int of an int subclass, and
the ValueError of
+ # one out of the range of a long shows that int, not the str() of the
subclass.
+ spark, service = mock_connect
+ df = spark.range(10)
+
+ class Seed(int):
+ def __str__(self):
+ return "seed"
+
+ __repr__ = __str__
+
+ for call in (df.sampleBy, df.stat.sampleBy):
+ for seed, shown in ((Seed(2**63), "9223372036854775808"),
+ (Seed(-(2**63) - 1), "-9223372036854775809")):
+ with pytest.raises(ValueError) as error:
+ call("id", {0: 0.5}, seed)
+ assert str(error.value) == f"Value out of range: {shown}"
+ # Relation.sample_by=107 -> StatSampleBy.seed=5.
+ df.sampleBy("id", {0: 1.0}, Seed(5)).collect()
+ plan =
parse_message(parse_message(service.execute_requests[-1])[3][0])[1][0]
+ assert parse_message(parse_message(plan)[107][0])[5] == [5]
+
+
def
test_with_metadata_and_pivot_refer_to_their_column_through_the_dataframe_as_pyspark(
mock_connect):
# As PySpark's withMetadata (self[columnName]) and pivot
(self._df[pivot_col]): the column
@@ -18778,6 +18917,83 @@ def
test_window_frames_and_columns_are_checked_as_pyspark():
assert repr(Window.partitionBy(["a", "b"])) == "WindowSpec(PartitionBy(a,
b))"
+def test_window_frame_bounds_are_compared_asserted_and_converted_as_pyspark():
+ # As PySpark's rowsBetween and rangeBetween: they compare the start and
then the end with the
+ # thresholds of their sides, with Python's <= and >=, whose TypeError a
type that does not
+ # compare with an int raises; WindowFrame then asserts that the start and
then the end that
+ # is not past its threshold is an int, a bare AssertionError of a NumPy
int or a Decimal;
+ # and the plan converts the start and then the end, whose errors are
raised at the call: 0,
+ # False too, is the current row, a row frame sets an int of an int32 in
the integer literal,
+ # and a range frame any other int in the long literal, both of which
protobuf's default
+ # (upb) backend refuses of a bool, and the long of an int beyond a long.
+ from pyspark.errors import PySparkValueError
+ from pyspark.sql import Window
+ from pyspark.sql import functions as F
+
+ o = Window.orderBy("id")
+
+ def bounds(spec):
+ frame = F.sum("a").over(spec)._expr.to_plan(None).window.frame_spec
+
+ def bound(boundary):
+ which = boundary.WhichOneof("boundary")
+ if which != "value":
+ return which
+ literal = boundary.value.literal
+ kind = literal.WhichOneof("literal_type")
+ return kind, getattr(literal, kind)
+
+ return bound(frame.lower), bound(frame.upper)
+
+ integer = "Field spark.connect.Expression.Literal.integer: Expected an
int, got a boolean."
+ long = "Field spark.connect.Expression.Literal.long: Expected an int, got
a boolean."
+ rows = (o.rowsBetween, Window.rowsBetween)
+ ranges = (o.rangeBetween, Window.rangeBetween)
+ for between in rows + ranges:
+ for start, end, message in [
+ ("1", 0, "'<=' not supported between instances of 'str' and
'int'"),
+ (None, "x", "'<=' not supported between instances of
'NoneType' and 'int'"),
+ (2.5, "x", "'>=' not supported between instances of 'str' and
'int'"),
+ (True, [], "'>=' not supported between instances of 'list' and
'int'")]:
+ with pytest.raises(TypeError) as error:
+ between(start, end)
+ assert str(error.value) == message
+ for start, end in [(np.int64(1), 0), (0, np.int64(1)),
(decimal.Decimal(1), 0),
+ (np.bool_(True), 0), (2**64, 1.5)]:
+ with pytest.raises(AssertionError) as error:
+ between(start, end)
+ assert type(error.value) is AssertionError and str(error.value) ==
""
+ assert bounds(between(False, False)) == ("current_row", "current_row")
+ # A NumPy int past its threshold is unbounded, as PySpark replaces it
by an int.
+ assert bounds(between(np.int64(-2**63), np.int64(2**63 - 1))) ==
("unbounded",) * 2
+ for between in rows:
+ assert bounds(between(-5, 2**31 - 1)) == (("integer", -5), ("integer",
2**31 - 1))
+ for start, end in [(True, 0), (0, True), (True, 2**40)]:
+ with pytest.raises(TypeError) as error:
+ between(start, end)
+ assert str(error.value) == integer
+ with pytest.raises(PySparkValueError) as error:
+ between(2**40, True)
+ assert error.value.getMessageParameters()["arg_name"] == "start"
+ for between in ranges:
+ assert bounds(between(-(2**31) - 1, 2**40)) == (("long", -(2**31) -
1), ("long", 2**40))
+ assert bounds(between(Window.unboundedFollowing,
Window.unboundedPreceding)) == (
+ ("long", 2**63 - 1), ("long", -(2**63)))
+ for start, end in [(True, 0), (0, True), (2**40, True)]:
+ with pytest.raises(TypeError) as error:
+ between(start, end)
+ assert str(error.value) == long
+ for start, end, shown in [(2**63, 0, "9223372036854775808"),
+ (0, -(2**63) - 1, "-9223372036854775809"),
+ (2**64, True, "18446744073709551616")]:
+ with pytest.raises(ValueError) as error:
+ between(start, end)
+ assert type(error.value) is ValueError
+ assert str(error.value) == f"Value out of range: {shown}"
+ assert repr(o.rangeBetween(0, Window.unboundedPreceding)) == (
+ "WindowSpec(OrderBy(id ASC NULLS FIRST), WindowFrame(RANGE_FRAME, 0,
-9223372036854775808))")
+
+
def test_expressions_carry_their_origins_as_pyspark():
# As PySpark's _with_origin: col() and the Column methods give the
expressions that they
# build the origin of their name and their call site in user code, as the
python_origin of
@@ -23081,6 +23297,67 @@ def
test_writer_bucket_sort_and_cluster_columns_are_checked_as_pyspark(offline_s
call()
+def test_writer_bucket_counts_are_set_at_the_write_as_pyspark(mock_connect):
+ # As PySpark's: bucketBy keeps an int, a bool included, and the
WriteOperation of each write
+ # sends the bucketing only of a count above 0, which it sets in the int32
num_buckets after
+ # the input plan, so a bool is the TypeError and an int beyond an int32
the ValueError of
+ # protobuf's default (upb) backend, before the path, the table name and
the save mode are
+ # checked, and before any request. The last bucketBy wins.
+ spark, service = mock_connect
+ df = spark.range(3)
+
+ def sent_bucket_by():
+ # ExecutePlanRequest.plan=3, Plan.command=2,
Command.write_operation=2, and
+ # WriteOperation.bucket_by=8: bucket_column_names=1 and num_buckets=2.
+ plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
+ write = parse_message(parse_message(plan[2][0])[2][0])
+ return [parse_message(bucket_by) for bucket_by in write.get(8, [])]
+
+ for count in (0, -1, False, -(2**31) - 1, -(2**64)):
+ df.write.bucketBy(count, "id").save("p")
+ assert sent_bucket_by() == []
+ df.write.bucketBy(4, "id").sortBy("id").bucketBy(0, "id").saveAsTable("t")
+ assert sent_bucket_by() == []
+ df.write.bucketBy(True, "id").bucketBy(2**31 - 1, ["id",
"x"]).insertInto("t")
+ assert sent_bucket_by() == [{1: [b"id", b"x"], 2: [2**31 - 1]}]
+
+ requests = len(service.execute_requests)
+ refused = [
+ (True, TypeError,
+ "Field spark.connect.WriteOperation.BucketBy.num_buckets: Expected an
int, got a boolean."),
+ (2**31, ValueError, "Value out of range: 2147483648"),
+ (2**64, ValueError, "Value out of range: 18446744073709551616"),
+ ]
+ writes = [
+ lambda w: w.save("p"),
+ lambda w: w.save(123),
+ lambda w: w.mode("bad").save("p"),
+ lambda w: w.saveAsTable("t", format="parquet"),
+ lambda w: w.insertInto("t", overwrite=True),
+ lambda w: w.jdbc("jdbc:x", "t"),
+ lambda w: w.parquet(123),
+ lambda w: w.json("p"),
+ lambda w: w.csv("p"),
+ lambda w: w.orc("p"),
+ lambda w: w.text("p"),
+ lambda w: w.xml("p", rowTag="r"),
+ ]
+ for count, error, message in refused:
+ for write in writes:
+ writer = df.write.bucketBy(4, "id").bucketBy(count, "id")
+ # Each write fails again, as PySpark's writer keeps the count.
+ for _ in range(2):
+ with pytest.raises(error) as e:
+ write(writer)
+ assert type(e.value) is error and str(e.value) == message
+ assert len(service.execute_requests) == requests
+ writer = df.write.bucketBy(True, "id")
+ with pytest.raises(TypeError):
+ writer.save("p")
+ writer.bucketBy(2, "id").save("p")
+ assert sent_bucket_by() == [{1: [b"id"], 2: [2]}]
+
+
def _sent_catalog(request, field):
# Relation.catalog=200 -> the Catalog operation `field`.
return parse_message(_sent_relation(request, 200, execute=True)[field][0])
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]