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 a5eb50a4 [SPARK-61596][CONNECT][PYTHON] Send no storage level for
persist(None) in the Python client, as PySpark does
a5eb50a4 is described below
commit a5eb50a4007d80234657d78433ce40ee77aca987
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 09:25:09 2026 +0900
[SPARK-61596][CONNECT][PYTHON] Send no storage level for persist(None) in
the Python client, as PySpark does
### What changes were proposed in this pull request?
PySpark's `DataFrame.persist(storageLevel)` defaults `storageLevel` to
`MEMORY_AND_DISK_DESER`, and when it is given `None` explicitly, its client
sends no storage level (`core.py`: `if kwargs.get("storage_level", None) is not
None`). The server then caches at its `spark.sql.defaultCacheStorageLevel`.
This PR does the same in the Python client:
- The core's `DataFrame::persist` takes `impl Into<Option<StorageLevel>>`.
Passing a `StorageLevel` works as before. `None` sends no storage level.
`cache` is unchanged.
- The drop-in's `persist` tells an omitted `storageLevel` apart from a
given `None`, using a `PersistLevel` argument, as the `StorageLevel`
constructor's `Replication` already does.
- `docs/compatibility.md`'s "Rust migration for the 4.3 line" describes the
new `persist` signature.
### Why are the changes needed?
For parity with PySpark 4.3.0. The client sent `MEMORY_AND_DISK_DESER` for
`persist(None)` too, so the server's default storage level was ignored:
```python
spark.conf.set("spark.sql.defaultCacheStorageLevel", "DISK_ONLY")
df = spark.range(5)
df.persist(None)
df.storageLevel
```
- PySpark 4.3.0: `StorageLevel(True, False, False, False, 1)` (DISK_ONLY,
the server default)
- Before: `StorageLevel(True, True, False, True, 1)` (MEMORY_AND_DISK_DESER)
- After: `StorageLevel(True, False, False, False, 1)`
`df.persist()` with no argument gives `MEMORY_AND_DISK_DESER` on both, as
before.
### Does this PR introduce _any_ user-facing change?
Yes. `persist(None)` now caches at the server's default storage level, as
in PySpark. In the Rust API, `DataFrame::persist` also accepts `None`.
### How was this patch tested?
- Offline: `test_persist_of_none_sends_no_storage_level_as_pyspark` checks
what omitted, `None` and `storageLevel=None`, and an explicit level send. It
fails without the fix, which sent `MEMORY_AND_DISK_DESER` for `None`.
- Core: `persist_of_no_storage_level_sends_none_as_pyspark`.
- e2e:
`test_persist_of_none_caches_at_the_default_storage_level_of_the_server_as_pyspark`,
against Spark 4.3.0 with `spark.sql.defaultCacheStorageLevel=DISK_ONLY`.
- A probe gives the same output on PySpark 4.3.0 and the client: omitted,
`None`, `storageLevel=None` and `MEMORY_ONLY`, plus the `AssertionError` of
`0`, `""`, `False` and a tuple.
- With `TZ=UTC` under the default (upb) protobuf backend:
- CI's offline set (`test_dropin_offline.py`, `test_arrow_handoff.py`,
`test_ml_offline.py`): 3273 passed.
- The Rust lib tests and the `--no-run` builds with and without
`wasm-udf`.
- `cargo fmt`, `scripts/audit_no_stubs.sh`, and ruff 0.14.0 `check` and
`format --check`.
### 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 #586 from HyukjinKwon/SPARK-61596-persist-none.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/dataframe.rs | 15 +++++------
crates/pyspark-rs/src/storagelevel.rs | 35 +++++++++++++++++++++++++
crates/spark-connect/src/dataframe.rs | 48 ++++++++++++++++++++++++++++++-----
docs/compatibility.md | 5 ++++
python/tests/test_dropin_e2e.py | 16 ++++++++++++
python/tests/test_dropin_offline.py | 22 ++++++++++++++++
6 files changed, 125 insertions(+), 16 deletions(-)
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index 8c8f0a97..2022abf9 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -2233,19 +2233,16 @@ impl PyDataFrame {
self.unpivot(ids, values, variableColumnName, valueColumnName)
}
- /// Persist the DataFrame at `storageLevel`, MEMORY_AND_DISK_DESER by
default, as
- /// PySpark's `DataFrame.persist()`.
- #[pyo3(signature = (storageLevel=None))]
+ /// Persist the DataFrame at `storageLevel`, as PySpark's
`DataFrame.persist()`:
+ /// MEMORY_AND_DISK_DESER when it is omitted, and no storage level for
None, so that the
+ /// server caches at its `spark.sql.defaultCacheStorageLevel`.
+ #[pyo3(signature =
(storageLevel=crate::storagelevel::PersistLevel::Omitted))]
fn persist<'py>(
slf: PyRef<'py, Self>,
py: Python<'py>,
- storageLevel: Option<Bound<'_, PyAny>>,
+ storageLevel: crate::storagelevel::PersistLevel,
) -> PyResult<PyRef<'py, Self>> {
- use spark_connect::storage::StorageLevelExt;
- let level = match storageLevel {
- Some(level) => crate::storagelevel::storage_level_proto(&level)?,
- None => spark_connect_proto::StorageLevel::memory_and_disk_deser(),
- };
+ let level = storageLevel.proto(py)?;
// As PySpark's, which returns the DataFrame itself.
let df = slf.dataframe.clone();
interruptible(py, &df.spark_session(), || {
diff --git a/crates/pyspark-rs/src/storagelevel.rs
b/crates/pyspark-rs/src/storagelevel.rs
index 494f6a72..24ec2244 100644
--- a/crates/pyspark-rs/src/storagelevel.rs
+++ b/crates/pyspark-rs/src/storagelevel.rs
@@ -119,6 +119,41 @@ pub(crate) fn storage_level_proto(
})
}
+/// The `storageLevel` argument of `DataFrame.persist`, where PySpark tells an
omitted one, its
+/// default `MEMORY_AND_DISK_DESER`, apart from a given None, for which its
client sends no storage
+/// level (`if kwargs.get("storage_level", None) is not None`), so that the
server caches at its
+/// `spark.sql.defaultCacheStorageLevel`.
+pub(crate) enum PersistLevel {
+ Omitted,
+ Given(Py<PyAny>),
+}
+
+impl<'a, 'py> FromPyObject<'a, 'py> for PersistLevel {
+ type Error = PyErr;
+
+ fn extract(obj: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
+ Ok(PersistLevel::Given(obj.to_owned().unbind()))
+ }
+}
+
+impl PersistLevel {
+ /// The storage level that `persist` sends: `MEMORY_AND_DISK_DESER` when
it is omitted, none
+ /// for None, and else the proto of [`storage_level_proto`].
+ pub(crate) fn proto(
+ &self,
+ py: Python<'_>,
+ ) -> PyResult<Option<spark_connect_proto::StorageLevel>> {
+ use spark_connect::storage::StorageLevelExt;
+ match self {
+ PersistLevel::Omitted => Ok(Some(
+ spark_connect_proto::StorageLevel::memory_and_disk_deser(),
+ )),
+ PersistLevel::Given(level) if level.is_none(py) => Ok(None),
+ PersistLevel::Given(level) =>
storage_level_proto(level.bind(py)).map(Some),
+ }
+ }
+}
+
#[pymethods]
impl PyStorageLevel {
/// As the `object.__new__` of PySpark's plain class: of any arguments,
which `__init__`
diff --git a/crates/spark-connect/src/dataframe.rs
b/crates/spark-connect/src/dataframe.rs
index 691cbaeb..a4c4c835 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -1580,17 +1580,30 @@ impl DataFrame {
self.persist(Self::memory_and_disk_deser())
}
- /// Persist this DataFrame with the given storage level.
+ /// Persist this DataFrame with the given storage level, or, of `None`,
with the server's
+ /// default, `spark.sql.defaultCacheStorageLevel`.
///
- /// Mirrors `pyspark.sql.DataFrame.persist(storageLevel)`.
- pub fn persist(&self, storage_level: proto::StorageLevel) ->
Result<DataFrame> {
+ /// Mirrors `pyspark.sql.DataFrame.persist(storageLevel)`, whose `None`
sends no storage
+ /// level.
+ pub fn persist(
+ &self,
+ storage_level: impl Into<Option<proto::StorageLevel>>,
+ ) -> Result<DataFrame> {
+ let request = self.persist_request(storage_level.into())?;
+ block_on(self.session.client().analyze_plan(request))?;
+ Ok(self.clone())
+ }
+
+ /// The request of [`Self::persist`], of no storage level for `None`.
+ fn persist_request(
+ &self,
+ storage_level: Option<proto::StorageLevel>,
+ ) -> Result<proto::AnalyzePlanRequest> {
let persist = proto::analyze_plan_request::Persist {
relation: Some(self.relation()?),
- storage_level: Some(storage_level),
+ storage_level,
};
- let request =
self.analyze_request(proto::analyze_plan_request::Analyze::Persist(persist));
- block_on(self.session.client().analyze_plan(request))?;
- Ok(self.clone())
+
Ok(self.analyze_request(proto::analyze_plan_request::Analyze::Persist(persist)))
}
/// Remove this DataFrame from cache. Mirrors
`DataFrame.unpersist(blocking)`.
@@ -5315,6 +5328,27 @@ mod plan_construction_tests {
.expect("failed to build session")
}
+ #[test]
+ fn persist_of_no_storage_level_sends_none_as_pyspark() {
+ // As PySpark's persist(None), which sends no storage level, so that
the server caches at
+ // spark.sql.defaultCacheStorageLevel; a storage level is sent as it
is given.
+ let df = session().range(1).unwrap();
+ let sent = |level: Option<proto::StorageLevel>| match
df.persist_request(level) {
+ Ok(proto::AnalyzePlanRequest {
+ analyze:
Some(proto::analyze_plan_request::Analyze::Persist(persist)),
+ ..
+ }) => persist.storage_level,
+ other => panic!("not a persist request: {other:?}"),
+ };
+ assert_eq!(sent(None), None);
+ let disk = proto::StorageLevel {
+ use_disk: true,
+ replication: 1,
+ ..Default::default()
+ };
+ assert_eq!(sent(Some(disk.clone())), Some(disk));
+ }
+
#[test]
fn
actions_of_a_plan_past_the_depth_bound_are_recursion_errors_without_a_request()
{
// Offline: the plan is refused before any request, so no server is
needed.
diff --git a/docs/compatibility.md b/docs/compatibility.md
index d6732368..da62d679 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -162,6 +162,11 @@ two runs, were equal. For reproducible values, use the
`_with_seed` variants
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.
+`DataFrame::persist` takes `impl Into<Option<StorageLevel>>`, so a
`StorageLevel` is passed
+as before. `None` sends no storage level, as PySpark's `persist(None)`, and
the server then
+caches at its `spark.sql.defaultCacheStorageLevel`. `cache` is unchanged and
persists at
+`MEMORY_AND_DISK_DESER`.
+
## Native LogisticRegression
The native `spark_connect::ml::LogisticRegression` fits Spark's JVM
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 25cdc9b7..2247394d 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -4760,6 +4760,22 @@ def
test_persist_cache_and_unpersist_return_the_dataframe_itself_as_pyspark(sess
df.unpersist()
+def
test_persist_of_none_caches_at_the_default_storage_level_of_the_server_as_pyspark(session):
+ # As PySpark's persist(None), which sends no storage level, so that the
server caches at its
+ # spark.sql.defaultCacheStorageLevel, while an omitted level is
MEMORY_AND_DISK_DESER.
+ from pyspark.storagelevel import StorageLevel
+
+ session.conf.set("spark.sql.defaultCacheStorageLevel", "DISK_ONLY")
+ given, omitted = session.range(5), session.range(6)
+ try:
+ assert given.persist(None) is given and given.storageLevel ==
StorageLevel.DISK_ONLY
+ assert omitted.persist().storageLevel ==
StorageLevel.MEMORY_AND_DISK_DESER
+ finally:
+ given.unpersist()
+ omitted.unpersist()
+ session.conf.unset("spark.sql.defaultCacheStorageLevel")
+
+
def test_values_of_local_rows_convert_and_raise_as_pyarrow(session):
# As PySpark Connect's: PyArrow takes the __int__ of a Decimal in an int
or a date field,
# raises its own errors, and takes the days of a date out of the dates of
Python, which
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index 8fe1936c..6e251c9f 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -1030,6 +1030,28 @@ def
test_storage_levels_are_converted_as_pyspark(mock_connect):
assert parse_message(_sent_catalog(service.execute_requests[-1],
19)[2][0]) == {2: [1], 5: [1]}
+def test_persist_of_none_sends_no_storage_level_as_pyspark(mock_connect):
+ # As PySpark's persist, whose omitted storageLevel is its default
MEMORY_AND_DISK_DESER,
+ # while its client sends no storage level for a given None (`if
kwargs.get("storage_level",
+ # None) is not None`), so that the server caches at its
spark.sql.defaultCacheStorageLevel.
+ from pyspark.storagelevel import StorageLevel
+
+ spark, service = mock_connect
+ df = spark.range(1)
+
+ def sent():
+ # AnalyzePlanRequest.persist=14 -> Persist.storage_level=2:
use_disk=1, use_memory=2,
+ # 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]) if 2 in persist else None
+
+ assert df.persist() is df and sent() == {1: [1], 2: [1], 4: [1], 5: [1]}
+ for call in (lambda: df.persist(None), lambda:
df.persist(storageLevel=None)):
+ assert call() is df and sent() is None
+ df.persist(StorageLevel.DISK_ONLY)
+ assert sent() == {1: [1], 5: [1]}
+
+
# ---------------------------------------------------------------------------
session builder
def test_session_builder_chaining_offline():
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]