HyukjinKwon opened a new pull request, #537: URL: https://github.com/apache/spark-connect-rust/pull/537
### 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 (`AtomicType`, `IntegerType`, `ArrayType`, `StructType`, ...). - 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 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. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
