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 2ca40e46 [SPARK-61333][CONNECT][PYTHON] Release pyspark.ml models 
whose summary keeps a DataFrame of them, as PySpark's garbage collector does
2ca40e46 is described below

commit 2ca40e4660afb3c0b05fdd4dea2872151a5e11dd
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 17:35:11 2026 +0900

    [SPARK-61333][CONNECT][PYTHON] Release pyspark.ml models whose summary 
keeps a DataFrame of them, as PySpark's garbage collector does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61333](https://issues.apache.org/jira/browse/SPARK-61333): a 
`pyspark.ml` model whose summary keeps a DataFrame of it is released, as 
PySpark's garbage collector releases it.
    
    - The native DataFrame of the Python drop-in 
(`crates/pyspark-rs/src/dataframe.rs`) gets garbage-collector support, 
`__traverse__` and `__clear__`:
      - `__traverse__` reports the Python objects that only this DataFrame 
keeps alive: the plans of `pyspark.ml` that `DataFrame(plan, session)` keeps.
      - `__clear__` drops the DataFrame's plan when the collector breaks a 
cycle.
    - The core gets two hidden helpers 
(`crates/spark-connect/src/dataframe.rs`):
      - `DataFrame::exclusive_relation_owners` returns the owners of the 
relations built outside the core that this DataFrame alone keeps. Every `Arc` 
from its plan down to the owner must be held once; an owner that another plan 
shares is not reported, so the collector never counts a reference twice.
      - `DataFrame::clear_plan`.
    - The collector can traverse an object while `object.__new__` is still 
creating it, because the allocation already tracks it and the instance 
dictionary is allocated before PyO3 writes the value. So `__traverse__` reads 
nothing until a flag that the constructor sets is set.
    
    ### Why are the changes needed?
    
    In the drop-in, a KMeans, BisectingKMeans or GaussianMixture model of 
`pyspark.ml` was never released on the server:
    - Every fit leaked one ML cache entry, until the session ended. Past the 
session's `maxStorageSize`, fits fail with `MLCacheSizeOverflowException`. Its 
client objects leaked too.
    - An elbow loop over k=2..5 left 4 models behind; official PySpark 4.3.0 
leaves none.
    
    The reason: these models keep `model.transform(dataset)` as the dataset of 
their summary, and its plan keeps the model (`__source_transformer__`).
    - PySpark's garbage collector frees that cycle, because its DataFrame is a 
Python object.
    - The drop-in's native DataFrame kept the Python plan through a Rust owner, 
which the collector could not see.
    - Other models (LogisticRegression, LinearSVC, ...) return the training 
dataset as their summary dataset, so they have no cycle.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, in the Python client: these models are released on the server once 
nothing uses them, as in PySpark. A DataFrame that still uses a model (a lazy 
transform, a DataFrame derived from its summary) keeps it.
    
    ### How was this patch tested?
    
    - Live (`python/tests/test_ml_e2e.py`): 
`test_models_whose_summary_keeps_their_transform_are_released_as_pyspark`.
      - KMeans, BisectingKMeans and GaussianMixture models leave the server's 
ML cache once deleted.
      - A model stays cached while a transform or a DataFrame derived from its 
summary is alive, and they still collect.
      - It fails without the change.
    - Offline (`python/tests/test_dropin_offline.py`): 
`test_cycles_through_a_dataframe_of_a_python_plan_are_collected_as_pyspark`.
      - With a collection at every allocation (`gc.set_threshold(1, 1, 1)`), 
cycles through DataFrames of Python plans are freed, and a derived DataFrame 
keeps its plan alive.
      - It fails without the change, and crashes the process (SIGSEGV in the 
collector) without the flag that guards objects still being created.
    - Rust (`plan_construction_tests`): 
`exclusive_relation_owners_are_those_only_this_dataframe_keeps`.
    - The reviewer's probe against official PySpark 4.3.0 now gives the same 
releases: `kmeans/bisecting/gmm del 0`, elbow loop `left 0`.
    - A stress run with `gc.set_threshold(1, 1, 1)` over chains of 
withColumn/filter/join and model fits and transforms released every model and 
did not crash.
    - Checks:
      - lib tests of both crates (717 passed);
      - the build of all tests (also `wasm-udf`, `datafusion,polars`) without 
warnings;
      - `cargo fmt --all --check`, and clippy with no diagnostics on the 
changed lines;
      - the offline Python suites (2980 passed, 8 skipped);
      - the live drop-in, Arrow and ML suites against a local Spark 4.3.0 
server (255 passed).
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #461 from HyukjinKwon/s16-dataframe-gc.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/dataframe.rs    | 31 +++++++++++++
 crates/spark-connect/src/dataframe.rs | 84 +++++++++++++++++++++++++++++++++++
 crates/spark-connect/src/plan.rs      |  2 +-
 python/tests/test_dropin_offline.py   | 47 ++++++++++++++++++++
 python/tests/test_ml_e2e.py           | 48 ++++++++++++++++++++
 5 files changed, 211 insertions(+), 1 deletion(-)

diff --git a/crates/pyspark-rs/src/dataframe.rs 
b/crates/pyspark-rs/src/dataframe.rs
index 6359ff82..5a0c3107 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -56,6 +56,11 @@ pub struct PyDataFrame {
     /// Whether `_repr_html_` was called, as PySpark's `_support_repr_html`: 
then `__repr__` is
     /// the string of the schema, so that a notebook does not show the 
DataFrame twice.
     support_repr_html: std::sync::atomic::AtomicBool,
+    /// Set once the value is written. Python's garbage collector may traverse 
the object while it
+    /// is created: the allocation already tracks it, and `object.__new__` 
allocates the instance
+    /// dictionary, which can start a collection, before PyO3 writes the 
value. Until then the
+    /// memory is zeroed, so this flag is false and `__traverse__` reads 
nothing else.
+    gc_ready: std::sync::atomic::AtomicBool,
 }
 
 /// The settings of the eager evaluation of `__repr__` and `_repr_html_`.
@@ -210,6 +215,7 @@ impl PyDataFrame {
         PyDataFrame {
             dataframe,
             support_repr_html: std::sync::atomic::AtomicBool::new(false),
+            gc_ready: std::sync::atomic::AtomicBool::new(true),
         }
     }
 
@@ -667,6 +673,31 @@ impl PyDataFrame {
         ))
     }
 
+    /// As a DataFrame of PySpark Connect, a Python object whose plan Python's 
garbage collector
+    /// sees: the Python objects that only this DataFrame keeps alive, the 
plans of `pyspark.ml`
+    /// that `DataFrame(plan, session)` keeps, are reported to the collector. 
So a reference cycle
+    /// through this DataFrame is freed, as PySpark frees it: a `pyspark.ml` 
model whose summary
+    /// keeps `model.transform(dataset)`, whose plan keeps the model, is 
released then.
+    fn __traverse__(&self, visit: pyo3::PyVisit<'_>) -> Result<(), 
pyo3::PyTraverseError> {
+        if !self.gc_ready.load(std::sync::atomic::Ordering::Relaxed) {
+            return Ok(());
+        }
+        for owner in self.dataframe.exclusive_relation_owners() {
+            if let Some(object) = owner.downcast_ref::<Py<PyAny>>() {
+                visit.call(object)?;
+            }
+        }
+        Ok(())
+    }
+
+    /// Break a reference cycle that the garbage collector found unreachable: 
the DataFrame drops
+    /// its plan, and so the Python objects that `__traverse__` reported.
+    fn __clear__(&mut self) {
+        if self.gc_ready.load(std::sync::atomic::Ordering::Relaxed) {
+            self.dataframe.clear_plan();
+        }
+    }
+
     /// The bytes of the relation of this DataFrame as it is sent, for the 
plan of `_plan`.
     fn _relation_bytes<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, 
pyo3::types::PyBytes>> {
         use prost::Message;
diff --git a/crates/spark-connect/src/dataframe.rs 
b/crates/spark-connect/src/dataframe.rs
index f5bd14cb..170f0724 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -1139,6 +1139,52 @@ impl DataFrame {
         Ok(DataFrame::from_raw_relation(session, relation, owner))
     }
 
+    /// The owners of the relations built outside the core (`from_relation`) 
that this DataFrame
+    /// alone keeps alive: every `Arc` from its plan down to such an owner is 
held once, by this
+    /// DataFrame. A Python wrapper reports them to Python's garbage 
collector, so that a
+    /// reference cycle through the wrapper can be freed, as through a 
DataFrame of PySpark
+    /// Connect, a Python object: a `pyspark.ml` model's summary keeps a 
DataFrame whose plan
+    /// keeps the model. An owner that another plan shares is not returned, so 
that the collector
+    /// does not count a reference twice. Not a stable API.
+    #[doc(hidden)]
+    pub fn exclusive_relation_owners(&self) -> Vec<&(dyn std::any::Any + Send 
+ Sync)> {
+        let mut owners = Vec::new();
+        if Arc::strong_count(&self.plan) != 1 {
+            return owners;
+        }
+        let mut pending: Vec<&LogicalPlan> = vec![self.plan.as_ref()];
+        while let Some(plan) = pending.pop() {
+            if let LogicalPlan::Raw {
+                owner: Some(owner), ..
+            } = plan
+            {
+                if Arc::strong_count(&owner.0) == 1 {
+                    owners.push(owner.0.as_ref());
+                }
+            }
+            pending.extend(
+                plan.inputs()
+                    .into_iter()
+                    .filter(|input| Arc::strong_count(input) == 1)
+                    .map(|input| input.as_ref()),
+            );
+        }
+        owners
+    }
+
+    /// Drop the plan of this DataFrame, which becomes an empty relation of 
its session: the
+    /// garbage collector of a Python wrapper breaks a reference cycle through 
the wrapper this
+    /// way, as it clears the references of a Python object. Not a stable API.
+    #[doc(hidden)]
+    pub fn clear_plan(&mut self) {
+        self.plan = Arc::new(LogicalPlan::Range {
+            start: 0,
+            end: 0,
+            step: 1,
+            num_partitions: None,
+        });
+    }
+
     /// The DataFrame of `relation`, as `from_relation`, of a relation without 
placeholders.
     fn from_raw_relation(
         session: SparkSession,
@@ -4584,6 +4630,44 @@ mod plan_construction_tests {
         }
     }
 
+    /// The owners of the relations built outside the core that only one 
DataFrame keeps are the
+    /// ones that a Python wrapper reports to the garbage collector: a 
relation that two plans
+    /// share is reported by neither, and a cleared plan keeps none.
+    #[test]
+    fn exclusive_relation_owners_are_those_only_this_dataframe_keeps() {
+        let spark = session();
+        let relation = proto::Relation {
+            common: None,
+            rel_type: Some(proto::relation::RelType::Sql(proto::Sql {
+                query: "SELECT 1 AS a".to_string(),
+                ..Default::default()
+            })),
+        };
+        let df = DataFrame::from_relation(spark.clone(), relation, 
Some(Arc::new(7u8))).unwrap();
+        let owners = df.exclusive_relation_owners();
+        assert_eq!(owners.len(), 1);
+        assert_eq!(owners[0].downcast_ref::<u8>(), Some(&7));
+
+        let derived = 
df.filter(crate::functions::col("a").gt(crate::column::lit(0)));
+        assert!(df.exclusive_relation_owners().is_empty());
+        assert!(derived.exclusive_relation_owners().is_empty());
+        drop(df);
+        assert_eq!(derived.exclusive_relation_owners().len(), 1);
+
+        let copy = derived.clone();
+        assert!(derived.exclusive_relation_owners().is_empty());
+        drop(copy);
+        let mut derived = derived;
+        assert_eq!(derived.exclusive_relation_owners().len(), 1);
+        derived.clear_plan();
+        assert!(derived.exclusive_relation_owners().is_empty());
+        assert!(spark
+            .range(3)
+            .unwrap()
+            .exclusive_relation_owners()
+            .is_empty());
+    }
+
     #[test]
     fn is_local_only_for_a_local_relation_itself() {
         let spark = session();
diff --git a/crates/spark-connect/src/plan.rs b/crates/spark-connect/src/plan.rs
index 8338e744..b9e8cfed 100644
--- a/crates/spark-connect/src/plan.rs
+++ b/crates/spark-connect/src/plan.rs
@@ -1097,7 +1097,7 @@ impl Drop for LogicalPlan {
 
 impl LogicalPlan {
     /// The plans that this one reads directly.
-    fn inputs(&self) -> Vec<&Arc<LogicalPlan>> {
+    pub(crate) fn inputs(&self) -> Vec<&Arc<LogicalPlan>> {
         inputs_of!(self)
     }
 
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 014669bf..0403953c 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -12789,6 +12789,53 @@ def 
test_ml_plans_send_a_deep_dataframe_without_parsing_it_as_pyspark(mock_conne
         DataFrame(Gone(None), spark)
 
 
+def 
test_cycles_through_a_dataframe_of_a_python_plan_are_collected_as_pyspark(mock_connect):
+    # As PySpark's DataFrame, a Python object: a cycle through a DataFrame of 
a Python plan, whose
+    # plan keeps an object that keeps the DataFrame (as a pyspark.ml model 
keeps its summary's
+    # model.transform(dataset)), is freed by the garbage collector, while a 
DataFrame derived from
+    # it keeps the plan alive. With a collection at every allocation, the 
collector also meets
+    # DataFrames that are still being created, before their value is written.
+    import gc
+    import weakref
+
+    from pyspark.sql.connect.dataframe import DataFrame
+    from pyspark.sql.connect.plan import LogicalPlan
+
+    spark, _ = mock_connect
+    source = spark.range(3)
+    relation = source._plan.plan(spark.client)
+
+    class Owner:
+        pass
+
+    class Plan(LogicalPlan):
+        def plan(self, session):
+            return relation
+
+    def cycle():
+        owner, plan = Owner(), Plan(None)
+        plan.owner = owner
+        owner.frame = DataFrame(plan, spark)
+        return weakref.ref(owner)
+
+    thresholds = gc.get_threshold()
+    gc.set_threshold(1, 1, 1)
+    try:
+        collected = [cycle() for _ in range(20)]
+        kept = cycle()
+        derived = kept().frame.select("id").filter("id > 0")
+        for _ in range(20):
+            spark.range(3).select("id").filter("id > 0")
+    finally:
+        gc.set_threshold(*thresholds)
+    gc.collect()
+    assert all(owner() is None for owner in collected)
+    assert kept() is not None
+    del derived
+    gc.collect()
+    assert kept() is None
+
+
 @pytest.mark.parametrize("schema", [
     T.StructType([]),
     T.StructType([T.StructField("x", T.LongType()), T.StructField("y", 
T.LongType())]),
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 28cbc4f9..b0518ee2 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -171,6 +171,54 @@ def 
test_session_clients_release_and_close_as_pyspark(session):
     assert client.is_closed and other.is_stopped
 
 
+def 
test_models_whose_summary_keeps_their_transform_are_released_as_pyspark(session):
+    # As PySpark: the summary of a KMeans, BisectingKMeans or GaussianMixture 
model keeps
+    # model.transform(dataset), whose plan keeps the model. Python's garbage 
collector frees that
+    # cycle, and the model is released on the server, once nothing else uses 
the model; a
+    # DataFrame that still uses it keeps it.
+    import gc
+    import time
+
+    from pyspark.ml.clustering import BisectingKMeans, GaussianMixture, KMeans
+    from pyspark.ml.linalg import Vectors
+
+    def cached(model):
+        return model._java_obj.ref_id in 
"\n".join(session.client._get_ml_cache_info())
+
+    def released(ref_id):
+        for _ in range(50):
+            gc.collect()
+            if ref_id not in "\n".join(session.client._get_ml_cache_info()):
+                return True
+            time.sleep(0.1)
+        return False
+
+    data = session.createDataFrame(
+        [(Vectors.dense(x, y),) for x, y in [(0, 0), (0.1, 0.2), (9, 9), (9.1, 
9.2)]],
+        ["features"])
+    for estimator in [KMeans(k=2, seed=1), BisectingKMeans(k=2, seed=1),
+                      GaussianMixture(k=2, seed=1, maxIter=3)]:
+        model = estimator.fit(data)
+        ref_id = model._java_obj.ref_id
+        assert cached(model) and model.summary.k == 2
+        del model
+        assert released(ref_id), type(estimator).__name__
+
+    model = KMeans(k=2, seed=1).fit(data)
+    ref_id = model._java_obj.ref_id
+    transformed = model.transform(data)
+    derived = model.summary.predictions.select("prediction")
+    del model
+    gc.collect()
+    assert ref_id in "\n".join(session.client._get_ml_cache_info())
+    assert len(transformed.collect()) == 4 and len(derived.collect()) == 4
+    del transformed
+    gc.collect()
+    assert len(derived.collect()) == 4
+    del derived
+    assert released(ref_id)
+
+
 def test_ml_feature_transformers_as_pyspark(session):
     from pyspark.ml.feature import IDF, HashingTF, MinMaxScaler, Tokenizer
 


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to