pyo3: Unexpected memory management behavior
I’m very excited about this library. The effort going into documentation and ergonomics is fantastic. I’ve been waiting to use it on stable Rust for months, and have finally started trying to integrate it into my CPU-bound Python codebase to write extension modules.
Right now, pyo3 seems to have a serious issue to me. The use of the object storage (even the lighter #887 implementation) means that this library is not zero-cost, and worse, can easily leak memory. The additional management layer that’s built on top of Python’s own reference counting, while ergonomic, is a big problem for my use-case.
The current situation, as I understand it:
-
GilGuardacquire overhead (minimal, and rare):- Acquire a
Mutexon thePyObjectalloc/dealloc array. - Allocate a
Vecto copy thePyObjectalloc/dealloc array out of TLS. - Write to 2x thread-local storage.
- Allocate two
Vecfor storing pointers to owned references.
- Acquire a
-
&PyAnyowned reference creation (mostly method returns, cheap, but very frequent):- Write to thread-local storage.
- Occasionally re-alloate owned reference
Vecsas they grow. - Memory is only freed at GilGuard drop
-
PyObjectdrop (cheap, but frequent):- Read from thread-local storage.
- Possibly acquire a
Mutexon the dealloc array. - Possibly only free memory at next
GitGuardacquire
The regular access to TLS and global mutexes are regrettable, but the memory-freeing behavior is really worrying to me. I’m not writing Python extensions because I want pretty-damn fast and unbounded memory growth. I’m going to the effort of writing a Python extension because I need as fast as possible and predictable memory usage.
The solution outlined in #885 seems perfect. A PyAny<'a> has no need for object storage, and Clone and Drop work as one would expect. I’d even go one stage further and have PyObject and Py<T> always acquire the GIL for Clone and Drop. Sure, it’s slower than using the current TLS and deferred drop, but it’s simpler, more predictable, and people can always use ManuallyDrop turn them back into PyAny<'a> to batch clone/drop if performance is suffering.
You could even remove the mirrored object API on PyObject and require that they’re converted into PyAny<'a> to call or getattr, making PyObject’s only purpose to be storing a long-term reference to a Python object between GIL acquisitions.
At that point, there’s no additional global state beyond what’s already provided by the Python interpreter. Things are deallocated predictably. There’s a smaller API surface. The library is truly zero-cost and adds no additional complexity.
I would urge you to be bold with making breaking changes while the library is young and the userbase relatively small. It would be a trememdous shame if the most popular Rust/Python bindings were significantly slower than the equivalent C, and introduced an unexpected additional memory model.
In any case, thanks for all the work you’ve put in so far. 😃
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Reactions: 4
- Comments: 21 (13 by maintainers)
Commits related to this issue
- Add a section on memory management for `extension` Adding a special case of memory management when writing an extension. This is a documentation of: https://github.com/PyO3/pyo3/issues/1056 and ht... — committed to haixuanTao/pyo3 by haixuanTao 4 years ago
- Add a section on memory management for `extension` Adding a special case of memory management when writing an extension. This is a documentation of: https://github.com/PyO3/pyo3/issues/1056 and ht... — committed to haixuanTao/pyo3 by haixuanTao 4 years ago
- Merge #2864 2864: Add a section on memory management for `extension` r=davidhewitt a=haixuanTao Adding a special case of memory management when writing an extension. This is a documentation of: h... — committed to PyO3/pyo3 by bors[bot] 4 years ago
Incredible, I’ve been watching and hoping for a long while for this to be sorted! I’m really glad it was included for 1.0. ❤️
To me, the imporant things to get right for this library are, in order:
Currently, 1 and 4 are pretty well nailed, but 2 and 3 are both being held back by object storage. Here’s my attempt at a solution that does away with all thread locals and object storage.
The first part of the solution is already solved by the current
PyAny(zero-cost wrapper around a pointer) andPyDict,PyList(zero-cost wrapper around a pointer that asserts a native type). The change I’d make is that a user never interacts with&PyAnyor&PyDictdirectly.Instead, these are always wrapped by either:
PyRef<'py, T>(e.g.PyRef<'py, PyAny>orPyRef<'py, PyDict>'pylifetime is tied toPython<'py>, so guarantees that the GIL is held.CloneandDropperform immediate refcount incr/decr.Derefimpl toTfor easy.call(...)andgetattr(...)etc.PyOwned<T>(e.g.PyOwned<PyAny>orPyOwned<PyDict>)CloneandDropacquire the GIL and perform immediate refcount incr/decr, then drop the GIL again. This is not efficient, but it keeps the memory model predictable and correct. People can use.into_ref(...)(below) for efficient batch clone and drop..into_ref(self, py: Python<'py>)method consumes thePyOwned<T>and returns aPyRef<'py, T>..as_ref(&self, py: Python<'py>)method does not consume thePyOwned<T>, and returns a&'py T(the only time a user ever deals with a&'py Tdirectly. I’m not 100% sure about the lifetimes here, or whether it would actually work. Maybe.clone().into_ref(py)is more correct, at the expese of a refcount.I believe this does away with all thread locals and all object storage, and brings the performance and memory characteristics in line with the equivalent C.
I’d be happy to have a go at this myself, but I don’t want to step on other people’s toes, or spend time on something that isn’t wanted, or has already been tried and found problematic.
With the release of the Bound API in 0.21 (beta), there is finally a resolution to this problem. 🎉
Migrating to the Bound API will solve this problem immediately for code which needs this fixed, and the follow-up to this work is #3960 to remove the existing GIL Refs API.
@etianen thanks for all the ideas. I agree that the direction I want for PyO3 is to remove as much object storage as possible.
TLDR; Yes, I like this design and have considered it myself, but I’m not sure it’s the right time to do it.
I’ve thought many times about ideas similar to your
PyOwned<T>/PyRef<'a, T>combination. Note that your proposal forPyOwned<T>is more or less exactly what the currentPy<T>is, except for the drop semantics. (PyObjectis very similar toPy<PyAny>, and I’d like to remove it, but haven’t quite found the appropriate way to do it given how PyO3’s conversion traits work currently.)Regarding
PyRef<'a, T>- again, this is an API that I’ve considered moving towards. It fits nicely asPyRefis already a name we use for#[pyclass], and the meaning would be essentially the same for native types (except “refcell” semantics wouldn’t be needed for native types).Why I’m not sure now is the moment.
The biggest downside of
PyRef<'py, T>with current Rust, is that the GIL lifetime'pyisn’t perfectly preserved over multiple calls. Consider, for example, this method definition which we would adopt if we switched toPyRef<'py, T>:If
PyRef<'py, PyAny>derefs to&'a PyAnyfor the method call, then this lifetime'ais not the original GIL lifetime'py. Instead,'ais the lifetime of the derefencing borrow. So as far as Rust is concerned the result of the method call is borrowed from the original receiver. This is obviously wrong!The result of this is that a series of chained PyO3 API calls gradually see the GIL lifetime which the compiler guarantees get narrower and narrower. It’s not the end of the world, but it’s quite an annoying papercut.
The future solution I see
There is, fortunately, a way that I can see this being resolved in the future: arbitrary self types. If we were able to use
&PyRef<'py, T>as a self type, then this problem goes away:With arbitrary self types, we really can have our cake and eat it! So this is a direction which I would like to see for PyO3, but I’m not actively pursuing it now because we need someone to champion getting the feature added to the Rust language first!
Thanks. I think it’s good timing to revisit our object model now, since recently some safety problems are pointed out aroung GILGuard. Let me create the 2nd draft.