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 3d364f1f [SPARK-61237][CONNECT][PYTHON] Release the relation of a
checkpointed DataFrame on the server when its last DataFrame is dropped, as
PySpark does
3d364f1f is described below
commit 3d364f1fb45423ee37da7f990d95b774344d6076
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Mon Nov 9 20:42:54 2026 +0900
[SPARK-61237][CONNECT][PYTHON] Release the relation of a checkpointed
DataFrame on the server when its last DataFrame is dropped, as PySpark does
### What changes were proposed in this pull request?
[SPARK-61237](https://issues.apache.org/jira/browse/SPARK-61237): Release
the relation of a checkpointed DataFrame on the server when its last DataFrame
is dropped, as PySpark does.
- `checkpoint()` and `localCheckpoint()` (and their `_with` variants) now
attach a reference to the checkpoint's `CachedRemoteRelation` plan. The plans
derived from it (`select`, `filter`, `join`, ...) keep the reference alive
through their inputs. When the last such plan is dropped, the reference sends
`RemoveCachedRemoteRelationCommand` for the relation id, without waiting for
the server. Its errors are ignored, and nothing is sent when the session is
stopped or its client is closed.
- `LogicalPlan::CachedRemoteRelation` gets an `owner:
Option<RelationOwner>` field, as `LogicalPlan::Raw` and the ML plans have.
`plan::cached_remote_relation(id)` keeps its signature and has no owner. This
is a change to a public enum variant: the workspace callers (`plan.rs`,
`dataframe.rs`) are updated, and no examples or other crates match on it.
- Official PySpark 4.3.0 does the same in `CachedRemoteRelation.__del__`
(`sql/connect/plan.py`). Checked on the same server: after `del` of a
`localCheckpoint()` DataFrame and of its derived DataFrame, and `gc.collect()`,
reading the relation id gives `CONNECT_INVALID_PLAN.DATAFRAME_NOT_FOUND`, and
the derived DataFrame counts 7 rows while the checkpoint is gone. The drop-in
now gives the same results.
- The other places that build a CachedRemoteRelation
(`cached_remote_relation(id)`, and the `foreachBatch` worker's
`_create_remote_dataframe` in PySpark) do not create a checkpoint, so they keep
no owner. The Rust client has no foreachBatch worker path.
### Why are the changes needed?
A checkpointed relation stayed on the server, with its data, until the
session ended, whatever happened to its DataFrames. A loop such as `for i in
range(n): df = df.localCheckpoint()` grew the server's state by one relation
per iteration. Official PySpark releases the relation when the DataFrame is
garbage-collected, so the behavior differed from PySpark.
### Does this PR introduce _any_ user-facing change?
Yes. A checkpointed relation is removed on the server when its last
DataFrame is dropped, as in PySpark. Derived DataFrames keep working while the
checkpoint is alive. The Rust `LogicalPlan::CachedRemoteRelation` variant has a
new `owner` field (see above).
### How was this patch tested?
- Rust e2e, `crates/spark-connect/tests/e2e_dataframe.rs`, before
`subqueries_return_the_rows_of_pyspark`:
- `a_dropped_checkpoint_releases_its_relation_on_the_server`: after the
`local_checkpoint()` DataFrame is dropped, its relation (taken with
`to_relation()`) is polled until reading it fails with
`CONNECT_INVALID_PLAN.DATAFRAME_NOT_FOUND` (60 s bound). Without the fix the
relation stays readable and the test fails. Official PySpark 4.3.0 gives the
same result for the same case.
- `a_checkpoint_stays_while_a_dataframe_derived_from_it_is_alive`: a
`filter` over the checkpoint still counts 3 after the checkpoint is dropped,
the relation is still readable, and it is released once the derived DataFrame
is dropped too. Official PySpark 4.3.0 gives the same results.
- `checkpoint()` (reliable) is not covered: the test server has no
checkpoint directory, and the server rejects it with "Checkpoint directory has
not been set in the SparkContext".
- Python e2e, `python/tests/test_dropin_e2e.py`, before
`test_to_pandas_converts_the_columns_as_pyspark`:
`test_a_derived_dataframe_of_a_local_checkpoint_outlives_the_checkpoint_as_pyspark`
checks that a derived DataFrame of `localCheckpoint()` still counts and
collects after `del` of the checkpoint and `gc.collect()`. This is a guard
against releasing too early, so it passes without the fix too; the release
itself is checked by the Rust tests above and by a manual probe of the drop-i
[...]
- The offline test
`test_checkpoints_send_their_eager_and_storage_level_as_pyspark`
(`python/tests/test_dropin_offline.py`) now reads the last `CheckpointCommand`
among the requests, since a dropped checkpoint sends its removal in the
background too, and checks that its six dropped checkpoints each send
`RemoveCachedRemoteRelationCommand` for their relation (deterministic, against
the mock server).
- The live Rust tests `e2e_dataframe` (6 passed), `e2e_new_methods` (7
passed) and `e2e_coverage` (25 passed) against a local Spark 4.3.0 server.
- The lib tests of both crates (664 passed), the build of all tests, also
with `wasm-udf`, the offline Python suites (2819 passed, 8 skipped), and the
live drop-in and Arrow suites (234 passed) and live cases (13 passed) against a
local Spark 4.3.0 server. Clippy reports no diagnostics in the changed lines.
### 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 #419 from HyukjinKwon/SPARK-61237-checkpoint-release.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/spark-connect/src/dataframe.rs | 22 ++++++++++-
crates/spark-connect/src/plan.rs | 13 ++++--
crates/spark-connect/src/session.rs | 27 +++++++++++++
crates/spark-connect/tests/e2e_dataframe.rs | 61 +++++++++++++++++++++++++++++
python/tests/test_dropin_e2e.py | 12 ++++++
python/tests/test_dropin_offline.py | 28 +++++++++++--
6 files changed, 155 insertions(+), 8 deletions(-)
diff --git a/crates/spark-connect/src/dataframe.rs
b/crates/spark-connect/src/dataframe.rs
index bdda219c..aac9ad53 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -11,13 +11,28 @@ use spark_connect_proto as proto;
use crate::column::Column;
use crate::expression::{Expression, ExpressionNode};
-use crate::plan::{AggregateGroupType, JoinType, LogicalPlan, SetOpType};
+use crate::plan::{AggregateGroupType, JoinType, LogicalPlan, RelationOwner,
SetOpType};
use crate::progress::ExecutionStream;
use crate::row::{Row, StructValue, Value};
use crate::session::{ExecutionInfo, SparkSession};
use crate::types::DataType;
use crate::udf::CommonInlineUserDefinedFunctionExpression;
+/// The server's checkpointed relation, shared by the plans of a checkpoint
and of every DataFrame
+/// derived from it (through their [`RelationOwner`]). The last one to drop
removes the relation
+/// on the server, as PySpark's `CachedRemoteRelation.__del__` does.
+struct CheckpointRef {
+ relation_id: String,
+ session: SparkSession,
+}
+
+impl Drop for CheckpointRef {
+ fn drop(&mut self) {
+ self.session
+ .release_cached_remote_relation(self.relation_id.clone());
+ }
+}
+
/// A Spark DataFrame, lazily evaluated.
///
/// Mirrors `pyspark.sql.DataFrame`.
@@ -1405,10 +1420,15 @@ impl DataFrame {
&resp.response_type
{
if let Some(rel) = &res.relation {
+ let checkpoint = CheckpointRef {
+ relation_id: rel.relation_id.clone(),
+ session: self.session.clone(),
+ };
return Ok(DataFrame::new(
self.session.clone(),
LogicalPlan::CachedRemoteRelation {
relation_id: rel.relation_id.clone(),
+ owner: Some(RelationOwner(Arc::new(checkpoint))),
},
));
}
diff --git a/crates/spark-connect/src/plan.rs b/crates/spark-connect/src/plan.rs
index d675a4ca..098b5bdb 100644
--- a/crates/spark-connect/src/plan.rs
+++ b/crates/spark-connect/src/plan.rs
@@ -297,8 +297,14 @@ pub enum LogicalPlan {
data_hashes: Vec<String>,
schema_hash: Option<String>,
},
- /// CachedRemoteRelation: a reference to a cached remote relation.
- CachedRemoteRelation { relation_id: String },
+ /// CachedRemoteRelation: a reference to a cached remote relation, such as
the result of
+ /// `checkpoint()`. The owner, if any, keeps the relation alive on the
server while any
+ /// plan of it is alive, and removes it when the last one drops, as
PySpark's
+ /// `CachedRemoteRelation.__del__` does.
+ CachedRemoteRelation {
+ relation_id: String,
+ owner: Option<RelationOwner>,
+ },
/// A relation the server returned, such as the result of
`SparkSession::sql`, sent back
/// as is (pyspark's `CachedRelation`).
CachedRelation { relation: Box<proto::Relation> },
@@ -1518,7 +1524,7 @@ impl LogicalPlan {
relation.rel_type =
Some(proto::relation::RelType::LocalRelation(local));
}
- LogicalPlan::CachedRemoteRelation { relation_id } => {
+ LogicalPlan::CachedRemoteRelation { relation_id, .. } => {
let mut cached = proto::CachedRemoteRelation::default();
cached.relation_id = relation_id.clone();
relation.rel_type =
Some(proto::relation::RelType::CachedRemoteRelation(cached));
@@ -2407,6 +2413,7 @@ pub fn local_relation(schema: DataType, data:
Option<Vec<u8>>) -> LogicalPlan {
pub fn cached_remote_relation(relation_id: impl Into<String>) -> LogicalPlan {
LogicalPlan::CachedRemoteRelation {
relation_id: relation_id.into(),
+ owner: None,
}
}
diff --git a/crates/spark-connect/src/session.rs
b/crates/spark-connect/src/session.rs
index 8e86a7fd..d8d87e7a 100644
--- a/crates/spark-connect/src/session.rs
+++ b/crates/spark-connect/src/session.rs
@@ -828,6 +828,33 @@ impl SparkSession {
)),
})),
};
+ self.execute_command_in_background(command);
+ }
+
+ /// Remove the cached remote relation `relation_id` on the server, as
PySpark's
+ /// `CachedRemoteRelation.__del__` does when its DataFrame goes. Like
`release_ml_objects`,
+ /// it does not wait for the server, and its errors are ignored. A stopped
session is not
+ /// released: stopping it released its server state already, as PySpark
skips a closed
+ /// client. Safe to call from `Drop`.
+ pub(crate) fn release_cached_remote_relation(&self, relation_id: String) {
+ if self.is_stopped() {
+ return;
+ }
+ let command = proto::Command {
+ command_type: Some(
+ proto::command::CommandType::RemoveCachedRemoteRelationCommand(
+ proto::RemoveCachedRemoteRelationCommand {
+ relation: Some(proto::CachedRemoteRelation {
relation_id }),
+ },
+ ),
+ ),
+ };
+ self.execute_command_in_background(command);
+ }
+
+ /// Execute `command` on the server without waiting for its responses, on
the shared
+ /// runtime. Its errors are ignored; safe to call from `Drop`.
+ fn execute_command_in_background(&self, command: proto::Command) {
let mut plan = proto::Plan::default();
plan.op_type = Some(proto::plan::OpType::Command(command));
let request = proto::ExecutePlanRequest {
diff --git a/crates/spark-connect/tests/e2e_dataframe.rs
b/crates/spark-connect/tests/e2e_dataframe.rs
index da4c312e..1f359d42 100644
--- a/crates/spark-connect/tests/e2e_dataframe.rs
+++ b/crates/spark-connect/tests/e2e_dataframe.rs
@@ -428,6 +428,67 @@ fn int_pairs(df: &DataFrame) -> Vec<(i32, i32)> {
pairs
}
+/// Reads `relation` as a DataFrame, polling until the server no longer has
it, as a release
+/// sent without waiting takes effect. Returns the condition of the error the
read fails with.
+fn wait_until_relation_is_released(s: &SparkSession, relation:
&spark_connect_proto::Relation) {
+ let deadline = std::time::Instant::now() +
std::time::Duration::from_secs(60);
+ loop {
+ if let Err(error) = DataFrame::from_sent_relation(s.clone(),
relation.clone()).count() {
+ assert_eq!(
+ error.get_condition().as_deref(),
+ Some("CONNECT_INVALID_PLAN.DATAFRAME_NOT_FOUND"),
+ "the released relation is not found: {error}"
+ );
+ return;
+ }
+ assert!(
+ std::time::Instant::now() < deadline,
+ "the server still has the relation of the dropped checkpoint"
+ );
+ std::thread::sleep(std::time::Duration::from_millis(200));
+ }
+}
+
+#[test]
+fn a_dropped_checkpoint_releases_its_relation_on_the_server() {
+ // As PySpark's CachedRemoteRelation.__del__: the last DataFrame of a
checkpoint that is
+ // dropped removes the relation on the server, and only then is it gone.
+ if !should_run() {
+ return;
+ }
+ let s = session();
+ // checkpoint() needs a checkpoint directory, which the test server does
not set.
+ let checkpoint = s.range(5).unwrap().local_checkpoint().unwrap();
+ let relation = checkpoint.to_relation();
+ assert_eq!(checkpoint.count().unwrap(), 5);
+ drop(checkpoint);
+ wait_until_relation_is_released(&s, &relation);
+}
+
+#[test]
+fn a_checkpoint_stays_while_a_dataframe_derived_from_it_is_alive() {
+ // The derived DataFrame keeps the checkpoint alive: it still counts after
the checkpoint
+ // itself is dropped, and the relation is released only once the derived
one is dropped.
+ if !should_run() {
+ return;
+ }
+ let s = session();
+ let checkpoint = s.range(5).unwrap().local_checkpoint().unwrap();
+ let relation = checkpoint.to_relation();
+ let derived = checkpoint.filter(col("id").gt(lit(1)));
+ drop(checkpoint);
+ assert_eq!(derived.count().unwrap(), 3);
+ assert_eq!(
+ DataFrame::from_sent_relation(s.clone(), relation.clone())
+ .count()
+ .unwrap(),
+ 5,
+ "the relation is still on the server while the derived DataFrame lives"
+ );
+ drop(derived);
+ wait_until_relation_is_released(&s, &relation);
+}
+
#[test]
fn subqueries_return_the_rows_of_pyspark() {
// As PySpark's DataFrame.scalar(), DataFrame.exists() and
Column.isin(df): scalar,
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 3cfc13e4..35c37b18 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -2856,6 +2856,18 @@ def
test_to_arrow_casts_to_the_arrow_schema_of_the_schema_as_pyspark(session):
session.sql("SELECT named_struct('a', 1, 'a', 2) AS v").toArrow()
assert e.value.getCondition() == "DUPLICATED_FIELD_NAME_IN_ARROW_STRUCT"
+def
test_a_derived_dataframe_of_a_local_checkpoint_outlives_the_checkpoint_as_pyspark(session):
+ # The checkpoint is released when its last DataFrame goes: a DataFrame
derived from it keeps
+ # working after the checkpoint itself is deleted and collected.
+ import gc
+
+ checkpoint = session.range(5).localCheckpoint()
+ derived = checkpoint.filter(F.col("id") > 1)
+ del checkpoint
+ gc.collect()
+ assert derived.count() == 3
+ assert [row.id for row in derived.orderBy("id").collect()] == [2, 3, 4]
+
def test_to_pandas_converts_the_columns_as_pyspark(session):
# As official PySpark 4.3.0's SparkConnectClient.to_pandas: each column by
its Spark type,
# in the session time zone, with the metrics of the execution in attrs.
diff --git a/python/tests/test_dropin_offline.py
b/python/tests/test_dropin_offline.py
index b35f2d7b..c742d855 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -808,11 +808,15 @@ def
test_checkpoints_send_their_eager_and_storage_level_as_pyspark(mock_connect)
# ExecutePlanResponse.checkpoint_command_result=19 -> relation=1 ->
relation_id=1.
service.execute_payload = message_field(19, message_field(1,
message_field(1, "r1")))
+ def commands():
+ # ExecutePlanRequest.plan=3 -> Plan.command=2.
+ plans = (parse_message(parse_message(r)[3][0]) for r in
list(service.execute_requests))
+ return [parse_message(plan[2][0]) for plan in plans if 2 in plan]
+
def sent():
- # ExecutePlanRequest.plan=3 -> Plan.command=2 ->
Command.checkpoint_command=14: local=2,
- # eager=3, storage_level=4, where false is not sent.
- plan = parse_message(parse_message(service.execute_requests[-1])[3][0])
- return parse_message(parse_message(plan[2][0])[14][0])
+ # The last Command.checkpoint_command=14: local=2, eager=3,
storage_level=4, where false
+ # is not sent. (A dropped checkpoint also sends its removal, in the
background.)
+ return parse_message([command for command in commands() if 14 in
command][-1][14][0])
df = spark.range(1)
for checkpoint, local, eager in ((lambda: df.checkpoint(), [], [1]),
@@ -828,6 +832,22 @@ def
test_checkpoints_send_their_eager_and_storage_level_as_pyspark(mock_connect)
df.localCheckpoint(True, StorageLevel(False, True, True, True, 2))
assert parse_message(sent()[4][0]) == {2: [1], 3: [1], 4: [1], 5: [2]}
+ # The six checkpoints were dropped at once, and each removed its relation,
as PySpark's
+ # CachedRemoteRelation.__del__ does:
Command.remove_cached_remote_relation_command=15 ->
+ # relation=1 -> relation_id=1. They are sent in the background, so wait
for them.
+ import gc
+ import time
+
+ def removed():
+ return [parse_message(parse_message(command[15][0])[1][0])[1]
+ for command in commands() if 15 in command]
+
+ gc.collect()
+ deadline = time.monotonic() + 60
+ while len(removed()) < 6 and time.monotonic() < deadline:
+ time.sleep(0.05)
+ assert removed() == [[b"r1"]] * 6
+
def
test_persist_cache_and_unpersist_return_the_dataframe_itself_as_pyspark(mock_connect):
# As PySpark's, which persist the plan of the DataFrame and return it, not
a copy.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]