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 4afc8468 [SPARK-61490][CONNECT][PYTHON] Release the instance dict of 
the Python client's PyO3 classes when they are freed, which PyO3 0.28 keeps
4afc8468 is described below

commit 4afc8468cda639d380ed1a1a7884d4e50b583542
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 12:20:00 2026 +0900

    [SPARK-61490][CONNECT][PYTHON] Release the instance dict of the Python 
client's PyO3 classes when they are freed, which PyO3 0.28 keeps
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61490](https://issues.apache.org/jira/browse/SPARK-61490): The 
instances of the Python client's Rust-backed classes that have a `__dict__` 
release it when they are freed, as instances of PySpark's plain Python classes 
do.
    
    - A new module, `crates/pyspark-rs/src/instance_dict.rs`. Its 
`release_instance_dicts`, called at the end of the module init in 
`crates/pyspark-rs/src/lib.rs`, wraps the `tp_dealloc` of each class whose 
instances have the dict. These are the 28 `#[pyclass(dict)]` classes (`Column`, 
`SparkSession`, `DataFrame`, `GroupedData`, `RuntimeConf`, `Catalog`, the 
readers and writers, `Observation`, `DataType`, `StructField`, `WindowSpec`, 
...) and the 36 classes that extend `DataType` in Rust  [...]
    - The wrapper takes the dict out of its slot (at the class's 
`__dictoffset__`), runs PyO3's own dealloc, which then finds no dict, and then 
drops the dict. So the dict is released after the instance and its weak 
references are gone, in the order of CPython's `subtype_dealloc`.
    - Each class has its own small wrapper and a `OnceLock` with PyO3's dealloc 
and the dict offset, so freeing an instance does no lookup.
    - A Python subclass, such as a UDT, keeps the dict slot of its base, and 
CPython's `subtype_dealloc` calls the base's `tp_dealloc`, so it is covered.
    - A class that extends another in Rust has a `tp_dealloc` of its own, which 
runs its bases' Rust dealloc directly, so each one is wrapped.
    - The extension is built for the limited API (`abi3-py39`), where 
`PyTypeObject` is opaque. The module reads the slot with `PyType_GetSlot(type, 
Py_tp_dealloc)`. It writes the field at its standard offset (after 
`PyObject_VAR_HEAD`, `tp_name`, `tp_basicsize` and `tp_itemsize`) only if the 
field holds exactly the pointer that `PyType_GetSlot` returned. Otherwise it 
leaves the class as it is.
    - The module is to be removed after the upgrade to PyO3 0.29. Left in 
place, it is harmless there: 0.29's own `Py_CLEAR` of the dict then finds the 
slot empty.
    - AGENTS.md, section 15, gets the lesson next to the "Value classes" bullet.
    
    Nothing else changes. The dict is CPython's instance dict, as before, so 
attribute lookup, `vars()`, `dir()`, deletion and monkeypatched methods (the 
instance dict before non-data descriptors) behave as before. There is no 
`__getattr__`/`__setattr__` store and no change on attribute access.
    
    ### Why are the changes needed?
    
    PyO3 0.28.3 never releases the `__dict__` of a `#[pyclass(dict)]` instance.
    
    - Its dealloc, `PyClassObjectContents::dealloc` 
(src/pycell/impl_.rs:367-373), calls `self.dict.clear_dict(py)`.
    - That is `PyDict_Clear` of the dict (src/impl_/pyclass.rs:101). The 
reference is never dropped.
    - PyO3 0.29.3 calls `release_dict` there instead (src/pycell/impl_.rs:437), 
a `Py_CLEAR` (src/impl_/pyclass.rs:131).
    - PyO3 cannot be upgraded here: arrow-pyarrow 58.3.0 pins PyO3 0.28, and 
pyo3-ffi's `links = "python"` forbids two versions.
    
    So every freed instance whose dict was ever made kept an empty dict: an 
attribute set, `vars()`, `dir()`, a monkeypatched method, or a `__reduce__` 
that reads it, as a UDT's does.
    
    Memory that 20,000 instances keep once freed, in bytes (tracemalloc, after 
`gc.collect()`), when each is given one attribute and when none is. It is the 
same for a RuntimeConf, an ArrayType, a bare DataType, a UDT and an 
Observation; a Column and a GroupedData are within 31 KB of it.
    
    | Client | Python | Given an attribute | Given none |
    |---|---|---|---|
    | master | 3.11.8 | 2,560,032 | 1,280,032 |
    | this PR | 3.11.8 | 1,280,032 | 1,280,032 |
    | PySpark 4.3.0 | 3.11.8 | 32 | 32 |
    | master | 3.13.0 | 1,280,032 | 32 |
    | this PR | 3.13.0 | 32 | 32 |
    
    Python 3.9 behaves as 3.13, and 3.12 as 3.11. The 1,280,032 bytes that 3.11 
and 3.12 keep for instances given no attribute are a separate leak, which this 
PR cannot fix (see below).
    
    PyO3 0.28's dealloc also differed from CPython's in two ways. A dict that 
was still referenced when its instance was freed (`d = vars(obj); del obj`) was 
emptied, while CPython keeps its items. And its `PyDict_Clear` freed the 
attributes within the dealloc itself, outside CPython's trashcan, so freeing a 
long chain of instances linked through attributes overflowed the C stack:
    
    - A chain of 100,000 Columns, each an attribute of the next, crashed the 
interpreter with a segmentation fault on master, on the main thread and on 
another one.
    - 50,000 did not crash.
    - This PR and PySpark free 300,000. The dict is now dropped with 
`Py_DECREF`, whose `dict_dealloc` uses the trashcan.
    
    #### Not fixed here: the dict that `object.__new__` makes on CPython 3.11 
and 3.12
    
    Tracked as 
[SPARK-61492](https://issues.apache.org/jira/browse/SPARK-61492): the upgrade 
to PyO3 0.29, which arrow-pyarrow 58.3.0 blocks today (it pins pyo3 0.28).
    
    On 3.11 and 3.12, `object.__new__` makes the dict eagerly for every 
instance of a type with a `tp_dictoffset` (`_PyObject_InitializeDict`). PyO3 
0.28 then writes the fields of the instance over the slot 
(`create_class_object_of_type` writes `PyClassObjectContents::new`, whose dict 
is null, src/pyclass_init.rs:156). So that dict is lost at creation: 64 bytes 
for every instance of these classes, with an attribute or without.
    
    - A probe that called `object.__new__` on `Column` found a dict in the slot 
on 3.11.8 and 3.12.4, and none on 3.13.0.
    - PyO3 0.29.3 carries that dict over into the instance 
(src/pyclass_init.rs:161-185).
    - No code of the extension runs between `object.__new__` and that write, so 
only the PyO3 upgrade can fix it. Moving the dict to a slot after PyO3's fields 
would avoid the write, but PyO3's own `__dict__` getter (of abi3-py39) reads 
PyO3's field, and the fields of the Rust subclasses of `DataType` start where 
that slot would be.
    
    The new module's doc comment and AGENTS.md record this.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, in the Python client, as in PySpark:
    
    - Freed instances of these classes and of their Python subclasses no longer 
keep their dict. On CPython 3.9 and 3.13 they keep nothing, as PySpark's; on 
3.11 and 3.12 each keeps 64 bytes instead of 128 (the dict lost at creation, 
above).
    - A dict that is still referenced when its instance is freed keeps its 
items.
    - A long chain of instances linked through attributes is freed instead of 
crashing the interpreter.
    
    ### How was this patch tested?
    
    - New offline tests in `python/tests/test_dropin_offline.py`, right after 
`test_variant_and_spatial_values_are_sent_and_collected_by_their_attributes_as_pyspark`:
      - `test_freed_instances_release_their_dict_as_pyspark`:
        - An attribute is set, read, listed by `vars()` and `dir()`, and 
deleted.
        - A monkeypatched `Column.alias` and `DataFrame.count` are called in 
place of the methods until they are deleted.
        - A UDT's dict pickles and copies (`pickle`, `copy.copy`, 
`copy.deepcopy`).
        - Then 14 kinds of instances are each given an attribute and freed 
(checked with a weakref): a Column, a DataFrame, a GroupedData, a RuntimeConf, 
a Catalog, a DataFrameReader, a DataFrameNaFunctions, a DataFrameWriter, a 
WindowSpec, an Observation, a StructField, a bare DataType, an ArrayType and a 
UDT. The dict that `vars()` returned keeps its items, and its reference count 
drops by one.
      - `test_freed_instances_given_attributes_keep_no_memory_as_pyspark`: 
tracemalloc over 20,000 create/free cycles, each instance given an attribute, 
of a Column, a GroupedData, an ArrayType, a UDT and an Observation. They keep 
under 20,000 bytes; on 3.11 and 3.12, under 20,000 bytes more than as many 
instances given no attribute keep (the dict lost at creation, above).
      - 
`test_freed_instances_free_a_deep_chain_of_their_attributes_as_pyspark`: a new 
interpreter frees a chain of 300,000 Columns linked through attributes.
    - Without the fix (the hook in `lib.rs` reverted by hand, which leaves the 
new module out of the build, then rebuilt), all three fail on 3.11.8:
      - `{} == {'tag': [1]}`;
      - `assert (2560101 - 1304458) < 20000`;
      - `(-11, '') == (0, 'freed\n')`, a segmentation fault.
      - On 3.13.0 the first two fail the same way (`assert (1285034 - 0) < 
20000`).
    - With the fix, they pass on 3.11.8, 3.12.4 and 3.13.0. Probes of the same 
release and memory checks pass on 3.9.23 too, which has no pytest here.
    - Other probes, with the fix: a `__del__` of a UDT subclass with 
`__slots__` sees its dict, and a weakref callback runs; 4 threads each create 
and free 50,000 StructFields given an attribute; a replaced `__dict__` is 
released. A reference cycle through an instance's dict (`c.me = c`) is still 
not collected, as before: PyO3 0.28 does not visit the dict in its GC 
traversal, which this PR leaves alone.
    - The whole offline suite, `tests/test_dropin_offline.py 
tests/test_arrow_handoff.py tests/test_ml_offline.py`, on 3.11: 3128 passed, 8 
skipped.
    - The live suites, `tests/test_arrow_e2e.py tests/test_dropin_e2e.py 
tests/test_ml_e2e.py`, against a local Spark 4.3.0 Connect server: 292 passed.
    - Official PySpark 4.3.0 test files, run on the drop-in against the same 
server, with this PR and without it: `pyspark/sql/tests/connect/` 
`test_parity_types.py`, `test_parity_column.py`, `test_connect_column.py`, 
`test_parity_observation.py`, `test_parity_conf.py`, `test_parity_catalog.py`, 
`test_parity_group.py`, `test_parity_window.py`, `test_parity_serde.py` and 
`test_parity_readwriter.py`.
      - Both: 347 passed, 57 skipped and one failure, `test_metadata_column`, 
whose catalog plugin `testcat` this server lacks.
      - `test_observe_str` failed once with this PR, while a cargo build loaded 
the machine: its 10-second `eventually` timed out before the first streaming 
progress. It passed when rerun, and the server log shows the query stopped at 
the session's teardown.
    - Timings on 3.11, 5 alternating runs of each build, in ns per operation 
(the minimum and the median of the runs, each the best of 7 `timeit` repeats). 
The attribute paths do not change, and creating and freeing a Column costs the 
same within noise:
    
      | Operation | master, min / median | this PR, min / median |
      |---|---|---|
      | read an instance attribute (`c.tag`) | 34.7 / 36.0 | 31.1 / 33.5 |
      | look up a method (`c.alias`) | 50.1 / 52.4 | 47.1 / 49.3 |
      | read a Rust getter (`field.name`) | 60.5 / 63.3 | 62.4 / 66.6 |
      | write an instance attribute (`c.tag = 2`) | 25.5 / 26.2 | 25.4 / 27.6 |
      | create and free a Column (`F.col("a")`) | 457.6 / 471.5 | 459.4 / 482.1 
|
      | create a Column, set an attribute, free it | 521.8 / 542.0 | 519.4 / 
522.2 |
    
    - `cargo fmt --all --check`.
    - `cargo clippy -p pyspark-rs --release --all-targets` reports nothing in 
`instance_dict.rs` or `lib.rs`. Its findings are all in files that this PR does 
not touch.
    - `cargo test -p apache-spark-connect --release --no-run`, also with 
`--features wasm-udf`, builds without warnings.
    - `ruff check python/tests/test_dropin_offline.py`.
    
    ### 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 #537 from HyukjinKwon/SPARK-61490-release-instance-dicts.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 AGENTS.md                              |  11 ++
 crates/pyspark-rs/src/instance_dict.rs | 227 +++++++++++++++++++++++++++++++++
 crates/pyspark-rs/src/lib.rs           |   5 +
 python/tests/test_dropin_offline.py    | 106 +++++++++++++++
 4 files changed, 349 insertions(+)

diff --git a/AGENTS.md b/AGENTS.md
index 64b91595..ce370c37 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -431,6 +431,17 @@ For every method matching a pyspark name:
   their attributes are the instance attributes of PySpark's, as given, and 
they pickle as plain
   classes into the server's Python workers. Do not make them 
`#[pyclass(dict)]` types: PyO3 0.28
   clears but never releases the `__dict__` of such an instance, so each value 
would keep a dict.
+- **Instance dicts of `#[pyclass(dict)]` classes:** PyO3 0.28's dealloc 
empties the `__dict__` of
+  an instance (`PyDict_Clear`) but never releases it. 
`crates/pyspark-rs/src/instance_dict.rs`
+  wraps, at module init, the `tp_dealloc` of each class whose instances have 
the dict: the wrapper
+  takes the dict out of its slot, runs PyO3's dealloc and then releases the 
dict, so the attribute
+  semantics stay CPython's (a `__getattr__`/`__setattr__` store instead would 
break the lookup
+  order of monkeypatched methods and slow every access). List there every new 
`dict` class and
+  every class that `extends` one, whose Rust dealloc does not go through its 
base's slot; Python
+  subclasses go through it. On CPython 3.11 and 3.12, PyO3 0.28 also writes 
over the dict that
+  `object.__new__` makes for every instance of such a class, which no code 
outside PyO3 can reach:
+  a `dict` class still costs a dict per instance there (hence the value 
classes above) until the
+  PyO3 0.29 upgrade, after which the module is to be removed.
 - **Streaming listeners and progress holders:** Keep progress holders 
(`StreamingQueryProgress`,
   `StateOperatorProgress`, etc.) as faithful pure-Python implementations 
parsed from server
   JSON, not Rust-backed. The listener bus (subscribe/dispatch) is genuinely 
Rust-backed;
diff --git a/crates/pyspark-rs/src/instance_dict.rs 
b/crates/pyspark-rs/src/instance_dict.rs
new file mode 100644
index 00000000..eb4c0e82
--- /dev/null
+++ b/crates/pyspark-rs/src/instance_dict.rs
@@ -0,0 +1,227 @@
+//! The release of the instance `__dict__` of the `#[pyclass(dict)]` classes, 
which PyO3 0.28
+//! does not do when an instance is freed.
+//!
+//! PySpark's classes are plain Python classes, whose instance `__dict__` 
CPython releases with
+//! the instance. PyO3 0.28's dealloc of an instance of a `dict` class empties 
the dict
+//! (`PyDict_Clear` in `PyClassObjectContents::dealloc`) but keeps its 
reference to it, so every
+//! instance whose dict was made, by an attribute set, `vars()`, `dir()`, a 
monkeypatched method
+//! or a `__reduce__` that reads it, leaves its dict behind. PyO3 0.29 
releases it
+//! (`release_dict`, a `Py_CLEAR`), but it cannot be used here, as 
arrow-pyarrow pins PyO3 0.28.
+//!
+//! So [`release_instance_dicts`] wraps, at module init, the `tp_dealloc` of 
each class whose
+//! instances have the dict. The wrapper takes the dict out of its slot, runs 
PyO3's dealloc,
+//! which then finds no dict, and releases the dict once the instance is gone, 
as CPython's
+//! `subtype_dealloc` releases it after the weak references are cleared. Its 
items are then freed
+//! by `dict_dealloc`, under CPython's trashcan: PyO3's `PyDict_Clear` freed 
them within the
+//! dealloc, so that freeing a long chain of instances, each an attribute of 
the next, overflowed
+//! the C stack. Only that changes: the dict is still CPython's instance dict, 
which its attribute
+//! lookup reads and writes as before, and freeing an instance, with a dict or 
without, costs a
+//! call and a few loads more.
+//!
+//! A Python subclass keeps the dict slot of its base, and CPython's 
`subtype_dealloc` calls the
+//! `tp_dealloc` of the base, so it is covered. A class that `extends` another 
in Rust has a
+//! `tp_dealloc` of its own, which runs the Rust dealloc of its bases 
directly, so it is wrapped
+//! too: a new `dict` class, or a class that extends one, belongs in the list 
below.
+//!
+//! On CPython 3.11 and 3.12, PyO3 0.28 also loses the dict that 
`object.__new__` makes for each
+//! instance of these classes, as it writes the fields of the instance over 
it. No code of the
+//! extension runs in between, so only PyO3 0.29 fixes that one 
(`create_class_object_of_type`).
+//!
+//! Remove this module after the upgrade to PyO3 0.29 or later. Left in place, 
it is harmless
+//! there: PyO3's own `Py_CLEAR` then finds the slot empty.
+
+use std::ffi::{c_char, c_void};
+use std::sync::OnceLock;
+
+use pyo3::ffi;
+use pyo3::intern;
+use pyo3::prelude::*;
+use pyo3::types::PyType;
+
+use crate::catalog::PyCatalog;
+use crate::column::PyColumn;
+use crate::conf::PyRuntimeConf;
+use crate::dataframe::{
+    PyDataFrame, PyDataFrameNaFunctions, PyDataFrameWriter, 
PyDataFrameWriterV2, PyMergeIntoWriter,
+};
+use crate::datasource::PyDataSourceRegistration;
+use crate::group::{PyCoGroupedData, PyGroupedData};
+use crate::observation::PyObservation;
+use crate::readwriter::PyDataFrameReader;
+use crate::resource::{
+    PyExecutorResourceRequests, PyResourceProfile, PyResourceProfileBuilder, 
PyTaskResourceRequests,
+};
+use crate::session::PySparkSession;
+use crate::stat::PyStatFunctions;
+use crate::streaming::{
+    PyDataStreamReader, PyDataStreamWriter, PyStreamingQuery, 
PyStreamingQueryManager,
+};
+use crate::tablearg::PyTableArg;
+use crate::tvf::PyTableValuedFunction;
+use crate::types::{
+    PyAnsiIntervalType, PyAnyTimeType, PyArrayType, PyAtomicType, 
PyBinaryType, PyBooleanType,
+    PyByteType, PyCalendarIntervalType, PyCharType, PyDataType, PyDateType, 
PyDatetimeType,
+    PyDayTimeIntervalType, PyDecimalType, PyDoubleType, PyFloatType, 
PyFractionalType,
+    PyGeographyType, PyGeometryType, PyIntegerType, PyIntegralType, 
PyLongType, PyMapType,
+    PyNullType, PyNumericType, PyShortType, PySpatialType, PyStringType, 
PyStructField,
+    PyStructType, PyTimeType, PyTimestampLTZNanosType, 
PyTimestampNTZNanosType, PyTimestampNTZType,
+    PyTimestampType, PyVarcharType, PyVariantType, PyYearMonthIntervalType,
+};
+use crate::window::PyWindowSpec;
+
+/// Where `tp_dealloc` is in CPython's `PyTypeObject`: after 
`PyObject_VAR_HEAD`, `tp_name`,
+/// `tp_basicsize` and `tp_itemsize`, as in every CPython 3. The limited API 
keeps the struct
+/// opaque, so the field is written only where it holds what `PyType_GetSlot` 
reads for it.
+const TP_DEALLOC_OFFSET: usize =
+    size_of::<ffi::PyVarObject>() + size_of::<*const c_char>() + 2 * 
size_of::<ffi::Py_ssize_t>();
+
+/// What the wrapper of a class needs, as `tp_dealloc` gets only the instance.
+struct Hook {
+    /// The `tp_dictoffset` of the class, which its Python subclasses keep.
+    dict_offset: ffi::Py_ssize_t,
+    /// PyO3's `tp_dealloc` of the class.
+    dealloc: ffi::destructor,
+}
+
+/// Wraps the `tp_dealloc` of each class with a wrapper and a hook of its own.
+macro_rules! release_dicts_of {
+    ($py:expr; $($class:ty),+ $(,)?) => {$({
+        static HOOK: OnceLock<Hook> = OnceLock::new();
+        unsafe extern "C" fn dealloc(obj: *mut ffi::PyObject) {
+            // SAFETY: CPython calls it for an instance of the class, or of a 
Python subclass.
+            unsafe { release_dict_and_dealloc(obj, &HOOK) }
+        }
+        wrap_dealloc(&$py.get_type::<$class>(), &HOOK, dealloc)?;
+    })+};
+}
+
+/// Makes the instances of the classes with a `__dict__`, the `dict` classes 
and those that
+/// extend one, release their dict when they are freed, as instances of Python 
classes do.
+pub(crate) fn release_instance_dicts(py: Python<'_>) -> PyResult<()> {
+    release_dicts_of!(py;
+        PyCatalog,
+        PyColumn,
+        PyRuntimeConf,
+        PyDataFrame,
+        PyDataFrameNaFunctions,
+        PyMergeIntoWriter,
+        PyDataFrameWriter,
+        PyDataFrameWriterV2,
+        PyDataSourceRegistration,
+        PyGroupedData,
+        PyCoGroupedData,
+        PyObservation,
+        PyDataFrameReader,
+        PyExecutorResourceRequests,
+        PyTaskResourceRequests,
+        PyResourceProfileBuilder,
+        PyResourceProfile,
+        PySparkSession,
+        PyStatFunctions,
+        PyDataStreamReader,
+        PyDataStreamWriter,
+        PyStreamingQuery,
+        PyStreamingQueryManager,
+        PyTableArg,
+        PyTableValuedFunction,
+        PyStructField,
+        PyWindowSpec,
+        // `DataType` and the classes that extend it, which keep its dict.
+        PyDataType,
+        PyAtomicType,
+        PyNumericType,
+        PyIntegralType,
+        PyFractionalType,
+        PyDatetimeType,
+        PyAnyTimeType,
+        PyAnsiIntervalType,
+        PySpatialType,
+        PyNullType,
+        PyBooleanType,
+        PyByteType,
+        PyShortType,
+        PyIntegerType,
+        PyLongType,
+        PyFloatType,
+        PyDoubleType,
+        PyDecimalType,
+        PyStringType,
+        PyBinaryType,
+        PyDateType,
+        PyTimestampType,
+        PyTimestampNTZType,
+        PyTimestampNTZNanosType,
+        PyTimestampLTZNanosType,
+        PyArrayType,
+        PyMapType,
+        PyStructType,
+        PyCharType,
+        PyVarcharType,
+        PyTimeType,
+        PyCalendarIntervalType,
+        PyYearMonthIntervalType,
+        PyDayTimeIntervalType,
+        PyVariantType,
+        PyGeometryType,
+        PyGeographyType,
+    );
+    Ok(())
+}
+
+/// Installs `wrapper` as the `tp_dealloc` of `class`, once its hook is set. A 
class without an
+/// instance dict at a fixed offset, or whose type object is not laid out as 
CPython's, is left
+/// as it is.
+fn wrap_dealloc(
+    class: &Bound<'_, PyType>,
+    hook: &'static OnceLock<Hook>,
+    wrapper: ffi::destructor,
+) -> PyResult<()> {
+    let py = class.py();
+    let dict_offset: ffi::Py_ssize_t = class.getattr(intern!(py, 
"__dictoffset__"))?.extract()?;
+    if dict_offset <= 0 || hook.get().is_some() {
+        return Ok(());
+    }
+    let ty = class.as_type_ptr();
+    // SAFETY: `ty` is a type object, pointer aligned and larger than 
`TP_DEALLOC_OFFSET` plus a
+    // pointer; the field is written only if it holds the `tp_dealloc` that 
CPython reports.
+    unsafe {
+        let dealloc = ffi::PyType_GetSlot(ty, ffi::Py_tp_dealloc);
+        if dealloc.is_null() {
+            drop(PyErr::take(py));
+            return Ok(());
+        }
+        let field = ty.cast::<u8>().add(TP_DEALLOC_OFFSET).cast::<*mut 
c_void>();
+        if field.read() != dealloc {
+            return Ok(());
+        }
+        let wrapped = Hook {
+            dict_offset,
+            dealloc: std::mem::transmute::<*mut c_void, 
ffi::destructor>(dealloc),
+        };
+        if hook.set(wrapped).is_ok() {
+            field.write(wrapper as *mut c_void);
+        }
+    }
+    Ok(())
+}
+
+/// Runs PyO3's dealloc of `obj` without its dict, which it would empty and 
keep, and then
+/// releases the dict, once the instance and its weak references are gone.
+///
+/// # Safety
+/// `obj` is an instance being freed, of the class of `hook` or of a Python 
subclass of it.
+#[inline(always)]
+unsafe fn release_dict_and_dealloc(obj: *mut ffi::PyObject, hook: 
&OnceLock<Hook>) {
+    let Some(hook) = hook.get() else {
+        // The wrapper is installed only after its hook is set.
+        std::process::abort()
+    };
+    unsafe {
+        let slot: *mut *mut ffi::PyObject = 
obj.byte_offset(hook.dict_offset).cast();
+        let dict = slot.replace(std::ptr::null_mut());
+        (hook.dealloc)(obj);
+        if !dict.is_null() {
+            ffi::Py_DECREF(dict);
+        }
+    }
+}
diff --git a/crates/pyspark-rs/src/lib.rs b/crates/pyspark-rs/src/lib.rs
index 5b155550..24640522 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -19,6 +19,7 @@ mod eval_type;
 mod functions;
 mod group;
 mod infer;
+mod instance_dict;
 mod interrupt;
 mod ml;
 mod observation;
@@ -239,5 +240,9 @@ fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) -> 
PyResult<()> {
     functions::register_functions(_py, &functions_module)?;
     m.add_submodule(&functions_module)?;
 
+    // The instances of the classes with a `__dict__` release it when they are 
freed, which
+    // PyO3 0.28 does not do (see `instance_dict`).
+    instance_dict::release_instance_dicts(_py)?;
+
     Ok(())
 }
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 863e5692..ca459079 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -7564,6 +7564,112 @@ def 
test_variant_and_spatial_values_are_sent_and_collected_by_their_attributes_a
     assert type(row.g) is T.Geometry and vars(row.g) == {"wkb": wkb, "srid": 0}
 
 
+def test_freed_instances_release_their_dict_as_pyspark(mock_connect):
+    # As PySpark's classes, plain Python classes, whose instance __dict__ 
CPython releases with
+    # the instance: an attribute is set, read, listed by vars() and dir() and 
deleted; one that
+    # shadows a method, as monkeypatching sets it, is called in its place 
until it is deleted;
+    # and a freed instance releases its dict, which keeps its items while it 
is referenced. Of
+    # a class, of one that extends it in Rust (ArrayType) and of a Python 
subclass (a UDT), whose
+    # dict pickles and copies. PyO3 0.28 emptied the dict of a freed instance 
and kept it.
+    import copy
+    import sys
+    import weakref
+
+    from pyspark.sql import functions as F
+    from pyspark.sql.observation import Observation
+    from pyspark.sql.window import Window
+
+    spark, _ = mock_connect
+    df = spark.range(1)
+    column = F.col("a")
+    column.tag = 1
+    assert column.tag == 1 and vars(column) == {"tag": 1} and "tag" in 
dir(column)
+    del column.tag
+    assert vars(column) == {}
+    column.alias = lambda *names: "patched"
+    df.count = lambda: 42
+    assert column.alias("b") == "patched" and df.count() == 42
+    del column.alias, df.count
+    assert repr(column.alias("b")) == "Column<'a AS b'>" and df.count.__self__ 
is df
+    udt = _ScaledPointUDT(2.0)
+    for copied in (pickle.loads(pickle.dumps(udt)), copy.copy(udt), 
copy.deepcopy(udt)):
+        assert type(copied) is _ScaledPointUDT and vars(copied) == {"scale": 
2.0}
+
+    for make in (lambda: F.col("a"), lambda: spark.range(1), lambda: 
df.groupBy("id"),
+                 lambda: spark.conf, lambda: spark.catalog, lambda: 
spark.read, lambda: df.na,
+                 lambda: df.write, lambda: Window.partitionBy("id"), lambda: 
Observation("o"),
+                 lambda: T.StructField("a", T.LongType()), T.DataType,
+                 lambda: T.ArrayType(T.LongType()), lambda: 
_ScaledPointUDT(2.0)):
+        obj = make()
+        obj.tag = [1]
+        attributes, freed = vars(obj), weakref.ref(obj)
+        expected, references = dict(attributes), sys.getrefcount(attributes)
+        del obj
+        assert freed() is None and attributes == expected
+        assert sys.getrefcount(attributes) == references - 1
+
+
+def 
test_freed_instances_given_attributes_keep_no_memory_as_pyspark(mock_connect):
+    # As PySpark's classes, plain Python classes: 20,000 instances, each given 
an attribute,
+    # keep next to nothing once freed (PySpark's, 32 bytes): of a Column, a 
GroupedData of the
+    # session, a DataType, a UDT (a Python subclass of DataType) and an 
Observation. PyO3 0.28
+    # kept the emptied dict of each, 64 bytes. On CPython 3.11 and 3.12, PyO3 
0.28 also loses
+    # the dict that object.__new__ makes for each instance, which only PyO3 
0.29 fixes: there,
+    # the memory that as many instances given no attribute keep is the base.
+    import gc
+    import sys
+    import tracemalloc
+
+    from pyspark.sql import functions as F
+    from pyspark.sql.observation import Observation
+
+    spark, _ = mock_connect
+    df = spark.range(1)
+
+    def kept(make, attribute):
+        gc.collect()
+        tracemalloc.start()
+        try:
+            before = tracemalloc.get_traced_memory()[0]
+            for _ in range(20_000):
+                obj = make()
+                if attribute:
+                    obj.tag = 1
+                del obj
+            gc.collect()
+            return tracemalloc.get_traced_memory()[0] - before
+        finally:
+            tracemalloc.stop()
+
+    eager_dicts = sys.version_info[:2] in ((3, 11), (3, 12))
+    for make in (lambda: F.col("a"), lambda: df.groupBy("id"), lambda: 
T.ArrayType(T.LongType()),
+                 _DayPointUDT, lambda: Observation("o")):
+        make().tag = 1  # What a first instance caches is no leak.
+        base = kept(make, False) if eager_dicts else 0
+        assert kept(make, True) - base < 20_000
+
+
+def test_freed_instances_free_a_deep_chain_of_their_attributes_as_pyspark():
+    # As PySpark's classes, whose instances CPython frees through its 
trashcan: a chain of
+    # 300,000 Columns, each an attribute of the next, is freed. PyO3 0.28 
emptied the dict of each
+    # in its dealloc, which freed the next one within it, until the C stack 
overflowed. In a new
+    # interpreter, as that crashed it.
+    import subprocess
+    import sys
+
+    freed = subprocess.run([sys.executable, "-c", """
+from pyspark.sql import functions as F
+head = None
+for _ in range(300_000):
+    column = F.col("a")
+    column.next = head
+    head = column
+del column, head
+print("freed")
+"""], capture_output=True, text=True, timeout=300)
+    assert (freed.returncode, freed.stdout) == (0, "freed\n"), freed.stderr
+
+
 def test_str_of_variant_values_is_their_json_and_they_are_no_rows_as_pyspark():
     # As PySpark's VariantVal: str is its JSON, in UTC, as toJson(); repr is 
of its bytes. And
     # as PySpark's createDataFrame, whose VariantVal has a __dict__, so that 
it is a row, which


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

Reply via email to